【发布时间】:2020-12-12 18:43:56
【问题描述】:
我正在尝试创建一个简单的程序,它会要求用户输入年龄,然后要求用户输入另一个年龄以找出差异。
当我要求用户确认他们的年龄时,我的程序中出现了问题。
当我要求用户确认年龄时,如果用户回答确认他们的选择,我希望程序继续运行。但目前,我陷入了一个循环,即使用户输入确认,程序也会跳过我的if 语句并始终运行我的else: 语句。
#This program will prompt you to state your age and then will proceed to
#calculate how long till __ age
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" and yourWish == "yes" and yourWish == "y" and yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if desiredAge == 'yes' and desiredAge == 'Yes':
print(Yes())
else:
No()
choose()
print('Goodbye.')
【问题讨论】:
-
你的意思是如果 yourWish == "Yes" or yourWish == "yes" or... yourWish 不可能是全部同时,只有一个或另一个。
-
and意味着yourWish应该是"Yes"、"yes"、"y"、"Y",这是不可能的。您需要使用or而不是and。这意味着如果任何条件为True则执行循环 -
你可以用
if yourWish.lower() in {'yes', 'y'}:更简洁地测试它 -
Thierry 与
{'yes', 'y'}一起使用的是set,以防您想知道。 -
对!那完全飞过我的头哈哈。非常感谢你们解决了我的问题。
标签: python python-3.x if-statement input