I need help fixing my first program's bugs - python

I'm trying to write my first program that just gets an input from the user, selects a random number from 1 - 10, and checks to see if the user's number and computer's number matched.
Here's the code I tried:
def Num_Guess():
print("Hello! Welcome to the \"Guessing Game!\"")
import time
time.sleep(2)
print("Input a number from 1-10 and see if the computer has the same number!")
time.sleep(2)
User_Guess = input("Pick a number between 1 and 10: ")
def int_check(User_Guess):
if User_Guess.isnumeric() == True:
User_Guess = int(User_Guess)
def range_check(User_Guess):
if User_Guess == range(1,10):
print("Great! Your guess was", User_Guess, end='')
print("!")
return User_Guess
else:
print("Sorry, please pick a number between 1 and 10.")
time.sleep(2)
#Deletes the variable so that the global version does not override the local one.
del User_Guess
User_Guess = input("Pick a number between 1 and 10: ")
int_check(User_Guess)
range_check(User_Guess)
else:
print("Sorry, please pick a NUMBER between 1 and 10.")
time.sleep(2)
del User_Guess
User_Guess = input("Pick a number between 1 and 10: ")
int_check(User_Guess)
int_check(User_Guess)
time.sleep(2)
#Picks a random number between 1 and 10.
import random
n = random.randint(1, 10)
print("The computer picked" , n , end='')
print("!")
time.sleep(2)
if User_Guess == n:
print("The numbers match! You and the computer both picked" , User_Guess, end='')
print("!")
elif not User_Guess == n:
print("The numbers did not match. You picked" , User_Guess , "and the computer picked" , n , end='')
print(".")
time.sleep(2)
def Reset_Quit():
rq = input("Restart or quit? (r/q): ")
if rq == "r":
print("\n")
Num_Guess()
if rq == "q":
print("Quiting...")
time.sleep(2)
quit()
else:
print("Sorry, please say either \"r\" or \"q\".")
time.sleep(2)
Reset_Quit()
Reset_Quit()
Num_Guess()
What I'm trying to accomplish is:
Checking if the user's input is numeric or not. If yes, it will move on to the next step which is converting the string to an integer. If it is not, then it will simply make the user re-enter their input.
The next step will be checking if the input is within the range of 1 - 10. If it is, it will move on to comparing the user's input and the computer's to see if they match. If it is not, it will make the user redo their input and have it go through the numeral checking process again.
The final step is making the reset/quit promptly to not allow numbers or any other character that could cause the program to crash other than "r"/"R" or "q"/"Q".

I understood what the problem is.
In your range_check function, you are trying to match the user input with a range (which is a generator object) using ==. So instead use in keyword -
def range_check(User_Guess):
if User_Guess in range(1,11): # Here was the error
print("Great! Your guess was", User_Guess, end='')
...
Edit:
The program asks user to enter a number from 1-10, but program logic only accepts numbers 1-9. Rest of your code also uses the logic for including numbers 1-9 only. So correct the user input prompt to "number between 0-10" or "number from 1-9".
If you want to include 10 also:
use range(1, 11) and randint(1, 11)

Related

How do I compare the input value from one function, to the return value of another function?

