Test if input is a string instead of a number? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
Sorry I'm a beginner. But like if I had:
x = eval(input('Enter a value for x: '))
How do I make it so that if the person input a string instead of a number it would print "Enter a number" instead of getting an error. Some type of if statement where:
if x == str():
print('Please enter a number')
else:
print('blah blah blah')

It sounds like you are looking for str.isdigit:
>>> x = input(':')
:abcd
>>> x.isdigit() # Returns False because x contains non-digit characters
False
>>> x= input(':')
:123
>>> x.isdigit() # Returns True because x contains only digits
True
>>>
In your code, it would be:
if not x.isdigit():
print('Please enter a number')
else:
print('blah blah blah')
On a side note, you should avoid using eval(input(...)) because it can be used to execute arbitrary expressions. In other words, it is very often a security hole and is therefore considered a bad practice by most Python programmers. Reference:
Is using eval in Python a bad practice?

Related

How do I create an if statement to check if my variable is an int? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I want to make a program where I need to check the input of the user
so, the question is How do I check the input value, if it`s a string or an integer?
Here's some experimental code that didn't work:
a = 10
print(type(a))
if (a==10):
print("aaaaa")
else:
if(type(a)== "<class 'int'>"):
print("12345")
You can do it in the following way:
a = 10
if type(a) is int:
print("Yes")
else:
print("No")
input() will always return string, i.e type(input()) will be str
from my understanding, you want to validate input before proceeding further
, this is what you can do
foo = input()
if not foo.isdigit():
raise ValueError("Enter a valid integer")
foo = int(foo)
this will not work for a negative number, for that you can check if foo startswith "-"
if foo.lstrip("-").isdigit():
multiply_by = -1 if foo.startswith("-") else 1
foo = multiply_by * int(foo.lstrip("-"))
and if you want to check type of variable
a = 10
if isinstace(a, int):
pass

Python comparison if statement not working [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I am just messing around with Python trying to do a simple guessing program. The code inside my if statement never runs, and I can't figure out why. I've tried printing both variables at the end, and even when they're the same, the comparison never resolves to true. I've also tried just setting y as 2 and guessing 2 as the input, and it still doesn't work.
import random
x = input("Guess a number 1 or 2: ")
y = random.randint(1,2)
if x==y:
print("yes")
The problem here is that x is a string and y is an int:
x = input("Try a number ") # I chose 4 here
x
'4'
x == 4
False
int(x) == 4
True
input will always return a string, which you can convert to int using the int() literal function to convert that string into the required value

How can I evaluate a string in Python? [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 5 years ago.
Improve this question
This is my code:
from decimal import *
a = eval (input ("Pelase, give me a numbre: \n"))
if type(a) not in (int, float, Decimal):
print ("It's not possible to make a float from a complex number")
else :
a=float(a)
print ("Now your number is", a, "and its type is" , type(a))
If the input is just text (Hello for instance) you get an error.
I'd like to evaluate if it is a str and give advice to the user based on that evaluation.
def do_input():
user_input = input("Input a number: ")
try:
num = int(user_input)
except ValueError:
try:
num = float(user_input)
except ValueError:
print("You didn't input a number")
num = None
return num
for _ in range(3):
a = do_input()
print("Now your number is", a, "and its type is" , type(a))
Output:
Input a number: 3
Now your number is 3 and its type is <class 'int'>
Input a number: 2.1
Now your number is 2.1 and its type is <class 'float'>
Input a number: ij
You didn't input a number
Now your number is None and its type is <class 'NoneType'>
In python, a string is like a "instance of class str". To order to compare if the "content" within the input was a string, you can make something like...
a = input("Put something...")
if isinstance(a, str):
print("Error caught, a string was given...")
else:
print ("Now your number is", a, "and its type is" , type(a))
eval function does not really parse given string as number. It evaluates string as a python expression. So try one of the two ways mentioned below :
One way
from decimal import *
a = input("Please, give me a number : \n")
if type(a) not in (int, float, Decimal):
print("It's not possible to make a float.")
else:
a = float(a)
print("Now your number is", a, "and its type is", type(a))
Case 1 :
Please, give me a number :
5
Now your number is 5.0 and its type is <class 'float'>
Case 2 :
Please, give me a number :
hello
It's not possible to make a float.
Another way
try:
a = float(input("Please, give me a number : \n"))
print("Now your number is", a, "and its type is", type(a))
except ValueError:
print("It's not possible to make a float.")
Case 1 :
Please, give me a number :
5
Now your number is 5.0 and its type is <class 'float'>
Case 2 :
Please, give me a number :
hello
It's not possible to make a float.
The expression argument is parsed and evaluated as a Python expression
(technically speaking, a condition list) using the globals and locals
dictionaries as global and local namespace. If the globals dictionary
is present and lacks ‘builtins’, the current globals are copied
into globals before expression is parsed. This means that expression
normally has full access to the standard builtins module and
restricted environments are propagated. If the locals dictionary is
omitted it defaults to the globals dictionary. If both dictionaries
are omitted, the expression is executed in the environment where
eval() is called. The return value is the result of the evaluated
expression. Syntax errors are reported as exceptions. Example:
from math import *
def secret_function():
return "Secret key is 1234"
def function_creator():
# expression to be evaluated
expr = raw_input("Enter the function(in terms of x):")
# variable used in expression
x = int(raw_input("Enter the value of x:"))
# evaluating expression
y = eval(expr)
# printing evaluated result
print("y = {}".format(y))
if __name__ == "__main__":
function_creator()
Output :
Enter the function(in terms of x):x*(x+1)*(x+2)
Enter the value of x:3
y = 60
Instead of using eval (which is rather dangerous - a user could enter any valid python code and it'll run), you should use int, and use a try-catch statement something like the following:
while True:
try:
a = int(input ("Pelase, give me a numbre: \n"))
break
except ValueError:
print("Not a number!")
For more examples, see here: https://docs.python.org/3/tutorial/errors.html
eval function does not really parse given string as number. It evaluates string as a python expression.
So the fact that eval('2') gives 2 is just a coincidence, because 2 is correct python expression that evaluates to number.
So you shouldnt use eval to parse strings as numbers. Instead simply try parsing (con verting) it as integer, float and Decimal (in this order) and if you don't get error in any of your tries it means this is correct number of specified type.
Answer posted by #jose-a shows how could it be done.
Why not simply encapsulate your Logic within a try :: except Block like so:
iNumber = input ("Please, enter a Number: \n")
try :
# TRY CASTING THE ENTERED DATA TO A FLOAT...
iNumber = float(iNumber)
print ("Now your number is {} and its type is {}".format(iNumber, type(iNumber)))
except:
# IF CASTING FAILS, THEN YOU KNOW IT'S A STRING OR SO...
# DO SOMETHING - THROW AN EXCEPTION OR WHATEVER...
print ("Non Numeric Data is not acceptable...")
UPDATE:
If you wish to handle Complex Number Inputs (like you mentioned in your comment)... you could just wrap the Code above in an if - else block like so:
import re
iNumber = input ("Please, enter a Number: \n")
# MATCH A SOMEWHAT COMPLEX NUMBER PATTERN
if re.match(r"\d{1,}[ \-\+]*\d{1,}[a-z]", iNumber):
print("Not possible to convert a complex number to float: {}".format(iNumber))
else:
try :
# TRY CASTING THE ENTERED DATA TO A FLOAT...
iNumber = float(iNumber)
print ("Now your number is {} and its type is {}".format(iNumber, type(iNumber)))
except:
# IF CASTING FAILS, THEN YOU KNOW IT'S A STRING OR SO...
# DO SOMETHING - THROW AN EXCEPTION OR WHATEVER...
print ("Non Numeric Data is not acceptable...")

Condition checking in python with user input [duplicate]

This question already has answers here:
If...else statement issue with raw_input on Python
(2 answers)
Closed 7 years ago.
I tried taking an input from keyboard. the checking that input with an if else statement. But everytime the else part is working. The if statement does not happen to be true. I can't understand where I am going wrong.
Here is what I have done.
abc= raw_input("Enter a 2 digit number");
if abc==6:
print "Its party time!!!"
else:
print "Its work time"
Please suggest
Your input variable is a string. You need to cast it to an integer to correctly compare it to 6.
if int(abc) == 6:
raw_input returns a string. abc is a string, and a string will never be equal with an integer. Try casting abc or the return value of raw_input(). Or, you can make 6 a string.
Casting the return value of raw_input() :
abc = int( raw_input('Enter a 2 digit number') )
Casting abc :
abc = int(abc)
or
if int(abc) == 6:
Changing 6 to string :
if abc == '6':
>>> abc= raw_input("Enter a 2 digit number")
Enter a 2 digit number6
>>> if int(abc) == 6:
print "Its party time!!!"
Its party time!!!
>>>

Printing with Quotes [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 8 years ago.
Improve this question
How come when I use the program below i keep getting "y" in quotes opposed to the value defined by y, which would be the string entered by the user
def main():
x = (input("Give me a boolean: ").lower() == 'true')
y = str(input("Give me a string: "))
z = int(input("Give me a number: "))
if x == True:
print (y)
print ("\"",y,"\"",sep="")
else:
print (z*2)
main()
Let's talk about booleans, because this is actually the problem here.
x = bool(input("Give me a boolean: "))
# x is ALWAYS True unless the user enters an empty string
The problem here is that all non-empty strings are boolean True. "Hello" is True, "TRUE" is True, and "False" is True. The only string that evaluates to False is "". So when you prompt for input here, then test it later, you're always going to pass that test unless the user just bypasses the test. Let's move on...
y = str(input("Give me a string: ")) # good here, though no need to call str()
z = int(input("Give me a number: ")) # uh oh...
If I enter ajkldfj for z, it will throw a ValueError. The usual way to handle this is try/except, e.g.:
z = input("Give me a number: ")
try:
int(z)
except ValueError as e:
# handle it
Next up...
if x == True or true:
This is the same issue that TONS of people have. if foo == 1 or 2 doesn't mean what you think it does, it actually means if (foo == 1 is True) or (2 is True). To do what you're trying to do, you should do if x == "True" or x == "true", but better is if x.lower() == "true" and better still is if x.casefold() == 'true' but BEST YET is just if x. Remember, you're already turning it into a bool when you prompt for it. You can change that of course by dropping the bool() call, then testing for it here, in which case I recommend if x.lower() == 'true' or if x.casefold() == 'true'. The other code you'll see quite often is if x in ('true','True'), but since we can just lowercase to remove all ambiguity: DO IT!
Now to your print statements:
print (y) # prints the value in y
print ('"y"') # prints "y"
If this isn't what you want to do, you can use string formatting or really any of a bazillion other things to format it correctly. Let me know what you want to do and we can talk further!
you must use below line for print only y
print(y)
and below for y with Parentheses
print( "(" + y + ")")
Warning:in your Code if X==False then python give you below error
NameError: name 'true' is not defined
You can use format alongside print.
print("({0})".format(y))
Where 0 references the first argument passed to format, 1 the second, and so on. Also, you're doing x == True or true, the or true is wrong and should be removed. Also bool("True") == bool("False") == True, since strings (of length > 0) are True in Python, you probably want something like
x = str(input("True/False? "))
y = str(input("Input string: "))
z = int(input("Number: "))
if x.lower() == "true":
print("({0})".format(y))
Edit: Sample session
>>> def main():
x = str(input("True/False? "))
y = str(input("Input string: "))
z = int(input("Number: "))
if x.lower() == "true":
print("({0})".format(y))
>>> main()
True/False? false
Input string: dog
Number: 2
>>> main()
True/False? true
Input string: dog
Number: 2
(dog)

Categories