I started to make a number guessing game. Here is the code I wrote:
import random
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' NamePlayer ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, 7):
Guess = int(input())
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' NamePlayer)
else:
print('You are wrong')
The problem is that for the last iteration I get the print for the condition that is met inside of the for
loop, as well as the print outside of the loop. Of course I don't want the print 'Too high, take another guess' or something like that if it is the last guess.
How can I only print 'Damnn are you a mindreader' or 'You are wrong' for the last iteration?
CodePudding user response:
You can store number of guesses in a var like N.
N = 7
for Guesstaken in range(1, N):
Guess = int(input())
if Guesstaken == N - 1:
break
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' NamePlayer)
else:
print('You are wrong')
CodePudding user response:
It would be better if you had a line to print rules of game, I wasn't sure how many tries you wanted to give. your program counted from 1.....6 and it was just 6 steps so i made it loop 7 times as this
for Guesstaken in range(7):
Guess = int(input())
if Guess < randomnumber and Guesstaken<6:
print('Too low, take another guess!')
elif Guess > randomnumber and Guesstaken<6:
print('Too high, take another guess!')
else:
break
CodePudding user response:
import random
number_of_trials=6
c=0
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' NamePlayer ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, number_of_trials 1):
c =1
Guess = int(input())
if Guess < randomnumber and c!=number_of_trials:
print('Too low, take another guess!')
elif Guess > randomnumber and c!=number_of_trials:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' NamePlayer)
else:
print('You are wrong')
here c is a counter to see if the number_of_trials are reached. It will help in not displaying 'Too high, take another guess' or something like that if it is the last guess.