4

I'm new to programming and I'm trying to teach myself Python. I've started to write a little flashcard script. My idea is that the user is presented with a problem and is prompted to submit an answer. If the answer is incorrect the user is prompted to try again, an so on until the correct answer is entered. So far it works as planned, but I don't know how to make it start over again after the correct answer is entered. I suppose I'll also need to include some means of allowing the user to exit the game, which I also don't know how to do so if you want to throw in a suggestion about that I'd appreciate it. :-)

PS - If my code is lame I'm open to suggestions. But I'm mainly looking for an answer to my original question(s). This is my first foray into coding so I'm sure as time goes on I'll get better at writing more elegant code.

Thanks!

def add():
   from random import randint
   a = randint(1, 5)
   b = randint(1, 5)
   c = a + b
   print a,  '+',  b
   print 'What\'s the sum?'
   d = input()
   while d != c:
     print 'Wrong, try again!'
     d = input()
   else:
     print "Correct!"
Brian
  • 81
  • 2
  • 8
  • you could simplify the loop to `while input() != c`, and remove the first `d = input()` – Snakes and Coffee Jan 17 '13 at 05:48
  • congrats on your foray into programming! looking good so far :) – Eevee Jan 17 '13 at 06:16
  • You should not put the import inside your definition generally. http://stackoverflow.com/questions/128478/should-python-import-statements-always-be-at-the-top-of-a-module – jgritty Jan 17 '13 at 06:55

2 Answers2

3

Firstly, use raw_input instead of input and then convert that to an integer. To answer your question though, ask for user input like so:

play_again = raw_input('Play again? (y/n)')
if play_again.lower().startswith('y'):
    add()
return

input is unsafe because it gets evaluated as native code, and so a skilled individual may be able to hack into the system. raw_input treats the input as a string, and you can call int() on the result.

This only applies for Python 2 however. For Python 3, input is fine - it replaced the Python 2 raw_input.

Also, there is recursion in the function - although nobody will probably be persistent enough to make the stack overflow, although for other applications, iteration will be the best method.

Converting this to an iterative loop is trivial (and also recommended). Put everything apart from the import inside a while True loop. Then at the end of the loop, add this code:

play_again = raw_input('Play again? (y/n)')
if play_again.lower().startswith('y'):
    continue
break

You could of course check for 'n' instead of 'y' and get rid of the continue, replacing it with a simple break statement.

Note that you can also replace the if statement to a less readable:

if raw_input('Play again? (y/n)').lower().startswith('y'):  # or 'n'

And get rid of the intermediate play_again variable. Although I wouldn't sacrifice readability for compactibility.

Volatility
  • 31,232
  • 10
  • 80
  • 89
  • @SnakesandCoffee the OP uses `print` as a statement, so I assume it's Python 2. However, it is worth to note the difference. – Volatility Jan 17 '13 at 05:49
  • 2
    `continue` isn't going to work as a variable name.. ;^) More importantly, though, using a `while` loop is preferable to a possibly interpreter-breaking recursive call. – DSM Jan 17 '13 at 05:50
  • @DSM how did I forget that? Probably need more sleep. `:P` – Volatility Jan 17 '13 at 05:54
  • Would be better if a loop is used instead of recursion, as in a game loop – elssar Jan 17 '13 at 07:03
0

In Python 3 (for input) :

I slightly modified your code (added "()" for print, and int in order for comparison to work. Didn't check if you enter a non int)

def add():
   from random import randint
   a = randint(1, 5)
   b = randint(1, 5)
   c = a + b
   print (a,  '+',  b)
   d = int(input('What\'s the sum?'))
   while d != c:
     print ('Wrong, try again!')
     print (a,  '+',  b,' ? ')
     d = int(input())
   else:
     print ("Correct!")


while True:
    add()
    if input('Continue (O/N) ? ') == 'N':
        break

I printed also the addition in your loop because many wrong answers can clear the initial question.

As stated, the initial loop execute your function until you type 'N'. You might add the correct answer in the add loop if the user wants to quit.

Iggy
  • 53
  • 8