(初学者Python)根据用户输入创建if/else语句?
我正在尝试创建一个简单的脚本,它会问一个问题,用户可以输入答案(或者可以出现一个可以选择答案的提示?),然后程序会根据输入给出回应。
例如,如果我说
prompt1=input('Can I make this stupid thing work?')
我可能走错了方向。请尽量详细说明,因为这是我学习的练习。提前谢谢你!
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
2 个回答
1
另一个例子,这次是作为一个函数。
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()
2
你已经很接近了。找个好的教程看看吧 :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True
会让程序一直循环下去,永不停止。- 用
==
来检查两个东西是否相等。 - 用
.lower()
可以让你在比较答案时不管大小写都能更方便。 if/elif/elif/.../else
是检查条件的正确顺序。
下面是 Python 2 的版本:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input
用来代替input
。在 Python 2 中,input
会尝试把输入当作 Python 代码来解释。print
是一个语句,而不是一个函数。所以用的时候不要加()
。