简体   繁体   中英

My Python number guessing game

I have been trying to make a number guessing game for Python and so far it has altogether gone quite well. But what keeps bugging me is that it resets the number on every guess so that it is different, but I want it to stay the same and then people can take a while guessing it.

import os
import time

print("this is a random number generator")
number1 =int(input("please pick a NUMBER between 1 and 99"))
from random import randint
number2 = int(randint(1,99))
if number1 == number2:
    print(" congrats! you got it right")
elif number1 < number2:
    print ("too low try again")
elif number1 > number2:
    print ("too high try again")

if number1 not in range(1,99):
    print("you idiot! Pick a number IN THE RANGE")

while number1 != number2:


    print("this is a random number generator")
    number1 =int(input("please pick a NUMBER between 1 and 99"))
    from random import randint
    number2 = int(randint(1,99))
    if number1 == number2:
        print(" congrats! you got it right")
    elif number1 < number2:
        print ("too low try again")
    elif number1 > number2:
        print ("too high try again")

    if number1 not in range(1,99):
        print("you idiot! Pick a number IN THE RANGE")



time.sleep(10)
os.system("exit")

Since you have number2 = int(randint(1,99)) inside your while cycle, then you create a new number each time. Put that line outside the while and the number will remain the same until someone guesses it

There are a lot of things wrong with your code : the import statement should be at the beginning, and there is much duplicated code, which makes it hard to read.

Your problem comes from the fact that number2 = int(randint(1,99)) is called at each cycle of the while loop.

This could be improved to :

import os
import time
from random import randint

print("This is a random number generator")
number2 = int(randint(1,99))
while True:
    try:
        number1 =int(input("Please pick a NUMBER between 1 and 99\n"))
        if number1 not in range(1,99):
            print("You idiot! Pick a number IN THE RANGE")
        if number1 == number2:
            print("Congrats! You got it right")
            break
        elif number1 < number2:
            print ("Too low, try again")
        elif number1 > number2:
            print ("Too high, try again")
    except (ValueError, NameError, SyntaxError):
        print("You idiot! This is not a number")

time.sleep(10)
os.system("exit")

Also, no need to import from random import randint everytime you need randint() . Put it at the top next to import time

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