简体   繁体   English

random.randint 似乎不起作用,我认为

[英]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?也许您在 Python 2 而不是 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.在 Python 2 上,您需要将“input”替换为“raw_input”,否则它会尝试对输入的内容进行eval() ,这不是您想要的。

Because you mentioned python 3 in your tags, I'm assuming this is python 3 (Use raw_input for python 2).因为您在标签中提到了 python 3,所以我假设这是 python 3(将raw_input用于 python 2)。 You have to press enter after inputting your number from 1 to 100. When i tried your code, it worked no problem.输入从 1 到 100 的数字后,您必须按回车键。当我尝试您的代码时,它没有问题。

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? ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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