如果elif循环只在我输入3次后响应?

时间:2017-12-20 12:13:12

标签: python python-3.x

我是python的初学者,目前正在学习Al Sweigarts"用python自动化无聊的东西"并且我正在创建一个简单的程序来响应你并提出问题,并在我学到的每一件新事物中添加它。我试图让它回答是或否回答问题,如果有任何其他问题与#34进行相应的回答,请回答是或否#34;。但是它只会在我多次输入答案后才会响应,我不明白为什么。以下是我现在的代码部分。

print ('I am a computer, so i can calculate much faster, watch this')
print ('the multiplication table of 9 is')
for i in range (9,99,9):
     print (str(i))
print ('I could keep going forever, want me to?')
while input () != 'yes' and input () != 'no':
     print ('Please answer with yes or no')
if input () == 'no':
     print ('okay i will not')
elif input () == 'yes':
     print ('okay i will')
     for i in range (9,3009,9):
          print (str(i))
     print ('okay, that is enough')

有谁知道我做错了什么?我几天前才开始学习python。

1 个答案:

答案 0 :(得分:2)

每次调用input()时,解释器都会等待新的输入。您需要将对input()的第一次调用分配给变量,然后检查其值。

print ('I am a computer, so i can calculate much faster, watch this')
print ('the multiplication table of 9 is')
for i in range (9,99,9):
     print (str(i))
print ('I could keep going forever, want me to?')
answer = input()
while answer != 'yes' and answer != 'no':
     print ('Please answer with yes or no')
if answer == 'no':
     print ('okay i will not')
elif answer == 'yes':
     print ('okay i will')
     for i in range (9,3009,9):
          print (str(i))
     print ('okay, that is enough')


然而,如果用户输入yesno以外的任何内容,则会引入无限循环。

要解决此问题,请参阅Asking the user for input until they give a valid response