#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    1
    Rep Power
    0

    Python - While loop


    I have made a program which randomly selects 2 numbers between 1 and 100. It will then display the 2 numbers in a question and the program repetitively asks the user the same question until they answer it correctly. There is also a counter which counts how many attempts the user takes. However, When i run the program the first function works fine, it randomly picks the numbers and sets the correct variables. In the second function, the 'answer' input line works and asks as it should, but even if the correct answer is entered it still asks the user again, and again and again. What do I do to fix this?

    Program:


    #This guessing game continually asks user to answer a
    #random number question until they get it

    from random import*

    def setup_game():
    #introduces and sets variables in game
    global no_1, no_2, counter
    print ("This is a guessing game.")
    no_1 = randint(1,100)
    no_2 = randint(1,100)
    counter = 1

    def play_game():
    #asks user to answe until correct
    #it keeps a count of how many guesses
    global counter, answer
    answer = no_1 + no_2
    answer2 = input("Answer:"+str(no_1)+"+"+str(no_2)+"=")
    while answer2 != answer:
    print ("Wrong number - Try again!")
    answer2 = input("Answer:"+str(no_1)+"+"+str(no_2)+"=")
    counter = counter+1

    def display_result():
    #displays how many guess attempts the user took
    print ("\nWell Done! - you answered correctly")
    if counter >=2:
    print ("You took ",counter," shots to get the number",answer)
    if counter == 1:
    print ("You took ",counter," shot to get the number",answer)

    #Main Program
    setup_game()
    play_game()
    display_result()
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    Run your program with python 2.

    I did not try your program. Your global statements look like they're in the right places, which is a common problem at this forum.

    Differences between python versions 2 and 3 cause other common trouble. In python2, the builtin input function evaluates the line it reads. Since blindly evaluating input is a big mistake, they no longer provide the capability in python3. In python3, raw_input was renamed as input. In other words, input returns a string and there isn't a "raw_input" function. Running your program with python2 is a bad idea. You might discover that
    answer
    is always correct. Let's get to the point. You'll want

    int(input('addition question'))

    print the type and value of data---that's one of the quickest ways to debug.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo