我在Python中有一个问题,我想做一个while循环,并要求玩家输入骰子的数量和进行随机骰子滚动的边数。在第二个循环和任何其他循环我想问他们是否愿意继续。如果他们输入' n'或者没有'程序退出。
我能够使用全局变量来处理这个逻辑,并在第一次调用它之后在我的函数中更改该变量,这样第二次会询问用户是否要继续,但是根据我的理解使用全局变量像这样的变量不是一种非常类似Python的方式。我想改进这个。
以下代码有效,但永远不会提示用户退出。我知道这是因为它们变量在while循环开始时仍然设置为True,但我不知道如何设置标志而不诉诸全局变量。
如何在本地(非全局)设置True / False变量并使用它来控制程序中的流程?
import sys
import random
def get_user_input(first_loop):
if not first_loop:
another_time = input("Would you like to roll another time?")
if another_time.lower() in ['n', 'no']:
sys.exit()
# This allows the code above to output on additional loops.
first_loop = False
return first_loop
while True:
# How do I not reset this back to True each time the program loops?
first_loop = True
get_user_input(first_loop)
number_of_dice = int(input("Enter the number of dice you would like to roll: "))
number_of_sides = int(input("Enter the number of sides for the dice: "))
# create the dice_total list so each time we create a roll in the loop,
# it can be added to a list and the total calculated
dice_total = []
for die in range(number_of_dice):
random_roll = random.randrange(1, number_of_sides)
print("You rolled: ", random_roll)
dice_total.append(random_roll)
dice_total = sum(dice_total)
print("The total of the dice rolled is: ", dice_total)
答案 0 :(得分:2)
你非常接近。
# move this outside the loop
first_loop = True
while True:
if not first_loop:
get_user_input()
first_loop = False
无需在first_loop
函数本身中使用get_user_input
:
def get_user_input():
another_time = input("Would you like to roll another time?")
if another_time.lower() in ['n', 'no']:
sys.exit()
最好返回True
/ False
并相应地采取行动,而不是在函数中使用sys.exit
(为您提供更多控制权):
def get_user_input():
another_time = input("Would you like to roll another time?")
return not another_time.lower() in ['n', 'no']
然后你可以这样做:
while True:
if not first_loop:
if not get_user_input():
# break out of the loop
break
答案 1 :(得分:1)
您可以将变量放在list
中。这将允许您在get_user_input()
函数中更改其值,并避免使其成为全局变量。
import sys
import random
def get_user_input(first_loop):
if not first_loop[0]: # access value in the list
another_time = input("Would you like to roll another time?")
if another_time.lower() in ['n', 'no']:
sys.exit()
# This allows the code above to output on additional loops.
first_loop[0] = False
return first_loop[0] # access value in the list
while True:
# How do I not reset this back to True each time the program loops?
first_loop = [True] # change to a list
get_user_input(first_loop)
number_of_dice = int(input("Enter the number of dice you would like to roll: "))
number_of_sides = int(input("Enter the number of sides for the dice: "))
# create the dice_total list so each time we create a roll in the loop,
# it can be added to a list and the total calculated
dice_total = []
for die in range(number_of_dice):
random_roll = random.randrange(1, number_of_sides)
print("You rolled: ", random_roll)
dice_total.append(random_roll)
dice_total = sum(dice_total)
print("The total of the dice rolled is: ", dice_total)