How do i handle ValueError in this code Python? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I've done this before but i think this error is showing up because I'm not looping the code, the code works only once then on the second attempt is shows an error.
My Code:
import string
import time
def timer(x):
for n in range(x,0,-1):
time.sleep(1)
print(n)
print("Times Up"+"\n")
ask("Time for: ")
def ask(a):
x=int(input(str(a)))
print("\n"+"Clock's Ticking")
timer(x)
try:
ask("Time for: ")
except ValueError:
ask("Enter a number to time: ")
I want my code to not error when i put in something that isnt a integer for the time but dont know how to loop the exception code until the user enters a integer.

Move the exception handling to ask function:
import string
import time
def timer(x):
for n in range(x,0,-1):
time.sleep(1)
print(n)
print("Times Up"+"\n")
ask("Time for: ")
def ask(a):
x = None
while x is None:
try:
x=int(input(str(a)))
except ValueError:
print('Enter a number to time!')
timer(x)
ask("Time for: ")

Related

Square a number function challenge doesn't work [duplicate]

This question already has answers here:
How is returning the output of a function different from printing it? [duplicate]
(9 answers)
Closed 2 months ago.
The challenge is to square an input number.
import sys
# import numpy as np
# import pandas as pd
# from sklearn import ...
def square(x):
return print(x ** 2)
for line in sys.stdin:
print(line, end="")
I don't know how to use sys.stdin I guess because I don't know how to pass through the challenge test inputs for x.
Apologies, but I can't find any answers.
If you want to read lines from standard input, you can use input. It will raise EOFError at end of file. To read lines successively and handle them you can just read in a loop with an exception handler for EOFError.
try:
while True:
line = input()
x = int(line)
print(square(x))
except EOFError:
pass
Or for fun, wrap this up in a function that yields out the lines.
def read_stdin():
try:
while True:
yield input()
except EOFError:
pass
for line in read_stdin():
print(square(int(line)))

Dealing with an error without defining what the correct answer is [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'd like to deal with an input error without defining what the success criteria is i.e. only loop back round the user input turns out to be incorrect. All of the examples I can find require a definition of success.
Rather than list all the possible units as "success" criteria, I'd rather set up the else function to send the user back to the beginning and enter valid units.
I have the following code which uses pint (a scientific unit handling module) which throws and error if a user enters hl_units which is not recognised. This simply kicks the user out of the program on error with a message about what went wrong. I'd like the user to be sent back to re-input if possible.
try:
half_life = float(input("Enter the halflife of the nuclide: "))
hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
full_HL = C_(half_life, hl_units)
except:
print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")
else:
Thanks in advance.
I would use a while loop for that:
input = False
while not input:
try:
half_life = float(input("Enter the halflife of the nuclide: "))
hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
full_HL = C_(half_life, hl_units)
input = True
except:
print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")
input = False
I hope this works for you :)

captcha program always returning fail [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 6 years ago.
Just a little project i'm working on to improve my knowledge.
Curious as to why the program always returns failure, even if the captcha is correctly entered. I assume it has something to do with the results not being stored in memory?
import string
import random
def captcha_gen(size=7, chars=string.ascii_letters + string.digits):
return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
results = print(captcha_gen())
user_input = input("Please enter the captcha code as you see it: ")
if user_input == results:
print("success")
elif user_input != results:
print("failure")
else:
print("error")
Thanks!
results = print(captcha_gen())
print() returns None - it is used to print stuff to the screen. In this case, it is grabbing the output of captcha_gen() and printing it to the screen.
All functions in Python return something - if they don't specify what they return, then it is an implicit None
You want
results = captcha_gen()

Getting user input and making a decision

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.

Try statement - multiple conditions - Python 2

I have little problem with try statement along with multiple conditions. When there is error at 2nd condition, it asks for 1st condition. What I want from it to do is to repeat the same condition, not the whole cycle. I hope you understand me, since my English isn't very good and also I'm newbie to Python so I also don't know how to describe it in my native language.
I hope the following example will help you to better understand my thought.
while True:
try:
zacatek = float(raw_input("Zacatek: "))
konec = float(raw_input("Konec: "))
except Exception:
pass
else:
break
it does following:
Zacatek: 1
Konec: a
Zacatek:
but I want it to do this:
Zacatek: 1
Konec: a
Konec:
Thanks in advance for any help.
Write a function to query for a single float, and call it twice:
def input_float(msg):
while True:
try:
return float(raw_input(msg))
except ValueError:
pass
zacatek = input_float("Zacatek: ")
konec = input_float("Konec: ")
What's happening is that your except clause is catching a ValueError exception on your answer to Konec and returning to the top of the loop.
Your float function is trying to cast a non-numeric response "a" to a float and it throwing the exception.
Alternatively, you could write a different loop for each input:
zacatek = None
while not zacatek:
try:
zacatek = float(raw_input("Zacatek: "))
except Exception:
continue
konec = None
while not konec:
try:
konec = float(raw_input("Konec: "))
except Exception:
continue

Categories