Python Try / Except [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
What is the correct way to use Try / Except?
I am pretty new to Python and just trying to learn this new technique so any ideas why this doesn't work?
temp=input("Please choose an option: ")
try:
if temp == ("1"):
fc=input("Fahrenheit: ")
fer(int(fc))
if temp == ("2"):
cf=input("Celsius: ")
cel(int(cf))
except ValueError:
print("It looks like you input a value that wasn't a number!")
If you put a value in "temp" that isn't 1 or 2 than it should print that it isn't a number but it doesn't, any ideas?

"It looks like you input a value that wasn't a number!" will be printed if there is an exception in your try block. What you wanna do is:
temp=input("Please choose an option: ")
try:
if temp == ("1"):
fc=input("Fahrenheit: ")
fer(int(fc))
elif temp == ("2"):
cf=input("Celsius: ")
cel(int(cf))
else:
print("It looks like you input a value that wasn't 1 or 2!")
except ValueError:
print("It looks like you input a value that wasn't a number!")
You MUST keep the try and catch because it is possible that the input is not a number.

temp=input("Please choose an option: ")
try:
if temp == ("1"): # is temp == "1"
fc=input("Fahrenheit: ") # if yes, get number
fer(int(fc)) # convert to int, this can raise an exception
if temp == ("2"): # is temp == "2"
cf=input("Celsius: ") # if yes, get number
cel(int(cf)) # this can raise an exception
except ValueError: # capture all ValueError exceptions
print("It looks like you input a value that wasn't a number!")
The value of temp can never raise an exception in your code (only the parsing of the input can) so it just passes through. You need to add a check by hand to make sure temp is one of the valid entries.
A better way to do this would be (and you could validate temp via an exception):
def handle_f():
fc=input("Fahrenheit: ") # if yes, get number
fer(int(fc)) # convert to int, this can raise an exception
def handle_C():
cf=input("Celsius: ") # if yes, get number
cel(int(cf)) # this can raise an exception
fun_dict = {"1": handle_f, "2": handle_c}
try:
fun_dict[temp]()
except KeyError: # handle temp not being valid
print('not a valid temperature type')
except ValueError:
print("It looks like you input a value that wasn't a number!")

I think it's cleaner to abstract the process of reading an int from the user:
def input_int(prompt):
try:
return int(input(prompt))
except ValueError:
print("It looks like you input a value that wasn't a number!")
temp=input("Please choose an option: ")
if temp == ("1"):
fc=input_int("Fahrenheit: ")
fer(fc)
if temp == ("2"):
cf=input_int("Celsius: ")
cel(cf)

Related

How to make the try except function easier to read - Python 3 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
import random
chars = list('abcdefghijklmnopqrstuvwxyz1234567890')
password_char_list = []
password = ''
while True:
try:
password_length = int(input('Give the length of the password: '))
except ValueError:
print("Please give an integer.")
else:
break
def random_char():
char = random.choice(chars)
password_char_list.append(char)
for n in range(password_length):
random_char()
for n in password_char_list:
password += '' + n
print('Your password is ' + password)
So this is some code which I have written, an extremely simple and basic password generator. I'm self taught, new to Python and also new to the Stack Overflow community.
As you can see from the code above, I'm not completely fluent in Python yet. I've tried to use the try except function, but my code is far from concise and is difficult to read. What I would like to know is whether there is a better and slicker way to make sure that the input is an integer?
Many thanks,
Simply
P.S. this is the code which I would like to shorten
while True:
try:
password_length = int(input('Give the length of the password: '))
except ValueError:
print("Please give an integer.")
else:
break
Your code is fine and you shouldn't expect to be able to write Python more concisely than this. You could wrap the code in a function to make the logic even clearer.
def input_password_length():
while True:
try:
return int(input('Give the length of the password: '))
except ValueError:
print("Please give an integer.")
Often you will end up writing a more reusable function to make the overall code more concise and readable:
def input_integer(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please give an integer.")
password_length = input_integer('Give the length of the password: ')
You can write your try-except expressions in one line. That prevents some smaller codes with less purpose going into few lines.
while True:
try: password_length= int(input("Give the length of the password:")); break
except: print("Please give an integer:"); continue
Remove continue if you don't need to run it again.

Is there a way to get input from a def function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was wondering if it's possible to get the only input from a def function.
def choose():
while True:
try:
pick = float(input("Enter any number that isn't 0 "))
if pick != 0:
break
else:
pick = float(input("Try again! Enter any number that isn't 0 "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
choose()
I will try to be as clear as possible. Can you take the pick input from choose() and store it somewhere else. Say like when your done inputting the number you want.
Can you run:
print(pick + 15)
or you can't take the input from the choose() at all. I would just like to know. Cause if so I don't even know how to do so. So I would appreciate the advice.
You can't access local variables from outside the function. The function should return the value, and you can assign that to another variable.
def choose():
while True:
try:
pick = float(input("Enter any number that isn't 0 "))
if pick != 0:
return pick
else:
print("Try again. The number has to be non-zero!")
except ValueError:
print("Sorry, I didn't understand that.")
choice = choose()
print(choice + 15)
You also shouldn't ask for input in the else: block, because it's going to ask again when the loop repeats. Just print the error message there, without reading input.
You don't need the continue statement, since loops automatically continue unless the repetition condition becomes false (which can never happen with while True:) or you execute a break or return statement to leave the loop.

Why is the error raised regardless of input? [duplicate]

This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I am working my way through Python for Everyone and I am stuck at this junction. To my eye I have stated that the ValueError is only to be raised if 'num' is anything other than a integer. However when I run the code the error is raised everytime regardless of input. Can anyone nudge me in the right direction?
Extensively googled but I'm not entirely too sure what specifically I should google for...
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num != int : raise ValueError
elif num == "done" : break
except ValueError:
print("Error. Please enter an integer or type 'done' to run the program.")
quit()
print("Maximum", largest)
print("Minimum", smallest)
The code always raises ValueError even when the input is an integer.
This line checks if the inputted string is literally equal to the builtin type int:
if num != int : raise ValueError
Other problem is that the input() function always returns a string. So if you want to raise a ValueError when the user inputs anything but a number, simply do:
inputted = input("Enter a number: ")
num = int(inputted) # raises ValueError when cannot be converted to int
If you want to check if the string entered can be converted into an int, just try it:
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = int(num)
except ValueError:
continue

Python 3.X - only take number from user input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am stuck on a problem that I am trying to solve. I am only suppose to take int (1-4) from user's input and not take any string/float/etc. I have figured out what to do if a user chooses any integer other than 1-4. However, I am stuck on the part where a user chooses anything other than an integer (i.e string, float, etc).
this is what I have done so far:
def menu():
my code
menu()
# keeps on looping till user have selected a proper selection (1-4)
selection = int(input("> "))
if selection == 1:
my code
elif selection == 2:
my code
elif selection == 3:
my code
elif selection == 4:
my code
else:
print("I'm sorry, that's not a valid selection. Please enter a
selection from 1-4. ")
menu()
Any help would be appriciated. I've been trying to find a solution for hours but got stuck on the last part.
Seeing as you don't appear to be doing any integer operations on the value coming from input - I would personally just leave it as a string.
selection = input("> ")
if selection == "1":
pass
elif selection == "2":
pass
#...
else:
print("I'm sorry...")
By doing this you don't have to deal with that edge case at all.
If you must (for some reason) cast this to an int (like, you're using the value later) then you could consider using exception handling.
try:
selection = int(input("> "))
except ValueError:
selection = "INVALID VALUE"
and the continue you on, as your current else statement will catch this and correctly handle it.
try this If you make sure that your code allows the user to input only numbers in python:
def numInput():
try:
number = int(input("Tell me a number"))
except:
print "You must enter a number"
numInput()
return number
You can use an infinite loop to keep asking the user for an integer within the desired range until the user enters one:
while True:
try:
selection = int(input("> "))
if 1 <= selection <= 4:
break
raise RuntimeError()
except ValueError, RuntimeError:
print("Please enter a valid integer between 1 and 4.")

Python input validation: how to limit user input to a specific range of integers? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
Beginner here, looking for info on input validation.
I want the user to input two values, one has to be an integer greater than zero, the next an integer between 1-10. I've seen a lot of input validation functions that seem over complicated for these two simple cases, can anyone help?
For the first number (integer greater than 0, I have):
while True:
try:
number1 = int(input('Number1: '))
except ValueError:
print("Not an integer! Please enter an integer.")
continue
else:
break
This also doesn't check if it's positive, which I would like it to do. And I haven't got anything for the second one yet. Any help appreciated!
You could add in a simple if statement and raise an Error if the number isn't within the range you're expecting
while True:
try:
number1 = int(input('Number1: '))
if number1 < 1 or number1 > 10:
raise ValueError #this will send it to the print message and back to the input option
break
except ValueError:
print("Invalid integer. The number must be in the range of 1-10.")
Use assert:
while True:
try:
number1 = int(input('Number1: '))
assert 0 < number1 < 10
except ValueError:
print("Not an integer! Please enter an integer.")
except AssertionError:
print("Please enter an integer between 1 and 10")
else:
break
class CustomError(Exception):
pass
while True:
try:
number1 = int(raw_input('Number1: '))
if number1 not in range(0,9):
raise CustomError
break
except ValueError:
print("Numbers only!")
except CustomError:
print("Enter a number between 1-10!)

Categories