Why does my function keep looping and how can i fix it? - python

import time
import random
import sys
def code():
user_num=()
user_num=int(input("What number do you want from 0-30"))
if user_num>30:
print("number needs to be smaller")
print("restart code and try again")
else:
pass
if user_num<0:
print("your number needs to be greater")
print("restart code and try again")
else:
pass
code()
code()
random_num=random.randint(0,1)
if random_num==user_num:
print("your number is correct")
else:
print("your number is incorrect")
time.sleep(1)
try_again=input("do you want to try again (yes/no")
if try_again=="yes":
code()
else:
print("ok. Bye")
i am very new to functions so sorry if this is a rookie mistake. Any help with functions will be appreciated. Thank You.

At the very end of the "code" function you're calling it again

Try this:
import time
import random
import sys
def code():
user_num=()
user_num=int(input("What number do you want from 0-30"))
if user_num>30:
print("number needs to be smaller")
print("restart code and try again")
else:
pass
if user_num<0:
print("your number needs to be greater")
print("restart code and try again")
else:
pass
return user_num
random_num=random.randint(0,1)
user_num = code()
if random_num==user_num:
print("your number is correct")
else:
print("your number is incorrect")
time.sleep(1)
try_again=input("do you want to try again (yes/no")
if try_again in "yes":
user_num = code()
else:
print("ok. Bye")

Related

How do I correctly use isinstance() in my random number guessing game or is another function needed?

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break

not restarting for program and input integer not working

I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!!
import random
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
while True:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
else:
guess1=int(guess[0])
guess2=int(guess[1])
guess3=int(guess[2])
guess4=int(guess[3])
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
answer=input("Would you like to play again? (Yes or No) ")
if answer==Yes:
print ('Yay')
continue
else:
print ('Goodbye!')
break
Wrap your game in a function eg:
import sys
def game():
#game code goes here#
Then at the end, call the function to restart the game.
if answer=='Yes': # You forgot to add single/double inverted comma's around Yes
print ('Yay')
game() # calls function game(), hence restarts the game
else:
print ('Goodbye!')
sys.exit(0) # end game
try this
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
gueses=[]
while len(gueses)<=3:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
gueses.append(guess)
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
guess1=gueses[0]
guess2=gueses[1]
guess3=gueses[2]
guess4=gueses[3]
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
if P1=="x" and P2=="x" and P3=="x" and P4=="x":
print("you won")
else:
print("YOUE LOSE")
print("TRUE ANSWERS", A1,A2,A3,A4)
print("YOUR ANSWER", gueses)
game()
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print ('Yay')
game()
else:
print ('Goodbye!')
The previous answers are good starts, but lacking some other important issues. I would, as the others stated, start by wrapping your game code in a function and having it called recursively. There are other issues in the guess=int(input("\nTry and Guess the Numbers :). ")). This takes one integer as the input, not an array of integers. The simplest solution is to turn this into 4 separate prompts, one for each guess. I would also narrow the scope of your error test. I've included working code, but I would read through it and make sure you understand the logic and call flow.
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
if P1=="O" or P2=="O" or P3=="O" or P4=="O":
print("Here is your Clue :) :")
print(P1,P2,P3,P4)
try:
guess1=int(input("\nGuess 1 :). "))
guess2=int(input("\nGuess 2 :). "))
guess3=int(input("\nGuess 3 :). "))
guess4=int(input("\nGuess 4 :). "))
except ValueError:
print("Invalid Input")
continue
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
break
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print('Yay')
game()
else:
print('Goodbye!')
game()

How do I check if the user has entered a number?

I making a quiz program using Python 3. I'm trying to implement checks so that if the user enters a string, the console won't spit out errors. The code I've put in doesn't work, and I'm not sure how to go about fixing it.
import random
import operator
operation=[
(operator.add, "+"),
(operator.mul, "*"),
(operator.sub, "-")
]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
print("Correct")
score += 1
try:
val = int(input())
except ValueError:
print("That's not a number!")
else:
print("Incorrect")
if num_of_q==10:
print(name,"you got",score,"/",num_of_q)
You need to catch the exception already in the first if clause. For example:
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
print("What is",num1,symbol,num2,"?")
try:
outcome = int(input())
except ValueError:
print("That's not a number!")
else:
if outcome == op(num1, num2):
print("Correct")
score += 1
else:
print("Incorrect")
I've also removed the val = int(input()) clause - it seems to serve no purpose.
EDIT
If you want to give the user more than one chance to answer the question, you can embed the entire thing in a while loop:
for _ in range(num_of_q):
num1=random.randint(0,10)
num2=random.randint(1,10)
op,symbol=random.choice(operation)
while True:
print("What is",num1,symbol,num2,"?")
try:
outcome = int(input())
except ValueError:
print("That's not a number!")
else:
if outcome == op(num1, num2):
print("Correct")
score += 1
break
else:
print("Incorrect, please try again")
This will loop eternally until the right answer is given, but you could easily adapt this to keep a count as well to give the user a fixed number of trials.
Change
print("What is",num1,symbol,num2,"?")
if int(input()) == op(num1, num2):
to
print("What is",num1,symbol,num2,"?")
user_input = input()
if not user_input.isdigit():
print("Please input a number")
# Loop till you have correct input type
else:
# Carry on
The .isdigit() method for strings will check if the input is an integer.
This, however, will not work if the input is a float. For that the easiest test would be to attempt to convert it in a try/except block, ie.
user_input = input()
try:
user_input = float(user_input)
except ValueError:
print("Please input a number.")

