Я пытаюсь создать простую программу, которая попросит пользователя ввести возраст, а затем попросит пользователя ввести другой возраст, чтобы найти разницу.
Проблема в моей программе возникает, когда я прошу пользователя подтвердить свой возраст.
Когда я прошу пользователя подтвердить возраст, если пользователь отвечает, подтверждая свой выбор, я хочу, чтобы программа продолжала работать. Но в настоящее время я застрял в цикле, когда даже если пользователь вводит подтверждение, программа пропускает мой оператор 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.')
and
подразумевает, что yourWish
ДОЛЖНО быть "Yes"
, "yes"
, "y"
, "Y"
одновременно, что невозможно. Вам нужно использовать or
вместо and
. Это означает, что выполнить цикл, если какое-либо из условий равно True
Вы можете протестировать его более компактно с помощью if yourWish.lower() in {'yes', 'y'}:
То, что Тьерри использует с {'yes', 'y'}
, является set
, если вам интересно.
Верно! Это полностью пролетело над моей головой, ха-ха. Большое спасибо, ребята, которые решили мою проблему.
Я слышал о наборах, но я думаю, что я просто видел их слишком сложными для реализации, но теперь я начну использовать их чаще, поскольку они очищают и делают программу более компактной. Спасибо всем еще раз.
@ThierryLathuille Извините, что беспокою вас, но что именно делает «in»? Я изучил преимущества использования ".lower()", а затем внедрил его в свою программу. Затем я попробовал программу без «в», и она не работала, но с «в» она работала. Является ли «в» по существу «или»?
Были некоторые ошибки отступа, и вы использовали ключевое слово и вместо ключевого слова или вот рабочий код
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" or yourWish == "yes" or yourWish == "y" or 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 yourWish == 'yes' or yourWish == 'Yes':
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()
choose()
choose()
print('Goodbye.')
Вы имеете в виду, если ваше желание == "Да" или ваше желание == "да" или... ваше желание не может быть одновременно, только одно или другое.