2012-07-24 83 views
1

如果这是一个荒谬的问题,我很抱歉,但我只是学习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: '))' 
+1

有人试图帮助你的代码格式化。你应该让他们自己做,或者自己做,以便代码实际上是可读的。 – crashmstr 2012-07-24 17:33:11

回答

5
  1. 你的意思是一个大while循环内使用多个if语句,而不是多个while循环。在这段代码中,一旦你经历了一个while循环,你就再也回不到它了。只要您按字母顺序给出州名,此代码将只能工作

  2. 不要这样做!还有一个很多更好的方法来使用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个州。

+0

非常感谢你!我们还没有覆盖字典,我应该等到那时试图做到这一点大声笑 – user1549425 2012-07-24 17:42:46

+0

你非常欢迎。如果回答您的问题,请不要忘记[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – 2012-07-24 17:48:26

1

我不认为你了解while循环。基本上,

while condition: 
    dostuff() 

做的东西,而条件为真。只要条件不成立,你就继续前进。我认为你在寻找什么是一样的东西:

x=True 
while x 
    x=raw_input('please enter a state'): 
    if x == 'Alabama': 
     ... 
    elif x == 'Alaska': 
     ... 

这将永远循环下去,直到用户点击刚刚进入(bool('')在Python False

然而,一个更好的办法做到这一点会可以使用字典:

state_capitals={'Alabama':'Montgomery', 'Alaska':'Juneau'} 
x=True 
while x 
    x=raw_input('please enter a state'): 
    print '{0} is the capital of {1}'.format(state_capitals[x],x) 

用这种方式,将引发一个KeyError当不良资产被赋予(你能赶上使用try块,如果你想)。

+0

谢谢你的回答!你们真棒! – user1549425 2012-07-24 17:44:06

0

在所有诚实方面,这是更糟的可怕。但是,你很可能是初学者,因此会发生这样的事情。

对于这个任务,你应该使用dict包含国家=>资本映射和读国名一次

capitals = {'Alabama': 'Montgomery', 
      'Alaska': 'Juneau', 
      ...} 
state = raw_input('Please enter a state: ') 
if(state in capitals): 
    print '{0} is the capital of {1}'.format(capitals[state], state) 
else: 
    print 'Sorry, but I do not recognize {0}'.format(state) 

如果你想使用一个while循环,使用户可以输入多个如果用户不输入任何内容,则可以将整个代码包装在while True:区块中,并在raw_input之后紧接着使用if not state: break来中断循环。

+0

谢谢你回答我的问题,我完全是一个初学者大声笑 – user1549425 2012-07-24 17:45:52