Behaviour of raw_input() - python

I wanted to understand the behaviour of raw_input in the below code.
I know num will be string.
Irrespective of whatever number i enter it always enter the elif part i.e. if num is 5, which should go to if num<check: part or if num is 10 which should go to else part. Every single time it is going to elif. I thought comparing STRING and INT might throw exception( I dont think so) but just in case, so I had included try except but as expected it did not throw any exception. But what puzzles me is why it is ALWAYS hitting elif even when the input given was 10, atleast in that case i was expecting output Equal
num = raw_input('enter a number')
check = 10
try:
if num<check:
print 'number entered %s is less'%num
elif num>check:
print 'number entered %s is greater'%num
else:
print 'Equal!!!'
print 'END'
except Exception,e:
print Exception,e
Please, PYTHON gurus, solve the Mystery :)

raw_input returns a string. So use int(raw_input()).
And for how string and int comparsions work, look here.

See the answer here.
Basically you're comparing apples and oranges.
>>> type(0) < type('10')
True
>>> 0 < '10'
True
>>> type(0) ; type('10')
<type 'int'>
<type 'str'>

Python 2.7:
num = int(raw_input('enter a number:'))
Variable "num" will be of type str if raw_input is used.
type(num)>>str
or
num = input("Enter a Number:")# only accept int values
type(num)>>int
Python 3.4 :
num = input("Enter a Number:") will work ...
type(num)>>str
convert the variable "num" to int type(conversion can be done at time of getting the user "input") :
num1 = int(num)

Related

while loop not terminating on changing test condition [duplicate]

Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
Yes, you are absolutely right that "5" is distinct from 5. You can convert 5 into a string by using str(5). An alternative would be to convert "5" into an integer by int("5") but that option can fail, so better handle the exception.
So, the change to your program could be e.g. the following:
if guess == str(a):
instead of:
if guess == a:
Another option would be to convert guess into an integer, as explained in the other answer.
EDIT: This only applies to Python versions 2.x:
However, you're using input(), not raw_input(). input() returns an integer if you type an integer (and fails if you type text that isn't a valid Python expression). I tested your program and it asked What is 4 - 2?; I typed 2 and it sait Correct! so I don't see what is your problem.
Have you noticed that if your program asks What is 9 - 4? you can type 9 - 4 and it says Correct!? That's due to you using input(), not raw_input(). Similarly, if you type e.g. c, your program fails with NameError
I would however use raw_input() and then compare the answer to str(correct_answer)
I am assuming you are using python3.
The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
Now you have the input as a integer and you can compare it to a
Edited Code:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())

How do I get the user to input an int rather than a float?

I'm writing a program that takes in a value from the user, in the console, and I'm casting it to an int like so:
num = int(input("Enter a number: "))
I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn't cast to an int by truncating or rounding up for example.
How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?
You can use a try catch block to ensure they only give you an int:
while True:
try:
num = int(input("Enter a number: "))
#do something with num and then break out of the while loop with break
except ValueError:
print("That was not a number, please do not use decimals!")
When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.
You can use a try except to test if a user input is a whole number. Example code:
while True:
try:
value=int(input("Type a number:"))
break
except ValueError:
print("This is not a whole number.")
This code will loop back to the start if a user inputs something that is not an int.
So int() of a string like "3.1" doesnt work of course. But you can cast the input to a float and then to int:
num = int(float(input("Enter a number: ")))
It will always round down. If you want it to round up if >= .5:
num = float(input("Enter a number: "))
num = round(num, 0)
num = int(num)
You can simply use eval python built-in function. num = int(eval(input("Enter a number: "))).
For converting string into python code and evaluating mathimatical expressions, eval function is mostly used. For example, eval("2 + 3") will give you 5. However, if you write "2 + 3", then u will get only '2 + 3' as string value.
Try:
num = int(float(input("Enter number: ")))
and the float will be rounded to int.
You can also add a try...except method to give error to user if the number cannot be converted for any reason:
while True:
try:
num = int(float(input("Enter number: ")))
print(num)
break
except ValueError:
print("This is not a whole number")
use abs() it returns the absolute value of the given number

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

Python: How to check user input is a value or a str?

how to write python code to ask user to input a number, return the int of the number, and if user input a str, for example "One", return a error message like "please input a int number"? How could I do that?
Also I have to check if the number is odd or not, so i m not sure if I can do it with try and except.I dunno how to add that in my code.
Thanks.
def getnum():
errormessage="Please input a odd number"
asknum=raw_input("Please input a number: ")
num=int(asknum)
if num%2!=0: #return num if it is odd number
print num
else:
print errormessage
return getnum()
getnum()
try:
a = int(raw_input("Enter an integer: "))
print a # or do anything else with "a"
except ValueError:
print "Please enter an integer."
EDIT In response to the OP's comment:
try:
a = int(raw_input("Enter an integer: "))
if a % 2 == 1:
print "Integer is odd" # or do anything else
else:
print "Integer is even" # or do anything else
except ValueError:
print "Please enter an integer."
Note that using raw_input() will store the variable as a string, if you want to store it automatically as an int, use input().
This is for Python versions before 3.
There are various ways you could try it.
One way is
userinput = raw_input()
if not all(x in string.digits for x in userinput):
print 'Please enter an int number'
but that's a little weak on the verification - it just checks that all the input characters are digits.
Or you could try
userinput = raw_input()
try:
asint = int(userinput)
except ValueError:
print 'Please enter an int number'
but that uses try/except for something that should be a simple if/else.
s = input()
try:
return int(s)
except:
return 'Error'
Use the isdigit() function for string objects.
Returns true if number else false.
You can do what you wanted using the other answers mentioned.
For some extra information,the type of a variable in python can be obtained by using the type()
>>> a = 1
>>> type(a)
<type 'int'>
>>> b = 'str'
<type 'str'>
you can check a variable's type by
>>> if type(a) == int:
... print 'a is integer'
...
a is integer

Trouble with simple Python Code

I'm learning Python, and I'm having trouble with this simple piece of code:
a = raw_input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or negative number or zero. I'm guessing there's a simple solution, but i can't find it ;-)
Thanks in advance
Because you are using raw_input you are getting the value as a String, which is always considered greater than 0 (even if the String is '-10')
Instead, try using input('Enter a number: ') and python will do the type conversion for you.
The final code would look like this:
a = input('Enter a number: ')
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
However, as a number of folks have pointed out, using input() may lead to an error because it actually interprets the python objects passed in.
A safer way to handle this can be to cast raw_input with the desired type, as in:
a = int( raw_input('Enter a number: '))
But beware, you will still need to do some error handling here to avoid trouble!
That's because a is a string as inputted. Use int() to convert it to an integer before doing numeric comparisons.
a = int(raw_input('Enter a number: '))
if a > 0:
print 'Positive'
elif a == 0:
print 'Null'
elif a < 0:
print 'Negative'
Alternatively, input() will do type conversion for you.
a = input('Enter a number: ')
Expanding on my comment on the accepted answer, here's how I would do it.
value = None
getting_input = True
while getting_input:
try:
value = int(raw_input('Gimme a number: '))
getting_input = False
except ValueError:
print "That's not a number... try again."
if value > 0:
print 'Positive'
elif value < 0:
print 'Negative'
else:
print 'Null'
raw_input
returns a string so you need to convert a which is a string to an integer first: a = int(a)
raw_input is stored as a string, not an integer.
Try using a = int(a) before performing comparisons.
raw input will return a string, not an integer. To convert it, try adding this line immediately after your raw_input statement:
a = int(a)
This will convert the string to an integer. You can crash it by giving it non-numeric data, though, so be careful.

Categories