I'm trying to get the user guess the number the computer is producing randomly. When passing the return function nothing shows up.
user = 0
result = ""
import random
print ("Welcome to Guess My Number Game")
def main():
#user input
computer = random.randint(1,100)
print(computer)
user=int(input("Guess the number:"))
return (result)
def results(result):
computer = random.randint(1,100)
diff = 0
diff = user - computer
if diff < -10:
result = ("Too Low")
elif diff > 10:
result = ("Too High")
elif diff < 0:
result = ("Getting warmer, but still low")
elif diff > 0:
result = ("Getting warmer, but still high")
else:
guesses = str(guesses)
result = ('Good job, you guessed correctly in,',guesses,'guesses!')
There are couple of problems in your indentation however, if I can understand the logic correctly, you can do something similar to the below in order to keep user asking for a guess till getting a match;
import random
def results(val):
guesses = 0
while True:
user = int(input("Guess the number: "))
guesses = guesses + 1
diff = user - computer
if diff < -10:
print("Too Low")
elif diff > 10:
print("Too High")
elif diff < 0:
print("Getting warmer, but still low")
elif diff > 0:
print("Getting warmer, but still high")
else:
print('Good job, you guessed correctly in {} guesses!'.format(guesses))
break
return guesses
def main():
computer = random.randint(1, 100)
number_of_guesses = results(computer)
>>> results()
Guess the number: 2
Too Low
Guess the number: 10
Too Low
Guess the number: 50
Too High
Guess the number: 40
Too High
Guess the number: 30
Getting warmer, but still high
Guess the number: 25
Getting warmer, but still low
Guess the number: 26
Getting warmer, but still low
Guess the number: 28
Getting warmer, but still low
Guess the number: 29
Good job, you guessed correctly in 9 guesses!
9
I'm going to assume that you are trying to print the result variable from the results method
If my above statement is correct you have a misunderstanding about what return does. return is usually placed in a function to that will return some value. So you should make your code into this.
computer = random.randint(1,100)
print(computer) #if you print this guessing the number will be very easy
user=int(input("Guess the number:"))
print(results(computer, user))
def results(computer, user):
results = ""
# computer = random.randint(1,100) #you wont need this either
diff = 0
diff = user - computer
if diff < -10:
result = ("Too Low")
elif diff > 10:
result = ("Too High")
elif diff < 0:
result = ("Getting warmer, but still low")
elif diff > 0:
result = ("Getting warmer, but still high")
else:
guesses = str(guesses)
result = ('Good job, you guessed correctly in,',guesses,'guesses!')
return result
Related
The aim of this code is to get the computer to generate a random number and let the user try and guess what that number is in however many tries they choose. However, when they fail to guess correctly the program is supposed to print "You have failed in (x) tries" just once. Unfortunately this line keeps looping over and over again. Where have I gone wrong?
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
print (f"You have guessed {random_number} correctly")
guess(10)
It was looping forever because the incrementation of tries was done in the else block and there is no break keyword in else block too.
So, move tries = tries+1 in the if tries <limit: block and put break inside the else block as shown below:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
tries = tries + 1 # <--- move here
else:
print(f"You have failed in {limit} tries")
break; # <--- put break
print (f"You have guessed {random_number} correctly")
guess(10)
You need to keep a check of the tries.
You need to print the statement only in the user input is correct:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while tries<limit:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print (f"You have guessed {random_number} correctly")
break
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
guess(10)
You can use a for loop:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
found=False
for i in range(limit):
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
found=True
break
if found:
print (f"You have guessed {random_number} correctly")
else:
print(f"You have failed in {limit} tries")
guess(10)
There are multiple logical errors in your code,
the condition you are using in the while loop, guess != random_number, is to check if a number has been guessed correctly or not, not to check if the total number of guesses are exhausted.
No matter what happens, when the code will exit the while loop it will show the user that he/she has guessed correctly
Changing your code to take this into consideration will fix your problem. Below is a possible solution:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
# Flag to check if the user is guessing the right or wrong value
# Default assumption is that user is guessing incorrectly
UserGuess = False
while tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
# Changing flag and stopping the loop if the user guesses correctly
UserGuess = True
break
tries = tries + 1
if UserGuess:
print (f"You have guessed {random_number} correctly")
else:
print (f"You have failed in {limit} tries")
guess(10)
need help with a higher or lower game I think the problem has something to do with the loop. I have been told been told to add an except but I have no idea where to add it
print('Welcome to higher or lower game')
input('press enter to start.\n')
import random
Max = 10
Min = 0
num = random.randint(1, 10)
print('your starting number is a ' + str(num))
while 'well done.\n' :
guess = input('higher (h) or lower (l).\n')
new_num = random.randint(1, 10)
print('your new number is a ' + str (new_num))
try :
if new_num > num and guess == 'h':
print('well done.\n')
elif new_num < num and guess == 'l':
print('well done.\n')
break
if num and guess == 'l' and new_num > num and guess:
print('game over')
elif num and guess == 'h' and new_num < num and guess:
print('game over')
else:
print('game over you got a score of ' + str(score))
You do not have an except clause in the try statement. That clause is required unless you have a finally clause.
You really shouldn't have a try statement there. You could take it out and just go with some if and elif statements.
Example:
import random
number = random.randint(1,10)
lives = 3
Success = False
while lives > 0:
guess = int(input("What is your guess between 1 and 10? \r\n"))
if guess > number:
print("Too high! Go lower. \r\n")
lives -= 1
elif guess < number:
print("Too low! Go higher. \r\n")
lives -= 1
elif guess == number:
print("Congratulations, you win!")
global Success = True
break
if Success != True:
print("Sorry. Try again! The number was ", number, ".")
As far as I understand, try statements are mainly used for error handling.
Running Python code for guessing game - if guess number outside of range - do not want it to count against tries. Code works but counts erroneous numbers as tries.
My code:
import random
print("The number is between 1 and 10")
print("You have 5 tries!")
theNumber = random.randrange(1,10)
maxTries = 5
tries = 1
guess = int(input("Take a guess: "))
while ((tries < maxTries) & (guess != theNumber)):
try:
if guess > theNumber:
print("Guess lower...")
elif guess < theNumber:
print("Guess higher...")
if guess > 10:
raise ValueError
except ValueError:
print("Please enter a numeric value between 1 and 10.")
#continue
guess = int(input("Guess again: "))
tries = tries + 1
if(guess == theNumber):
print("You guessed it! The number was", theNumber)
print("And it only took you", tries, "tries!\n")
else:
print("You failed to guess", theNumber, "!")
It allows continued guessing up to 5 tries as long as guess is between 1 and 10. If outside of this range - it will not count as a try but tells the user to "Please enter a numeric value between 1 and 10"). Which the code does - it just counts those tries when I do not want it to work that way.
Try this one:
import random
min_number = 1
max_number = 10
number = random.randrange(min_number, max_number + 1)
print(number) # To know the number you are guessing
maximum_tries = 5
print(f"The number is between {min_number} and {max_number}")
print(f"You have {maximum_tries} tries!")
guess = int(input("Take a guess: "))
j = 1
while True:
if guess > max_number or guess < min_number:
print("Please enter a numeric value between 1 and 10.")
j = j - 1
elif guess > number:
print("Guess lower...")
print("You failed to guess", j, "!")
elif guess < number:
print("Guess higher...")
print("You failed to guess", j, "!")
if guess == number:
print("You guessed it! The number was", number)
print("And it only took you", j, "tries!\n")
break
if j == maximum_tries:
break
guess = int(input("Guess again: "))
j = j + 1
So i'm working on a guessing number game and one of the requirements is for the "range" of numbers to be updated so that the user with have an easier time with their guess'. I created a new input for when the number is either too high or too low. However, i'm not very good with loops and I can't figure out why my loop is repeating only once without my pasting the code over and over again. Can anyone help so the elif statements will repeat until the number is correct?
This is my code thus far...
import random
random_number = random.randint(1,100)
tries = 0
while tries < 800:
guess = input("Guess a random number between 1 and 100.")
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > 0 or not guess_num < 101:
print("That number is not between 1 and 100.")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess_high = input("Guess a number between 0 and {} .".format(guess_num))
elif guess_num < random_number:
print("Sorry that number is too low.")
guess_low = input("Guess a number between {} and 100 .".format(guess_num))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
import random
random_number = random.randint(1,100)
tries = 0
guess = input("Guess a random number between 1 and 100.")
while tries < 800:
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > 0 or not guess_num < 101:
print("That number is not between 1 and 100.")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess = input("Guess a number between 0 and {} .".format(guess_num))
elif guess_num < random_number:
print("Sorry that number is too low.")
guess = input("Guess a number between {} and 100 .".format(guess_num))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
Do not use break, as they terminate the while loop. See python language reference.
You should ask only once for guess_num. Remove the two input when the guess is too high or too low (BTW variable name guess was incorrect).
The last condition (out of tries) should be outside the while loop, since it will be executed when the number of tries is over 800.
Hint. A user can play this game with the equivlent of a binary search (start with 50, then guess 25 or 75 depending if higher/lower, etc). You should allow about 8 tries (not 800).
Here is how to update the ranges:
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 800:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
For which case does your loop only repeats once?
The loop would break (since you have a break statement in line 15 under the "if not guess_num > 0 or not guess_num < 101:") if the input guess is less than 0 or greater than 100.
If the user input an incorrect guess between 1 and 100, then the code does loop and hence the user is asked to input another number.
Although it does loop, the loop is not updating the range.
What you can do is set range_min and range_max as variables and change these variables according to if the guess is too low or too high.
See the following code:
import random
random_number = random.randint(1,100)
tries = 0
range_min = 0
range_max = 100
while tries < 800:
guess = input("Guess a random number between " + str(range_min +1) + " and " + str(range_max))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > range_min or not guess_num < (range_max+1):
print("That number is not between str(range_min +1) + " and " + str(range_max)")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess_high = input("Guess a number between 0 and {} .".format(guess_num))
range_max = guess_num
elif guess_num < random_number:
print("Sorry that number is too low.")
guess_low = input("Guess a number between {} and 100 .".format(guess_num))
range_min = guess_num
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
Here is how I would do it. Not sure if it works but the approach would be:
import random
random_number = random.randint(1,100)
max_tries = 100
tries = 0
left = 0
right = 100
found = False
def get_number():
try:
guess = int(input("Guss a random number between {} and {}".format(left, right)))
if guess > right or guess < left:
print("That number is not between {} and {}".format(left, right))
return guess
except:
print("That's not a whole number!")
get_number()
def update_range(guess):
if guess >= left:
left = guess
else:
right = guess
while tries <= max_tries and not found:
guess = get_number()
tries=+1
if guess == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
found = True
else:
update_range(guess)
if not found:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
As you can see I am using helper functions in order to reduce the number of if/else structures.
Also updating the range is necessary. And thanks to parametrized strings I can tell the user what's the range.
I also set a flag to know whether the user found the number or not at the end of the game
Python loop isn't wanting to loop back if the user's guess is greater than or less than the randomly generated value. It either exits the loop or creates an infinite loop. Where am I going wrong?
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 <= guess <= 100:
inputcheck = False
else:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries >= 7:
print("Sorry, you only have 7 guesses...")
keepGoing = False
The problem is with this line:
if 0 <= guess <= 100:
inputcheck = False
This will terminate the loop whenever the user enters a number between 0 and 100. You can rewrite this part as:
if not 0 <= guess <= 100:
print("Choose a number in the range!")
continue
The correct code is below:
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 > guess or guess > 100:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False
The problem here was that you were setting inputcheck to False when the value of guess was in between 0 and 100. This changed the value of while to False and the loop was exiting since while wasn't True anymore.
Also, you should change the last if case in the while loop since this now fixes the case of running indefinitely:
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False