Want the game to terminate after 6 trials - python

I am trying to exit the game after 6 trials. However, the game is continuing even after 6 trials.
I have applied a while count_trials <=6. It should go to the else part after the count_trails exceeds 6, isn't it? However, it's going beyond 6 and showing something like:
"Great Prashant! you guessed the number right in 9 guesses"
from random import randint
#Asking the user a number
def ask_a_number():
playernumber = int(input('Guess a number: '))
return playernumber
#Comparing the numbers and giving hints to the player about the right number
def compare_2_nos(num1, num2):
if (num1 < num2):
if abs(num1 - num2) > 3:
print('Your number is too low')
else:
print ('Your number is slightly low')
if (num1 > num2):
if abs(num1 - num2) > 3:
print('Your number is too high')
else:
print ('Your number is slightly high')
#Running the Guess the number game
name = input('Enter your name: ')
print ('Hi {}! Guess a number between 1 and 100').format(name)
num1 = ask_a_number()
count_trials = 1
num2 = randint(1,100)
while count_trials <= 6:
while num1 != num2:
compare_2_nos(num1, num2)
num1 = ask_a_number()
count_trials += 1
else:
print ("Great {}! you guessed the number right in {} guesses".format(name, count_trials))
break
else:
print ("You have have exceeded the number of trials allowed for this game")
I am expecting the game to print "You have have exceeded the number of trials allowed for this game" after 7 or more trials

The first bug you have is on line 22, you should put .format() right after the string.
And you are creating a 'infinite loop' since you are not increment count_trials every loop.
just change the while loop like this
while count_trials <= 6:
if num1 != num2:
compare_2_nos(num1, num2)
num1 = ask_a_number()
else:
print ("Great {}! you guessed the number right in {} guesses".format(name, count_trials))
break
count_trials += 1
or using a for loop with range(1, 7) as iterable.

Your program never gets out of the inner while loop.Also, you are asking for a number before the loop starts.So, for 6 trials your check condition should be count_trials<6.Try this
while count_trials < 6:
count_trials += 1
compare_2_nos(num1, num2)
num1 = ask_a_number()
if num1 == num2:
print ("Great {}! you guessed the number right in {} guesses".format(name, count_trials))
break
else:
print ("You have have exceeded the number of trials allowed for this game")

while loops are notorious for creating these kinds of problems.
My suggestion is to use a for loop that iterates over the exact number of trials you want, with an if condition that tests for success:
for trial in range(1, 7):
if num1 == num2:
print ("Great {}! you guessed the number right in {} guesses".format(name, trial))
break
compare_2_nos(num1, num2)
num1 = ask_a_number()
else:
print ("You have have exceeded the number of trials allowed for this game")
This also means you don't have to keep a 'counter' variable which you need to continue adding to, as seen with count_trials

Related

adding a loop to high and low game

#Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
# imports
import random
# declarations
num1 = (random.randint(0, 10))
num2 = (random.randint(0, 10))
guess = ""
# Now we build the program code:
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
print("The first number is", num1, "Enter h for higher or l for lower to guess the second number")
guess = input('-->')
if guess == 'h':
if num1 < num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
elif guess == 'l':
if num1 > num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
else:
print("Not an exceptable entry")
I made this and it works but I want to create a loop so the user can play all they want. I am new to this ..any suggestions would be appreciated
After copy paste your code in my IDE I realize you miss the conception for this code.
You should start this with the idea of breaking the loop if right, continue if wrong.
This isn't a good practice but I found a quick way to answer your need without refactoring your code:
Add you entire code (except the import of random module) inside
while True:
And add break control statement after each good answer.
I tested it and it's work but I recommend you to search for similar project to compare with your, it will be a good point for later in your adventure.
Using functions here would be a good idea, I'd recommend putting your main code in a function called 'play' for example and also create a function which prompts the user if he wants to play again.
Then create a while loop which calls your 'play' function, and update the condition of your main loop after each 'play' with the prompt function.
This is how I have done it.
# Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
# imports
import random
# Now we build the program code:
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
def play():
# declarations
num1 = (random.randint(0, 10))
num2 = (random.randint(0, 10))
print("The first number is", num1, "Enter h for higher or l for lower to guess the second number")
guess = input('-->')
if guess == 'h':
if num1 < num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
elif guess == 'l':
if num1 > num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
else:
print("Not an exceptable entry")
def promptAgain():
print("Play again? y/n")
response = input().lower()
if response == 'n':
return False
elif response == 'y':
return True
else:
print("Not an exceptable entry")
return promptAgain()
again = True
while again:
play()
again = promptAgain()
Since you only allow higher or lower input you need to ensure the same number is not randomly selected twice. I.e., if num1 is 8 then num2 should not be able to also be 8 (your current code doesn't prevent this).
Consider utilizing random.sample to achieve this:
"""Daniel Gardner's Higher/Lower Game."""
import random
MIN_RAND_VALUE = 0
MAX_RAND_VALUE = 10
GUESS_PROMPT = '--> '
HIGH_GUESS = 'h'
LOW_GUESS = 'l'
def get_yes_no_input(prompt: str) -> bool:
"""Returns True if the user enters yes."""
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
def higher_or_lower_game_loop() -> None:
num1, num2 = random.sample(range(MIN_RAND_VALUE, MAX_RAND_VALUE + 1), 2)
print('The first number is', num1,
'Enter h for higher or l for lower to guess the second number.')
guess = input(GUESS_PROMPT)
while guess not in {HIGH_GUESS, LOW_GUESS}:
print('Not an exceptable entry, you must enter h or l')
guess = input(GUESS_PROMPT)
if guess == HIGH_GUESS:
if num1 < num2:
print('You guessed it! the number is:', num2)
else:
print('Nice guess but the number is:', num2)
elif guess == LOW_GUESS:
if num1 > num2:
print('You guessed it! the number is:', num2)
else:
print('Nice guess but the number is:', num2)
def main() -> None:
print('Welcome to my high/lower game.',
'You will guess the second number in the game,',
'is it higher or lower than the number presented?')
while True:
higher_or_lower_game_loop()
play_again = get_yes_no_input('Play again? ')
if not play_again:
break
print('Goodbye!')
if __name__ == '__main__':
main()
Example Usage:
Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
The first number is 8 Enter h for higher or l for lower to guess the second number.
--> l
You guessed it! the number is: 5
Play again? yes
The first number is 10 Enter h for higher or l for lower to guess the second number.
--> l
You guessed it! the number is: 8
Play again? n
Goodbye!
You can utilize recursion and while loop to validate input:
from random import sample
def hilow():
num1, num2 = sample(range(1, 11), 2); # print(num1, num2)
print(f"The first number is {num1} Enter h for higher or l for lower to guess the second number")
while (guess:=input('-->').lower()) not in ('h','l'):print("Not an exceptable entry")
res = guess == 'h' and num1 < num2 or guess == 'l' and num1 > num2
print((f"Nice guess but the number is {num2}",f"you guessed it! the number is {num2}")[res])
while (p:=input("Play again (y/n)?: ").lower()) not in ('y','n'):print("Not an exceptable entry")
p == 'n' or hilow()
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
hilow()
Output:
Welcome to higher or lower, Choose whether or not the number is higher or lower
The first number is 2 Enter h for higher or l for lower to guess the second number
-->h
you guessed it! the number is 7
Play again (y/n)?: z
Not an exceptable entry
Play again (y/n)?: y
The first number is 2 Enter h for higher or l for lower to guess the second number
-->l
Nice guess but the number is 5
Play again (y/n)?: y
The first number is 3 Enter h for higher or l for lower to guess the second number
-->x
Not an exceptable entry
-->h
you guessed it! the number is 6
Play again (y/n)?: n

How to hide a print() or that it does not execute in under certain circumstances

I want to know if it's possible in python to not run an part of the code
from random import randint
def replay():
réponse = input("Want to replay?")
if réponse == "Yes".lower():
jeu()
if réponse == "No".lower():
exit()
def jeu():
choice = int(randint(1, 10))
userchoice = int(input("I think of a number between 1 and 10, guess it: \n"))
if choice <= userchoice:
print("The number is too high")
if choice >= userchoice:
print("The number is too law")
if choice == userchoice:
print("Well done the number was" ,userchoice,)
replay()
if choice != userchoice:
while True:
userchoice = int(input("Try again\n"))
if choice <= userchoice:
print("The number is too high")
if choice >= userchoice:
print("The number is too law")
if choice == userchoice:
print("Well done the number was " ,userchoice,)
replay()
jeu()
When I guess the number it gives me this:
and I don't want to see "The number is to high" and "the number is too low" at the same time. How to do so ? How can we hide this or prevent this part of code from running in that condition?
The problem is this operator:
>=,
<=
This two operators also tell python to check if a particular number is greater, less or equal to the next operand.
when you input an integer which is equal to the random number, it is equal to the random number. And 3 separate blocks if if created 3 new control statement which are independent of each other.
So the condition >= and <= is always met. hence it prints "it's to high" or "it's to low"
if choice < userchoice:
print("The number is too high")
elif choice > userchoice:
print("The number is too law")
elif choice == userchoice:
print("Well done the number was" ,userchoice,)
replay()
The problem is in this block:
if choice <= userchoice:
print("The number is too high")
if choice >= userchoice:
print("The number is too law")
if choice == userchoice:
print("Well done the number was" ,userchoice,)
It will fail for the case when choice and userchoice is same. Each of the 3 conditions will meet then and all 3 conditions will execute.
However, replace the redundant checking with lambda function and remove the misplaced use of while loop with repetitive code. You can refactor your code as follows to have a more decent look:
from random import randint
def replay():
réponse = input("Want to replay?")
if réponse.lower() == "Yes".lower():
jeu()
if réponse.lower() == "No".lower():
exit()
def jeu():
choice = int(randint(1, 10))
print("I think of a number between 1 and 10, guess it:")
while True:
userchoice = int(input())
if choice == userchoice:
print("Well done the number was" ,userchoice,)
replay()
else:
f = lambda c, uc: print("The number is too high") if c < uc else print("The number is too low")
f(choice, userchoice)
print("Try Again:")
jeu()

Can someone show me a more efficient/shorter way to write this python random # program?

I am new to python and I am eager to learn a shorter way of writing a random number program I made.
import random
a = random.randint(1,100)
for x in range(5):
num = int(input("Guess my random number:\n"))
if(num < a):
print("Your guess is too small!")
continue
elif(num > a):
print("Your guess is too big!")
continue
else:
print("You got it!")
break
if (num == a):
print("Hooray!")
else:
print("You ran out of guesses!")
print("The random number was:", a)
print("Your last guess was:", num)
print("It took you this many tries:", x+1)
import random
a = random.randint(1,100)
for x in range(5):
num = int(input("Guess my random number:\n"))
if num < a:
print("Your guess is too small!")
elif num > a:
print("Your guess is too big!")
else:
print("You got it!")
print("Hooray!")
break
else:
print("You ran out of guesses!")
print(f"The random number was: {a}")
print(f"Your last guess was: {num}")
print(f"It took you {x+1} tries.")
For loop in python supports else keyword. The code after else is executed, if loop is exited normally (without break). Your 'Hoorray!' is printed only right after 'You got it!' or not printed at all, so they can be merged.
As #Chris_Rands mentions, the code is overall ok (except for the indentation, which I assume is an error when pasting. The continues are not needed though, and the extra parenthesis either.
import random
a = random.randint(1, 100)
for x in range(5):
num = int(input("Guess my random number:\n"))
if num != a:
print("Your guess is too %s!" % 'small' if num < a else 'big')
else:
print("You got it!\nHooray!")
break
else:
print("You ran out of guesses!")
print("The random number was:", a)
print("Your last guess was:", num)
print("It took you %s many tries" % x+1)

Python guessing game, my win condition prints win and loss

Im learning python and having a go at the guessing game. my game works but my win condition prints both "you win" and "you loss", I think my "if" statements are incorrect but i could be wrong.
Also, there's an issue with my printing of the win loss, I can only get it to print the loss..
Thanks in advance!
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
number = random.randint(1, 5)
chances = 0
print("Guess a number between 1 and 5:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
if not chances == 0:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
Try changing your loop. Since you're breaking if it's correct, you can use a while: else. Otherwise you can win on your last chance and still get the lose message.
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
In your while loop the if statement should be...
if guess == number:
print("Something)
win += 1
break
and the last if statement should be...
if win != 0:
print("You lose")
else:
print("You win")
The problem lies within the final if statement. The player loses if their chances are greater than the diceRoll, whereas the if condition is true if the player's chances are not 0 i.e. the player failed once.
The code for the final if statement should look something like this:
if chances >= diceRoll:
print("YOU LOSE!!! The number is", number)
loss += 1
As for the problems printing the win, the problem here is in the first if statement inside the while loop. If the player wins the break statement is encountered first, so the code breaks out of the while loop without incrementing the win counter.
Just swap the break statement with the win += 1 and it'll work wonders:
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
break
To start look at
the position of your break
the loss condition

How do I print this elif string

I am trying to create a guessing game and it works all well. However, I want to include a part where if a user puts a number above 100, you are told that your choice should be less than 100. The code below doesn't seem to do that. What am I doing wrong?
import random
comGuess = random.randint(0,100)
while True:
userGuess = int(input("Enter your guess :"))
if userGuess > comGuess:
print ("Please go lower")
elif userGuess < comGuess:
print ("Please go higher")
elif userGuess > (100):
print ("Your choice should be less than 100")
elif userGuess <1:
print ("Your choice should be less than 100")
else:
print ("Great, you got it right")
break
Any number above 100 will definitely be higher than the target, and enter the if condition. Any number below 1 will definitely be lower than the target, and enter the first elif. If you want to validate the user's input, you should do that before comparing it to comGuess:
if userGuess > (100):
print ("Your choice should be less than 100")
elif userGuess <1:
print ("Your choice should be less than 100")
elif userGuess > comGuess:
print ("Please go lower")
elif userGuess < comGuess:
print ("Please go higher")
else:
print ("Great, you got it right")
break
Your first if statement is catching anything greater than comGuess, even if it's also over 100, and so the elif userGuess > (100) that comes later never gets a chance to fire. Either move that elif up, or change the first if statement to something like if (userGuess > comGuess) and (userGuess <= 100).

Categories