adding a loop to high and low game - python

#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

Related

How do I count only as one attempt if they input the same number multiple times consecutively?

Tried to make a guessing game that counts the number of attempts but I don't know how to count only as one attempt if they input the same number multiple times consecutively
import random
repeat = 'y'
i=1
while repeat.lower() == 'y':
n = int(input("Enter value of n(1 - 100) "))
n2 =int(input("Enter value of n2(1 - 100) "))
a= random.randrange(n, n2)
guess = int(input("Guess the hidden number"))
while guess !=a:
print('entry number:',i)
if guess<a:
print("you need to guess higher. Try again")
guess = int(input("Guess the hidden number"))
if guess>a:
print("you need to guess lower. Try again")
guess = int(input("Guess the hidden number"))
if guess == a:
print('it took you:',i,'tries to guess the hidden number')
print('Congratulations, the hidden number is',a)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('thank you')
break
This should do it.
You may also want to also store the two numbers in a list and sort the list after getting them so the program does not crash if the second number is lower.
You may want to print out the number of guesses it took when a user gets the correct answer.
import random
repeat = 'y'
i=0
while repeat.lower() == 'y':
n = int(input("Enter value of n(1 - 100) "))
n2 =int(input("Enter value of n2(1 - 100) "))
a= random.randrange(n, n2)
guess = int(input("Guess the hidden number"))
guessList = []
while guess != a:
if guess not in guessList:
print('here')
guessList.append(guess)
i += 1
print('entry number:',i)
if guess<a:
print("you need to guess higher. Try again")
guess = int(input("Guess the hidden number"))
if guess>a:
print("you need to guess lower. Try again")
guess = int(input("Guess the hidden number"))
if guess == a:
print('it took you:',i,'tries to guess the hidden number')
print('Congratulations, the hidden number is',a)
else:
print("Duplicate guess try again.")
guess = int(input("Guess the hidden number"))
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('thank you')
break````

How to make if statement check each for loop statement for valid input

import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (computer_choice) in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if user_choice == computer_choice:
print("Thank you for playing. ")
Needs to give the user 5 chances to give the computer_choice before failing. For loop is required.
You can add a counter which will keep the track of the number of attemps that user has made so far.
Also need to convert user input from string to int type.
import random
max_value = int(input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? "))
computer_choice = random.randint(1, int(max_value))
count = 0
for (computer_choice) in range(1,6):
user_choice = int(input("What number between 1 and " + max_value + " do you choose? "))
count += 1
if user_choice == computer_choice:
print("Thank you for playing. ")
if count==5:
print("you have reached maximum attempt limit")
exit(0)
Run the for loop with separate variable then computer_choice. Also add eval to input statement as it gives string to conert the user_choice to integer and add a break statement in if user_choice == computer_choice to end the program, rest should work fine.
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for (i) in range(1,6):
#input takes string convert choice to int using eval
user_choice = eval(input("What number between 1 and " + max_value + " do you choose? "))
if user_choice == computer_choice:
print("Thank you for playing. ")
break
if(i==5):
print("Sorry, maximum number of tries reached.")
One of the approach:
import random
max_value = input("I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? ")
computer_choice = random.randint(1, int(max_value))
for i in range(1,6):
user_choice = input("What number between 1 and " + max_value + " do you choose? ")
if int(user_choice) == int(computer_choice):
print("Right choice. Thank you for playing. ")
break
elif(i == 5):
print ("Sorry, maximum attempts reached...")
break
else:
print ("Oops, wrong choice, pls choose again...")
Output:
I'm going to pick a number. You have to try and guess the same number that I pick. Guess right and win a prize. What is the highest number I can pick? 5
What number between 1 and 5 do you choose? 1
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 3
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 4
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 5
Oops, wrong choice, pls choose again...
What number between 1 and 5 do you choose? 6
Sorry, maximum attempts reached...

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()

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

Want the game to terminate after 6 trials

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

Categories