Reputation: 183
I am trying to create a game that will ask the user to make a guess and if the guess is lower than the randomly generated integer, then it'll print ('Too low! Try again.), if the guess higher than the guess then it will print ('Too high! Try again) and if guess is equal to the random integer then it will ask the user if she wants to play again. This is where I am having trouble with - how can I have the code loop it back to recreate the random integer and start the loop if 'y' is entered?
import random
def main():
again='y'
count=0
while again=='y':
print('I have a number between 1 to 1000.')
print('Can you guess my number?')
print('Please type your first guess')
number=random.randint(1, 1000)
print(number)
guess=int(input(''))
while guess !='':
if guess>number:
print('Too high, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess<number:
print('Too low, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
else:
print('You entered an invalid value')
main()
Upvotes: 0
Views: 974
Reputation: 4351
You can do this by just adding one line with your code, use break
in the inner while loop, in this portion below, it will break the inner loop if user guessed the number accurately with getting new input of again
, then if again
= 'y'
it will start the outer loop again and random will generate again, otherwise the game will end.
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break # added this `break`, it will break the inner loop
Upvotes: 2
Reputation: 81
Since you are in two loops you have to break the deepest one. Here are two ways for your situation.
Eather update "guess" to: '':
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
guess=''
Or add a break after the again input:
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break
Upvotes: 1