简体   繁体   中英

Making random number guessing game as a small python project and I'm wondering why this isn't working

This is the code I've written so far in IDLE. When I run it, the while loop doesn't break when it should. Why could this be? What's wrong with my code? I'm very new to Python and have used C++ for years.

import random

random.seed()
randomNumber=random.randint(0,20)

print("Try to guess the number between 0 and 20\n\n\n")

while 1==1:
    guess = input("What is your guess?\n")
    if guess==randomNumber:
        break

print("Guess correct")

Cast input to int

guess = int(input("What is your guess?\\n"))

Your input is a string you need to convert it to an integer, so the the line

guess = input("What is your guess?\n")

should be

guess = int(input("What is your guess?\n"))

I have added the comment for the code: I think C++ has made you over-think some things. Python does a lot of the work for you that you have to do yourself in lower level languages.

import random

# random.seed() # you don't need a seed
randomNumber=random.randint(0,20)


print("Try to guess the number between 0 and 20")
# you must specify the datatype for the input
guess = int(input("What is your guess?")) # you don't need a line break

while guess != randomNumber: # no need for 1=1,
    guess = int(input("What is your guess?")) # data-type again
    if guess == randomNumber:
        print("Guess correct")
        break # exit condition

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