I've been working on a sleep calculator that needs a validation error message. The code that I need to validate is:
hourspernight = int(input("How many hours do you sleep in a day?")
hoursperweek = hourspernight * 7
input("You Sleep for",hoursperweek,"hours every week!")
I need to add validation so that, if the user inputs a character that is not an integer, it shows an error message asking for an integer.
Use a try/except inside a while loop which will keep asking for input until the user enters something valid:
while True:
try:
hourspernight = int(input("How many hours do you sleep in a day?"))
break
except ValueError:
print("Invalid input")
hoursperweek = hourspernight * 7
print ("You Sleep for {} hours every week!".format(hoursperweek))
Related
im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)
I'm a Python beginner and tried to use try and except for the first time. I'm asking the user for an integer value but instead of ending the program if the user enters for example a string, I would like to ask the user again and again until an integer is given.
At the moment the user is only asked once to give another answer if he gives a string but if he gives a wrong input again, the program stops.
Below an example of what I mean.
I had a look through similar questions on Stackoverflow but I couldn't fix it with any of the suggestions.
travel_score = 0
while True:
try:
travel_score = int(input("How many times per year do you travel? Please give an integer number"))
except ValueError:
travel_score = int(input("This was not a valid input please try again"))
print ("User travels per year:", travel_score)
The problem is that there is no exception handling for your second input.
travel_score = 0
while True:
try:
travel_score = int(input("How many times per year do you travel? Please give an integer number"))
except ValueError:
# if an exception raised here it propagates
travel_score = int(input("This was not a valid input please try again"))
print ("User travels per year:", travel_score)
The best way to handle this is to put an informative message back to the user if their input is invalid and allow the loop to return to the beginning and re-prompt that way:
# there is no need to instantiate the travel_score variable
while True:
try:
travel_score = int(input("How many times per year do you travel? Please give an integer number"))
except ValueError:
print("This was not a valid input please try again")
else:
break # <-- if the user inputs a valid score, this will break the input loop
print ("User travels per year:", travel_score)
#Luca Bezerras answer is good, but you can get it a bit more compact:
travel_score = input("How many times per year do you travel? Please give an integer number: ")
while type(travel_score) is not int:
try:
travel_score = int(travel_score)
except ValueError:
travel_score = input("This was not a valid input please try again: ")
print ("User travels per year:", travel_score)
The problem is that once you thrown the ValueError exception, it is caught in the except block, but then if it is thrown again there are no more excepts to catch these new errors. The solution is to convert the answer only in the try block, not immediately after the user input is given.
Try this:
travel_score = 0
is_int = False
answer = input("How many times per year do you travel? Please give an integer number: ")
while not is_int:
try:
answer = int(answer)
is_int = True
travel_score = answer
except ValueError:
answer = input("This was not a valid input please try again: ")
print ("User travels per year:", travel_score)
I'm a python starter and need some help on a quiz like game.
This is my code:
import time
from threading import Timer
import random as rnd
q = ["q1", "q2", "q3"]
a = ["a1 b1 c1", "a2 b2 c2", "a3 b3 c3"]
ca = ["b", "c", "b"]
points = 0
rand_q = rnd.randint(0, len(q) - 1) # Choosing random question
print(q[rand_q] + "\n" + a[rand_q] + "\n") # Asking question and showing answers
time.sleep(0.5) # Little pause between prompts
t = Timer(10, print, ['Time is up!']) # Setting up timer
t.start() # Start timer
start = time.time() # Start of time check
answer = input("You have 10 seconds to choose the correct answer.\n") # User input
if answer is ca[rand_q]: # Check if answer is correct
print("Correct answer!")
points = (points + round(10 - time.time() + start, 1)) * 10 # Calculate points
else:
print("Wrong answer!")
t.cancel() # Stop timer
print("Points:", points)
input("Press ENTER to quit")
del q[rand_q] # Removing the question
del a[rand_q] # Removing the answer
del ca[rand_q] # Removing the correct answer
When I run this I can answer questions and get points, but whenver i wait out the timer I get a prompt saying the time is up, but I can still fill in and answer the question.
I want the input to stop working after the 10 seconds, but I can't seem to make this work. Is there any way I can make the timer timeout all previous inputs on top of the "Time is up" prompt.
I've seen more posts like this but they seem outdated and I didn't get them to work.
EDIT: the sleep command doesn't work. It prints a line saying it's too late but you can still enter an answer after. Same for the threading timer. I want to terminate the input command after 10 seconds, but there seems to be no solution for windows.
The problem is that python's input function is blocking, which means the next line of code will not be executed until the user enters some data. A non blocking input is something that a lot of people have been asking for, but the best solution would be for you to create a separate thread and ask the question on there. This question has sort of been answered in this post
This solution will work except the user will still have to press enter at some point to progress:
import time
import threading
fail = False
def time_expired():
print("Too slow!")
fail = True
time = threading.Timer(10, time_expired)
time.start()
prompt = input("You have 10 seconds to choose the correct answer.\n")
if prompt != None and not fail:
print("You answered the question in time!")
time.cancel()
You can do what you intend to do, but it gets very complicated.
I have created a simple program which asks for a user's name and age. The program will then take the details from a textbox and work out how old they will be in 5 years time.
The interface is fine. It's the validation that I am having difficulty with. When a user enters a letter instead of a number the program shows an error message, but continues to run regardless. I have tried using a while True: loop but this seems to just crash the program.
Here's what I have written already:
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
if age.isalpha():
tkinter.messagebox.showinfo("Error", "The Age is invalid")
textboxAge.delete("0","end")
newAge = int(age)+5
print("Hello",name)
print("In 5 years time you will be",newAge)
I have looked at a few other tutorials but they are a little confusing. I am going to extend this by adding another elif in and the following code
elif age >= 100:
tkinter.messagebox.showinfo("Error", "You have entered a number greater than 100")
textboxAge.delete("0","end")
but this doesn't like the fact it is a string not an integer.
What would be the best way to check to see if a number has been entered into a textbox?
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
try:
newAge = int(age)+5
except ValueError:
tkinter.messagebox.showinfo("Error", "The Intended Reading Age is invalid")
textboxAge.delete("0","end")
return
print("Hello",name)
print("In 5 years time you will be ",newAge)
# ...
If an error occurs somewhere in the try-section, python will not crash, but rather jump to the except part. The critical step is converting age into integer. This throws a ValueError if it is a string. In this case, the message box is shown and the text in your textbox is deleted. return then will stop the function, so the rest of it won't be processed. If nothing happens in the try-section, then except will be skipped.
I start my python script asking the user what they want to do?
def askUser():
choice = input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?");
print ("You entered: %s " % choice);
I would then like to:
Confirm the user has entered something valid - single digit from 1 - 4.
Jump to corresponding function based on import. Something like a switch case statement.
Any tips on how to do this in a pythonic way?
Firstly, semi-colons are not needed in python :) (yay).
Use a dictionary. Also, to get an input that will almost certainly be between 1-4, use a while loop to keep on asking for input until 1-4 is given:
def askUser():
while True:
try:
choice = int(input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?"))
except ValueError:
print("Please input a number")
continue
if 0 < choice < 5:
break
else:
print("That is not between 1 and 4! Try again:")
print ("You entered: {} ".format(choice)) # Good to use format instead of string formatting with %
mydict = {1:go_to_stackoverflow, 2:import_from_phone, 3:import_from_camcorder, 4:import_from_camcorder}
mydict[choice]()
We use the try/except statements here to show if the input was not a number. If it wasn't, we use continue to start the while-loop from the beginning.
.get() gets the value from mydict with the input you give. As it returns a function, we put () afterwards to call the function.