0 python
所以我对python很新,但在创建基本的Yes或No输入时遇到了一些麻烦.我希望能够做一些事情,如果用户说是,如果用户说不做则做其他事情,并重复问题,如果用户输入的内容不是或不是.这是我的代码:
def yes_or_no():
YesNo = input("Yes or No?")
YesNo = YesNo.lower()
if(YesNo == "yes"):
return 1
elif(YesNo == "no"):
return 0
else:
return yes_or_no()
yes_or_no()
if(yes_or_no() == 1):
print("You said yeah!")
elif(yes_or_no() == 0):
print("You said nah!")
Run Code Online (Sandbox Code Playgroud)
从理论上讲,这应该可行,但我一直都有问题.每当我第一次输入是或否时,它总是重复这个问题.它第二次工作正常.请让我知道我做错了什么.谢谢!
你是第一次调用yes_or_no,它会输出一个值,但是你把它扔掉并再次调用函数而不是测试第一次调用的输出.
尝试将输出存储在变量中.
# Store the output in a variable
answer = yes_or_no()
# Conditional on the stored value
if answer == 1:
print("You said yeah!")
else:
print("You said nah!")
Run Code Online (Sandbox Code Playgroud)
对变量使用大写的名称被认为是不好的做法,应该为类保留.
此外,使用while循环可以更好地实现用户提示循环,以避免每次用户输入错误输入时向您的调用堆栈添加帧.
以下是您的功能的改进版本.
def yes_or_no():
while True:
answer = input("Yes or No?").lower()
if answer == "yes":
return 1
elif answer == "no":
return 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6141 次 |
| 最近记录: |