我正在玩If Else语句,我想知道如果第一个If Else是真的,如何让它循环再次询问问题。
此外,您如何在最后添加一个通用的Else,以便为其他任何其他名称说些什么?
我在Python 2.7
Raspberry Pi.
#!/usr/bin/python
name=""
while name !="quit":
name = raw_input("What is your name? ")
print "Hello", name
import time
time.sleep(2)
if name == "Jack":
print "Jack, I have decided that you are awesome."
time.sleep(2)
print "And I am a computer so I cannot be wrong"
else:
print "Oh, you are not Jack?"
time.sleep(2)
print "Haha, Jack is better than you"
if name == "Ronan":
print "Ronan, I know everything about you."
time.sleep(2)
print "For example, I know you hate cats."
else:
print "Oh, you are not Ronan?"
time.sleep(2)
print "Perhaps you can convince him that he loves cats"
答案 0 :(得分:1)
您忘记在print "Haha, Jack is better than you
行关闭括号。
你应该import time
只有一次,在while循环之外,最好是在脚本的开头。您无需导入while name !="quit"
。
if/else
构造应如下所示:
if something:
#do something
elif otherthing:
#do something else
else:
#if everything above fails, do this
答案 1 :(得分:0)
你错过了这一行的结束语print "Jack, I have decided that you are awesome."
最后一行的break
命令将有助于终止循环。
name=""
while name !="quit":
name = raw_input("What is your name? ")
print "Hello", name
import time
time.sleep(2)
if name == "Jack":
print "Jack, I have decided that you are awesome."
time.sleep(2)
print "And I am a computer so I cannot be wrong"
else:
print "Oh, you are not Jack?"
time.sleep(2)
print "Haha, Jack is better than you"
if name == "Ronan":
print "Ronan, I know everything about you."
time.sleep(2)
print "For example, I know you hate cats."
else:
print "Oh, you are not Ronan?"
time.sleep(2)
print "Perhaps you can convince him that he loves cats"
if name != "jack" and name != "Ronan":
print "I am not wrong"
break
答案 2 :(得分:0)
您可以使用continue
将执行返回到循环的顶部。
if name == "Jack":
print "Jack, I have decided that you are awesome."
time.sleep(2)
print "And I am a computer so I cannot be wrong"
continue
但实际上你需要重构你的if ... else语句。
你的循环终止逻辑也不太对,这样会更好:
while True:
name = raw_input("What is your name? ")
if name.lower() in ('quit', 'exit', 'end', 'bye'):
break
print "Hello", name
if name == "Jack":
.
.
.
至于你的if语句,因为你对每个名字都有else子句,所以通用的catch都有点困难。你可以在最后检查:
KNOWN_NAMES = ('Jack', 'Ronan', 'Whomever')
QUIT_VERBS = ('quit', 'q', 'exit', 'end', 'bye')
while True:
name = raw_input("What is your name? ")
if name.lower() in QUIT_VERBS:
break
if name == "Jack":
print "Jack, I have decided that you are awesome."
time.sleep(2)
print "And I am a computer so I cannot be wrong"
else:
print "Oh, you are not Jack?"
time.sleep(2)
print "Haha, Jack is better than you"
if name == "Ronan":
# etc, etc
if name not in KNOWN_NAMES:
print 'I know nothing about no "%s"' % name