Can't put limits to randint in python - python

Also the program doesn't show any error. And I can't find my error. When I run this code it says that my random number is either infinitely higher or lower
import random
def game1():
print("Hello I guessed a number, try to find it")
my_number = int(input("Guess the number:"))
a = random.randint(1,5)
number_of_tries = 1
while a != my_number:
if a > my_number:
print("Your number must be higher")
number_of_tries = number_of_tries+1
player_guess = int(input("Guess the number:"))
if a < my_number:
print("Your number must be lower")
number_of_tries = number_of_tries + 1
player_guess = int(input("Guess the number:"))
if a == my_number:
print("Congrats, you guessed the number")
print("Number of guesses is:", number_of_tries)
break
game1()

you assign the subsequent guesses to player_guess rather than my_number...
I'd tidy the code up to something like:
a = random.randint(1, 5)
number_of_tries = 0
print("Hello I guessed a number, try to find it")
while True:
my_number = int(input("Guess the number:"))
number_of_tries += 1
if a == my_number:
break
if a > my_number:
print("Your number must be higher")
if a < my_number:
print("Your number must be lower")
print("Congrats, you guessed the number")
print("Number of guesses is:", number_of_tries)

Required very little correction. just replace player_guess with my_number.
Basically, you are comparing a with my_number, and at first you store user input to my_number, if it is matched there is no problem. but when it don't match and the user requested to give another guess, the input stored in player_guess, but still compare a with player_guess (rather then with my_number). this should be corrected.

Related

How to use a loop to make something repeat until conditions are met? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 months ago.
I'm trying to make a simple number guessing game. I wanted to try to see if I could do this myself without looking up any answers but I'm very confused on how to keep the game going if the guess is not correct. Here is what I have so far:
import random
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
#create random number:
computer_number = random.randint(0, 100)
#How can i make this block of code loop to keep on giving the user tries??
if guess == computer_number:
print("You won")
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
import random
#ask user to guess a number:
#create random number:
computer_number = random.randint(0, 100)
#How can i make this block of code loop to keep on giving the user tries??
while True:
guess = int(input("Guess a number from 0 to 100: \n"))
if guess == computer_number:
print("You won")
break
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
You could use a while loop to loop the game until a condition is met.
For example:
#create random number:
computer_number = random.randint(0, 100)
while True:
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
#How can i make this block of code loop to keep on giving the user tries??
if guess == computer_number:
print("You won")
break
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
it's very easy you just need an while loop:
while condition:
#while condition True run what stands here
So the answer to your question is:
import random
#create random number:
computer_number = random.randint(0, 100)
guess = -1
#we need to firs declare the variables so we can use them in the condition
while guess != computer_number:
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
if guess == computer_number:
print("You won!")
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")

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````

Python Guessing Game Reject Invalid User Input

I'm taking my first-ever Python class and, like most Python classes, the last assignment is to create a guessing game from 1-100 that tracks the number of VALID tries. The element that I just cannot get (or find here on stackoverflow) is how to reject invalid user input. The user input must be whole, positive digits between 1 and 100. I can get the system to reject everything except 0 and <+ 101.
The only things I can think to do end up telling me that you can't have operators comparing strings and integers. I keep wanting to use something like guess > 0 and/or guess < 101. I've also tried to create some sort of function, but can't get it to work right.
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
# Check if input is a positive integer and is not 0 or >=101
# this line doesn't actually stop it from being a valid guess and
# counting against the number of tries.
if guess == "0":
print(guess, "is not a valid guess")
if guess.isdigit() == False:
print(guess, "is not a valid guess")
else:
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
try:
guess = int(guess)
if(100 > guess > 0):
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
else:
print("Number not in range between 0 to 100")
except:
print("Invalid input")
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 1
while True:
try:
guess = int(input("Try to guess my number: "))
if guess > 0 and guess < 101:
print("That's not an option!")
# Begin playing
elif guess == x:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
elif guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
counter += 1
except:
print("That's not a valid option!")
My instructor helped me out. (I posted to keep from needing that from the guy who's giving me the grade.) Here is what we came up with. I'm posting it to help out any future Python learner that may have this particular rejecting user input problem.
Thank you guys for posting SO FAST! Even though I needed the instructor's help, I would've looked even more incompetent without your insights. Now I can actually enjoy my holiday weekend. Have a great Memorial Day weekend!!!
import random
x = random.randint(1,100)
print("I'm thinking of a number from 1 to 100.")
counter = 0
while True:
try:
guess = input("Try to guess my number: ")
guess = int(guess)
if guess < 1 or guess > 100:
raise ValueError()
counter += 1
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
except ValueError:
print(guess, "is not a valid guess")

number guessing game with hints after certain number of tries. python

Thank you for your patience everyone.
Thank you Ben10 for your answer. (posted below with my corrected print statements) My print statements were wrong. I needed to take the parenthesis out and separate the variable with commas on either side.
print("It only took you ", counter, " attempts!")
The number guessing game asks for hints after a certain number of responses as well as the option to type in cheat to have number revealed. One to last hints to to let the person guessing see if the number is divisible by another number. I wanted to have this hint available until the end of the game to help narrow down options of the number.
Again thank you everyone for your time and feedback.
guessing_game.py
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: ", random_) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 10:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by ", divisor, ". ")
else:
print("Not it quite yet, The random number is NOT divisible by ", divisor, ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is ", cheat, ".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you ", counter, " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
I rewrite the code, to allow it to be more versitile. Noticed quite a few errors, like how you forgot to put a closing bracket at the end of a print statement. Also in the print statements you were doing String concatenation (where you combine strings together) incorrectly.
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: " + str(random_)) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 5:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by " + str(divisor) + ". ")
else:
print("Not it quite yet, The random number is NOT divisible by " + str(divisor) + ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is " + str(cheat) +".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you " + str(counter) + " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")

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