I have a class project, where I am making a number guessing game. I have the following requirements:
#1. A main() function that holds the primary algorithm, but itself only passes information among other functions. main() must have the caller for random_int()
#2. A function called in main() (not nested in main()!) that compares the user's guess to the number from random_int() and lets the user know if it was too high or too low.
#3. A function called in main() that asks the user for a new guess.
#4. A function that prints out a string letting the user know that they won.
#5. Tell the user how many guesses it took them to get the correct answer.
I am currently having an issue trying to take the user inputted value "guess" and compare it with the value of a randomly generated integer "random_int" in a while loop in the function def high_low():
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
I either get the error "guess not defined" or '>' not supported between instances of 'function' and 'function'
Here is all of the code for context, note though that most of it below what I have posted above is pseudocode for the purposes of figuring out the logic of the game's function, and I have not yet gone through with debugging.
#Python number guessing game
#Import randrange module
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = (input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, new_guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
random_int(1000)
new_guess()
high_low(random, new_guess)
win()
main() #Calls the "main" function, runs the program
The code has a couple of issues I'll walk through all of them with an explanation so that we understand the reason why they happen at all. First we'll address all errors one by one.
Error-1
The first error on executing the code is '>' not supported between instances of 'function' and 'function'.
To understand that, notice the difference between Call-1 and Call-2 in below example code:
def f1():
return 1
def f2():
return 2
def less_than(n1, n2):
return n1 < n2
less_than(f1, f2) # Call-1: this will not work and give you error similar to what you get
less_than(f1(), f2()) # Call-2: this works
Call-1 passes the function itself, whereas Call-2 passes result of f1() and f2(), which are integers and can be compared by <.
In the code the main() needs to be rewritten like this:
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
Error-2
After above fix, executing will give another error:
NameError: name 'guess' is not defined
It means guess has not been defined. That's fixed by re-writing high_low() again like this. Notice the name new_guess replaced with guess. One is the function and other is the variable.
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Error-3
Again running would give this error:
TypeError: '>' not supported between instances of 'str' and 'int'
Fix is simple, the new_guess() function needs to convert input to int as calling input returns everything as string.
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
Error-4
Last error would be:
UnboundLocalError: local variable 'attempts' referenced before assignment
This simply means no value has been set to attempts before using it in attempts += 1
This gets fixed again by updating high_low and adding attempts = 0:
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
Final code looks like this:
from random import randrange
#Initialize variables
attempts = 0
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
def high_low(random_int, guess): #Lets the user know if the number they guessed is too high or too low
attempts = 0
while guess != random_int: #While loop to continue until user guesses correct number
if guess > random_int:
print("The number you guessed is too high, guess again.")
elif guess < random_int:
print("The number you guessed is too low, guess again.")
attempts+=1
guess = new_guess()
def win(random_int, new_guess): #Prints that the answer is correct, along with the number of guesses it took
while guess == random_int:
if attempts >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guesses.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
elif attempts < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number, you win! It took you ", str(attempts()), " guess.")
input("Would you like to play again? (Y/N): ")
if input == Y: #If user inputs "Y", runs the program again
main()
elif input == N: #If user inputs "N", terminates the program
break
def main(): #Function to call all functions in the program
r = random_int(1000)
n = new_guess()
high_low(r, n)
win()
main() #Calls the "main" function, runs the program
your high_low function has no reference to a variable named guess. I think the solution is to just add the line guess = new_guess() right before the while loop.

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!")

How to apply nested while loops in python function

I am learning python and trying to build a number guessing game.
The game will randomly generate integer between 1 to 250 (both inclusive) for user to guess. When user input is out of the range, it will prompt user that it is our of range and request another input. Likewise, it will prompt user if it is too high or too low until correct number is guessed. At any point in time if user input 'stop', it will end the game.
As part of the assignment requirement, i need to code 2 new functions on top of those already provided and incorporate it in the final run of the game.
I am trying to convert the while loops below to a function with not much progress. It either end with positional argument error or endless loop.
the_number = random.randint(1,250)
# capture initial user input
user_input = get_user_input()
# repeat code below as long as the user has not guessed the right number
while user_input != the_number:
# repeat code below as long as user has not entered STOP
while user_input != 'STOP':
# verify user input is within range
check_range(user_input)
if user_input < the_number:
slow_print("{} is too low". format(user_input))
print('\n')
user_input = get_user_input()
elif user_input > the_number:
slow_print("{} is too high". format(user_input))
print('\n')
user_input = get_user_input()
else:
slow_print("Congratulations you have guessed the correct number")
break
else:
slow_print('\nGame stopped by user. Thank you for playing')
break
Please can anyone suggest how I can convert the while loops into a function that works.
I'm not certain what you are trying to achieve, but if all you need to do is add a further 2 functions then perhaps this is what you're looking for;
the_number = random.randint(1,250)
# capture initial user input
user_input = get_user_input()
# repeat code below as long as the user has not guessed the right number
while user_input != the_number:
# repeat code below as long as user has not entered STOP
while user_input != 'STOP':
# verify user input is within range
check_range(user_input)
if user_input < the_number:
tooLow(user_input)
user_input = get_user_input()
elif user_input > the_number:
tooHigh(user_input)
user_input = get_user_input()
else:
slow_print("Congratulations you have guessed the correct number")
break
else:
slow_print('\nGame stopped by user. Thank you for playing')
break
def tooLow(number):
slow_print("{} is too low". format(number))
print('\n')
def tooHigh(number):
slow_print("{} is too high". format(number))
print('\n')

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!!!!!!!!!!!!!!!!")

Random number being changed within Python script

I'm working on a Python script where a user has to guess a random number, selected by the script. This is my code:
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
It works... Sort of... I was trying it and came across this:
User enters 2, it says it's incorrect, but then displays the same number!
I have the feeling that, every time I call the variable 'number', it changes the random number again. How can I force the script to hold the random number picked at the beginning, and not keep changing it within the script?
As far as I understand it, you want to pick a new random integer in every loop step.
I guess you are using python 3 and so input returns a string. Since you cannot perform comparisson between a string and an int, you need to convert the input string to an int first.
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
try:
antwoord = int(antwoord)
except:
print ("You need to type in a number")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break

Categories