There are a couple of problems with the code you posted. As mentioned in the comments, the str()
call in name = str(input("how ya name bruh:"))
is pointless because the Python 3 input()
function always returns a string; calling str()
on an object that's already a string just returns that object. So it doesn't hurt anything, but it adds unnecessary clutter to the code.
Similarly, the expression int(1)
is redundant because 1 is already an integer. And calling int()
on an integer object just returns the original integer object.
However, guesstaken = guesstaken + str(int(1))
is strange. It doesn't perform arithmetic it does string concatenation because both guesstaken
and str(int(1))
are strings. Here's a short demo of what it does.
s = '0'
for i in range(5):
s = s + '1'
print(s)
output
01
011
0111
01111
011111
With that stuff out of the way we can get onto your question. :) You want to know how to get a new random integer once the player has guessed the correct number. That's simple: we just put the code inside another while
loop. We also need to ask the player if they want to play again so that we have some way of breaking out of that loop and exiting the program.
Here is a repaired version of your code, with that extra while
loop. I've used the string .format()
method to make the printing code cleaner.
''' Guess a number from 1 to 100 '''
from random import randint
name = input("What's your name? ")
prompt = name + " enter a number: "
while True:
randm = randint(1, 99)
guesstaken = 0
while True:
user_guess = int(input(prompt))
guesstaken += 1
if user_guess == randm:
print("You guessed {} {}, in {} guesses".format(randm, name, guesstaken))
# break out of inner loop
break
elif user_guess >= randm:
print("Guess lower")
elif user_guess <= randm:
print("Guess higher")
# Play again if user inputs "y" or "Y"
if input("Play again? [y/N] ").lower() != "y":
# break out of outer loop
break
print("Thanks for playing, {}.".format(name))
demo
What's your name? PM 2Ring
PM 2Ring enter a number: 50
Guess lower
PM 2Ring enter a number: 25
Guess higher
PM 2Ring enter a number: 37
Guess lower
PM 2Ring enter a number: 31
Guess higher
PM 2Ring enter a number: 34
Guess lower
PM 2Ring enter a number: 33
Guess lower
PM 2Ring enter a number: 32
You guessed 32 PM 2Ring, in 7 guesses
Play again? [y/N] y
PM 2Ring enter a number: 64
Guess lower
PM 2Ring enter a number: 32
Guess lower
PM 2Ring enter a number: 16
Guess higher
PM 2Ring enter a number: 24
Guess higher
PM 2Ring enter a number: 28
Guess lower
PM 2Ring enter a number: 26
You guessed 26 PM 2Ring, in 6 guesses
Play again? [y/N] n
Thanks for playing, PM 2Ring.