I’m sorry if this is a ridiculous question but I’m just learning python and I can’t figure this out. 🙂
My program is supposed to print the capital of any state that the user inputs. Sometimes it will work ten times in a row, other times it will work three times in a row, and then it will just stop after you type in a state. If I restart it and type in the state that it stopped on it will work just fine….for a random number of times and then it will stop again. What am I doing wrong? Also is my code awful? I had no idea what sort of code to use for this so I just kind of tossed in whatever I could make work.
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: '))'
You mean to use multiple
ifstatements within one bigwhileloop, rather than multiplewhileloops. In this code, once you’re past one while loop, you never come back to it. This code will work only as long as you are giving it state names in alphabetical order.Don’t do it this way! There is a much better way to do it using python dictionaries.
Otherwise, you’ll end up having 50 pairs of almost identical lines if you want to cover all 50 states.