I have a little problem with my code, i'm trying to make a guess game, actually it is from a book, but i can't figure out what is wrong with it...
# A guess game program made in python
import random
guessesTaken = 0
print('Hello! What is your name, may i ask?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20')
while guessesTaken < 6:
print('Take a guess..')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your number guess is too low, guess again')
if guess > number:
print('Your number is too high! guess lower or something!')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed the right number in' + guessesTaken + 'guesses!')
if guess != number:
number = str(number)
print('Nah, The number i was thinking of was ' + number)
This is the error it's giving me..
Hello! What is your name, may i ask?
ygh
Well, ygh, I am thinking of a number between 1 and 20
Take a guess..
4
Your number guess is too low, guess again
Nah, The number i was thinking of was 7
Take a guess..
2
Traceback (most recent call last):
File "C:/Users/Owner/Desktop/guess.py", line 19, in <module>
if guess < number:
TypeError: unorderable types: int() < str()
Process finished with exit code 1
I'm using Pycharm as my IDLE and i'm also on windows..
Few changes in your code tho, instead of calling str
you can use format()
# A guess game program made in python
import random
guessesTaken = 0
print('Hello! What is your name, may i ask?')
myName = input()
number = random.randint(1, 20)
print('Well, {}, I am thinking of a number between 1 and 20'.format(myName))
while guessesTaken < 6:
print('Take a guess..')
guess = input()
guess = int(guess)
guessesTaken += 1 # Instead of calling the variable itself then adding 1
if guess < number:
print('Your number guess is too low, guess again')
if guess > number:
print('Your number is too high! guess lower or something!')
if guess == number:
print('Good job, {}! You guessed the right number in {} guesses!'.format(myName,guessesTaken))
break # the beak goes here
if guess != number:
print('Nah, The number i was thinking of was {}'.format(number))
Also, your break
was placed incorrectly because it will be executed before sending the print
that you want, thus ending your code prematurely.
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.