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().
Related
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!")
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: ')
...
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
I'm new to coding and learning python... I was trying to check if an input is a number or not. I found a great answer from an inactive account 3 years ago that looks like this:
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=0
if a==0:
a=0
else:
print a
#Do stuff
https://stackoverflow.com/a/26451234/8032074
My question is, what exactly is happening from if a==0 until the end? I can tell that if I take it out, ALL input will end up getting printed, even if it's not a number.
But how exactly is that code preventing non-numerical entries from getting printed?
Thanks!!
It works because a=0 set a to 0 if it's neither a float nor an int. after that, it checks if a == 0 a equal to 0, if it's not, else, it will print the input. A better version using the try...except...else syntax:
a=raw_input("Amount:")
try:
float(a)
except ValueError:
print "This is not a number"
else:
print a
#Do stuff
Here's a fun version:)
import re
a = raw_input("Amount:")
if re.match("-?\d*[\.|\d]\d*", a):
print a
else:
print "This is not a number"
The point of the last if statement is to make sure not to print anything out if the input is not a number.
If the input is not a number, the try/except makes sure the input is set to 0. Then, if the input is 0 (if the input was originally not a number), it is not printed out.
However, in the case the the value inputted was actually 0, I would suggest changing the code to the following:
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=None
if a is not None:
print a
The '==' operator tests if the object pointed to by the variable is the same. In this case, '0' is the constant. If you re-write it slightly it makes more sense:
a=(raw_input("Amount:"))
not_a_number = 0;
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=not_a_number
if a==not_a_number:
a=0
else:
print a
#Do stuff
In case anyone wonders, I ended up synthesizing what I learned and did this:
answer = (raw_input("gimme a number: "))
def is_numeric(number):
try:
int(number)
return True
except ValueError:
try:
float(number)
return True
except ValueError:
print "that ain't a number"
return False
def reply(number):
if is_numeric(number):
print "%s is a good number" % number
reply(answer)
(I'm practicing functions right now.) Thanks for helping me understand what I was looking at!
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.