简体   繁体   中英

random.randint seems to not work, i think

i was doing a Guess the number "project" and I got stuck, when i run it, it ask me to chose a number then nothing happends, here's the code:

import random

play_game = "y"

while (play_game == "y"):
    answer = random.randint(1, 100)
    try_number = input("Guess a number between 1 and 100: ")
    try_number = int(try_number)
    counter = 1

    while try_number != answer:
        if try_number > answer:
            print("Your number is too large")
        if try_number < answer:
            print("Your number is to small")
        try_number = int(input("Guess a number between 1 and 100: "))
        counter = counter + 1
    print("You got it! You tried " + str(counter) + "times")
    play_game = input("Continue? ")

Thank you for your time!

Perhaps you're running this on Python 2 instead of Python 3? On Python 2, you need to replace "input" with "raw_input", otherwise it will try to eval() the contents of the input, which is not what you want.

Because you mentioned python 3 in your tags, I'm assuming this is python 3 (Use raw_input for python 2). You have to press enter after inputting your number from 1 to 100. When i tried your code, it worked no problem.

import random

play_game = "y"

while (play_game == "y"):
    answer = random.randint(1, 100)
    try_number = input("Guess a number between 1 and 100: ")
    try_number = int(try_number)
    counter = 1

    while try_number != answer:
        if try_number > answer:
            print("Your number is too large")
        if try_number < answer:
            print("Your number is to small")
        try_number = int(input("Guess a number between 1 and 100: "))
        counter = counter + 1
    print("You got it! You tried " + str(counter) + "times")
    play_game = input("Continue? ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM