[Tutor] creating a dictionary for capital quiz program
Alan Gauld
alan.gauld at btinternet.com
Tue Jun 2 17:43:38 CEST 2015
On 02/06/15 09:45, ZBUDNIEWEK.JAKUB wrote:
> I'm a newbie, but was able to tune it to correctly reply to user inputs.
> 1. My question is can it be optimized in any way?
Code can nearly always be optimised.
Whether it is worth doing so depends on the need to do so.
In this case I douybt its worthwhile :-)
> 2. Why (on Windows) do I have to give inputs in quotes not to cause
> an error (for ll input the error is ' NameError: name 'll' is
> not defined')?
As Peter has said, you are probably running Python 2 rather
than Python 3. input() changed behaviour in the upgrade.
> def main():
>
> right = 0
> wrong = 0
> capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": 'Phoenix', \
> 'Arkansas': 'Little Rock', 'California': 'Sacramento', \
You don't need the backslashes. Python is quite happy to read
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau',
"Arizona": 'Phoenix', 'Arkansas': 'Little Rock',
'California': 'Sacramento', ...etc...
}
So long as its inside (),{}, or {} (or triple quotes,
although they are slightly different) you don;t need line
continuation marks (\).
>
> for k in capitals.keys():
> state = input('Enter the capital of '+k+' :')
> if state.upper() == capitals[k].upper():
> right += 1
> print('Correct')
> else:
> wrong += 1
> print('Incorrect')
> choice = input('Do you want to play again y/n: ')
> if choice.upper() == 'N':
> print('end of game')
> break
> elif choice.upper() != 'Y':
> print("invalid choice")
>
> print('Number of correct answers is: ', right)
> print("Number of incorrect answers is:", wrong)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list