Try-Except block - Did I do this correctly? - python

We are learning exception handling. Did I do this correctly? Is ValueError the correct exception to use to catch strings being typed instead of numbers? I tried to use TypeError, but it doesn't catch the exception.
Also, is there a more efficient way to catch each exception in my four inputs? What is best practice here?
#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
rangeLower = float(input("Enter your Lower range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
rangeHigher = float(input("Enter your Higher range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
#Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
num1 = float(input("Enter your First number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
num2 = float(input("Enter your Second number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break

Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, i.e. Don't Repeat Yourself.
In your case what you should do is create a function called float_input as using your try except block and calling that for each variable assignment.
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
pass
range_lower = float_input('Enter your lower range: ')
...

Related

What to use instead of BREAK ( PYTHON )

In this example I was wondering what I could use instead of BREAK
while (True):
try:
guess = ***********
break
except ValueError:
print(***)
You could initialize guess to an invalid value and test for that.
guess = None
while guess is None:
try:
guess = int(input('Please enter your guess for the roll: '))
except ValueError:
print('Only enter a number please')
When there's no error, guess will be set to an integer, which is not None, so the loop will end.
But I prefer your original code, it's clearer.
Please provide a more information.
loop = True
while (loop):
try:
guess = int(input('Please enter your guess for the roll: '))
loop =False
#break
except ValueError:
print('Only enter a number please')
Another approach using a some lesser known but useful python control flows include using a for/else and try/except/else, it still requires a break but i think it's still a neat alternative
MAX_GUESS = 3
for _ in range(MAX_GUESS):
try:
guess = int(input('Input guess: '))
except ValueError:
print("Try again!")
else:
print("Success!")
break
else:
guess = None
print("Max guesses attempted")
The else block tied to the for/else loop is only entered if a break was NOT encountered during the loop, similarly the else of the try/except/else is only entered if an exception was NOT raised during the try

Can't create an while infinite loop

I'm trying to build a loop in PyCharm to force the user to submit only integers to the program.
But so far, I've only got the input in loop.
What should I do?
You have to cast the input(). In case the user provides a non-integer number, int() will throw a ValueError you you can subsequently handle as below
while True:
try:
num = int(input("Insert an integer number: "))
except ValueError:
print("Sorry, you must enter an integer.")
continue
else:
print(f"The number is: {num}")
break
This is because input always returns a string. What you can do is to try and convert this string into an int, catch the exception raised when this conversion fails, and ask user to try again. For example, like this:
x = None
while x is None:
try:
x = int(input("Enter Number:"))
except ValueError:
print("Oops, this doesn't seem right, try again!")

Struggling with validation (presence, then digit, then range). I think i need to be using the try and except then the if statement

flag=False
while flag==False:
try:
HoursWorked=input("Please enter the employee's hours worked")
if len(HoursWorked)!=0:
if HoursWorked.isdigit():
if HoursWorked>=0 and HoursWorked<=40:
flag=True
else:
print(" invalid, the range accepted is from digits 0-40 entered only")
else:
print("invalid, only digits (whole numbers) may be entered")
except:
print("Hours Worked is", HoursWorked)
I'd rewrite the code as such:
while True:
try:
hours_worked = int(input('Please enter the employee\'s hours worked\n'))
if hours_worked >= 0 and hours_worked <= 40:
print('Hours Worked is {0}'.format(hours_worked))
break
else:
print('invalid, the range accepted is from digits 0-40 entered only')
except ValueError as e:
print('invalid input, not a valid integer.')
There's no need to keep a flag like flag, because when you read a valid input you could just break out of the loop.
Also, I used the int() method and let it do the conversions and throw exceptions when needed.
Notice The except clause contains the part of the code that is caused by an exception! The "valid" part of your code should stay in the try clause.

If statement based on invalid class entered in Python

I'm quite new to python and I'm trying to create a program that uses an if statement that is based on if an int input ( int(input()) ) gets the right input class. For example: if I have an input that goes Var1 = int(input("Enter a number:...")), and the user enters hello there, this would, instead of giving an error message, go into one of the options in an if statement.
Since the rest of the code hasn't been created yet I can't post it, but I've tried all the ways I've come up with to solve this problem without success... Can anyone help me please?
You can surround your input with a try..except block and capture a ValueError that will occur when int() tries to convert a non-integer into an integer:
try:
var1 = int(input("Enter an integer: "))
except ValueError:
print("That's not an integer!")
You can even force your users to enter an integer by placing it in a loop:
var1 = None
while var1 is None:
try:
var1 = int(input("Enter an integer: "))
except ValueError:
print("That's not an integer!")
Or you can do checks at a later time:
var1 = input("Enter an integer: ")
try:
var1 = int(var1)
print("Thank you for entering an integer.")
except ValueError:
print("That's not an integer!")
You can use try/except:
while(True):
try:
var1 = int(input("enter a number: "))
break
except ValueError:
print('it should be a number')
caution: don't use try/except without Execption type like:
try:
printo('hi')
except:
pass
it will except all excetions even syntax error

Printing numbers as long as an empty input is not entered

If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break

Categories