如果这是一个荒谬的问题,我很抱歉,但我只是在学习 python,我无法弄清楚。 :)
我的程序应该打印用户输入的任何州的首都。有时会连续工作十次,有时会连续工作三次,然后输入一个状态就停止了。如果我重新启动它并输入它停止时的状态,它将正常工作......随机次数然后它会再次停止。我究竟做错了什么?我的代码也很糟糕吗?我不知道为此使用什么样的代码,所以我只是把我能做的任何东西都扔进去了。
x = str(raw_input('Please enter a sate: ' ))
while x == 'Alabama':
print 'Montgomery is the capital of', x
x = str(raw_input('Please enter a state: '))
while x == 'Alaska':
print 'Juneau is the capital of', x
x = str(raw_input('Please enter a state: '))
while x == 'Arizona':
print 'Phoenix is the capital of', x
x = str(raw_input('Please enter a state: ' ))
while x == 'Arkansas':
print 'Little Rock is the capital of', x
x = str(raw_input('Please enter a state: '))'
请您参考如下方法:
您的意思是在一个大的
while循环中使用多个if语句,而不是多个while循环。在这段代码中,一旦你过了一个 while 循环,你就再也不会回到它了。只要您按字母顺序为其提供状态名称,此代码仅有效。不要这样做! 使用 python 有一个好得多的方法来做到这一点 dictionaries .
capitals = {"Alabama": "Montgomery", "Alaska": "Juneau", "Arizona": "Phoenix", "Arkansas": "Little Rock"} while True: x = str(raw_input('Please enter a state: ' )) if x in capitals: print capitals[x], "is the capital of", x
否则,如果您想覆盖所有 50 个州,您最终会得到 50 对几乎相同的线。
