If statement based on invalid class entered in Python - 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

Related

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!")

Try-Except block - Did I do this correctly?

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: ')
...

How do I avoid error while using int()?

I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!
You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass
Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.
What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()
n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')
While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.

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

Python how to only accept numbers as a input

mark= eval(raw_input("What is your mark?"))
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print "This is not a number"
So I need to make a python program that looks at your mark and gives you varying responses depending on what it is.
However I also need to add a way to stop random text which isn't numbers from being entered into the program.
I thought I had found a solution to this but it won't make it it past the first statement to the failsafe code that is meant to catch it if it was anything but numbers.
So pretty much what happens is if I enter hello instead of a number it fails at the first line and gives me back an error that says exceptions:NameError: name 'happy' is not defined.
How can I change it so that it can make it to the code that gives them the print statement that they need to enter a number?
remove eval and your code is correct:
mark = raw_input("What is your mark?")
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print("This is not a number")
Just checking for a float will work fine:
try:
float(mark)
except ValueError:
print("This is not a number")
Is it easier to declare a global value than to pass an argument,
In my case it's also gives an error.
def getInput():
global value
value = input()
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
getInput()
print(value)
#can't comment :)
You can simply cae to float or int and catch the exception (if any). Youre using eval which is considered poor and you add a lot of redundant statements.
try:
mark= float(raw_input("What is your mark?"))
except ValueError:
print "This is not a number"
"Why not use eval?" you ask, well... Try this input from the user: [1 for i in range (100000000)]
you can use the String object method called isnumeric. it's more efficient than try- except method. see the below code.
def getInput(prompt):
value = input(prompt)
while not value.isnumeric():
print("enter a number")
value = input("enter again")
return int(value)
import re
pattern = re.compile("^[0-9][0-9]\*\\.?[0-9]*")
status = re.search(pattern, raw_input("Enter the Mark : "))
if not status:
print "Invalid Input"
Might be a bit too late but to do this you can do this:
from os import system
from time import sleep
while True:
try:
numb = float(input("Enter number>>>"))
break
except ValueError:
system("cls")
print("Error! Numbers only!")
sleep(1)
system("cls")
but to make it within a number range you can do this:
from os import system
from time import sleep
while True:
try:
numb = float(input("Enter number within 1-5>>>"))
if numb > 5 or numb < 1:
raise ValueError
else:
break
except ValueError:
system("cls")
print("Error! Numbers only!")
sleep(1)
system("cls")
Actually if you going to use eval() you have to define more things.
acceptables=[1,2,3,4,5,6,7,8,9,0,"+","*","/","-"]
try:
mark= eval(int(raw_input("What is your mark?")))
except ValueError:
print ("It's not a number!")
if mark not in acceptables:
print ("You cant do anything but arithmetical operations!")
It's a basically control mechanism for eval().

Categories