Would like to know how to add some code to make my program be able to deal with letters being inputted

My program is a simple arithmetic quiz however i want to know how to make it so that it doesn't just stop when i don't enter in an integer.
questionNo=0
score=0
name=input("What is your name?")
print("Welcome ",name," to your arithmetic quiz!")
time.sleep(1)
while questionNo<10:
function=random.randint(1,3)
if function==1:
rNumber1=random.randint(1,100)
rNumber2=random.randint(1,100)
print("Question is : ", rNumber1," + ",rNumber2)
guess=int(input("What is the answer?"))
ans=rNumber1+rNumber2
if ans==guess:
print("Correct!")
score+=1
time.sleep(1)
else:
print("Wrong")
time.sleep(1)
elif function==2:
rNumber1=random.randint(1,10)
rNumber2=random.randint(1,10)
print("Question is : ", rNumber1," X ",rNumber2)
guess=int(input("What is the answer?"))
ans=rNumber1*rNumber2
if ans==guess:
print("Correct!")
score+=1
time.sleep(1)
else:
print("Wrong")
time.sleep(1)
else:
rNumber1=random.randint(1,100)
rNumber2=random.randint(1,100)
print("Question is : ", rNumber1," - ",rNumber2)
guess=int(input("What is the answer?"))
ans=rNumber1-rNumber2
if ans==guess:
print("Correct!")
score+=1
time.sleep(1)
else:
print("Wrong")
time.sleep(1)
questionNo+=1
print("Well done ",name,"! You got ",score,"/10")
Wrap your call to int(input()) in a try-except clause.
Trying to convert a value of type str to int will always raise a ValueError exception.
So, wherever you want to catch this illegal conversion, meaning, whenever int(input()) is called, wrap it in the try-except in order to handle it:
try:
guess = int(input("What is the answer?"))
except ValueError:
print("You must enter a number as the answer!")
continue
And don't increment the questionNo counter in the except clause in order to keep the same number of questions in total.

Python - Checking for an empty input + script troubles

I am very knew to Python, so as expected, I'm encountering problems often when scripting and am usually not sure how to fix them.
I'm making a small game where you try and guess a number which the program has randomly chosen. I've gotten pretty far, but I noticed the program simply displayed an error message when I input nothing. I would like the program to display the text "Enter a number." in this situation, and then prompt the "Your guess: " input again, but after a lot of research, I'm really not sure how to successfully implement that feature into my code. My issue, specifically, is the "try and except" section - I don't really know how to write them properly, but I saw another post on here suggesting to use them.
import random
def question():
print("Guess a number between 1 and 100.")
randomNumber = random.randint(1, 100)
found = False
while not found:
myNumber = int(input("Your guess: "), 10)
try:
myNumber = int(input("Your guess: "), 10)
except ValueError:
print("Enter a number.")
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
question()
You should be able to see my intentions in the code I've written, thanks.
You're almost right. Just continue to the next iteration after handling exception.
import random
def question():
print("Guess a number between 1 and 100.")
randomNumber = random.randint(1, 100)
found = False
while not found:
try:
myNumber = int(input("Your guess: "), 10)
except Exception:
print('Enter a number.')
continue
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
question()
You can write a function like this:
def input_num(input_string):
""" This function collects user input
Args:
input_string: message for user
Return:
user_input: returns user_input if it is a digit
"""
user_input = raw_input("{}: ".format(input_string))
if not user_input.isdigit():
input_num(input_string)
return int(user_input)
then call this function
user_num = input_num("Enter a number")
It will keep asking a user to provide a valid input until user puts one
I'm confused why you ask for the input twice. You only need to ask them for input once. After that, you need to add a continue to your except statement. Otherwise, it will not repeat and just end the program. This is what your modified while loop should look like.
while not found:
try:
myNumber = int(input("Your guess: "), 10)
except ValueError:
print("Enter a number.")
continue
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
Just use the continue keyword in your except to continue the loop.
except ValueError:
print('Enter a number')
continue

Categories