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...")
Related
num = input("Enter Something:")
print(type(num))
for some reason when running this code, or any alternative version even without text (string), it still outputs a string.
<class 'str'>
is there any way to check for all types like expected? e.g str and int
The problem is that input() returns a string, so the datatype of num will always be a string. If you want to look at that string and determine whether it's a string, int, or float, you can try converting the string to those datatypes explicitly and check for errors.
Here's an example of one such check:
def check_user_input(input):
try:
# Convert it into integer
val = int(input)
print("Input is an integer number. Number = ", val)
except ValueError:
try:
# Convert it into float
val = float(input)
print("Input is a float number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
I got this example here where there's a more thorough explanation: https://pynative.com/python-check-user-input-is-number-or-string/
Here is a solution based on that for your problem specifically:
def convert_input(input):
try:
# Convert it into integer
val = int(input)
return val
except ValueError:
try:
# Convert it into float
val = float(input)
return val
except ValueError:
return input
num = input("Enter Something:")
num = convert_input(num)
print(type(num))
Input always returns string. If you want some other type you have to cast.
For example:
input_int = int(input("Enter something"))
You should know that, the default input is set to return string. To make this clear, do refer to the following example:
>>> number_input = input("Input a number: ")
Input a number: 17
>>> number = number_input
>>> print(type(number))
<class 'str'>
Python defines the number_input as a string, because input is by default a string. And if python recognizes number_input as string, variable number must also be a string, even though it is purely numbers.
To set number as a int, you need to specify the input as int(input("Input a number: ")). And of course, if you want to input float, just change the data type to float input.
But answering your question, you can't print <class 'str'> and <class 'int'> at the same time.
By default when you type input(), python run it as string data-type so you can change or actually limit it by usage of int()
integer_number = int(input("only numbers accepted: "))
I want to make a function in python that gets the square of digit values only and when invoked with a string it does not give an error and instead returns a message. This is what I have reached till now.
What I have tried:
def square(x):
answer = x
if answer == answer.int() :
print("the square of" ,x, "is", x*x)
if answer == answer.str() :
print("please enter a valid number to find its square")
but it gives me the error when invoked with a string such as "joe" as seen here:
Input In [114], in <cell line: 1>()
---> 1 square("joe")
Input In [113], in square(x)
1 def square(x):
3 answer = x
---> 4 if answer == answer.int() :
5 print("the square of" ,x, "is", x*x)
7 if answer == answer.str() :
AttributeError: 'str' object has no attribute 'int'
You can use type() to find the type of variable.
def square(x):
if type(x) is int:
print("The square of {} is {}".format(x, x*x))
else:
print("Please enter a valid number to print its square")
int() is a built-in function, not a method. You should be calling int(x) rather than x.int()
Use a try-except block. See below:
def square(x):
try:
x = int(x)
except ValueError:
print("Please enter a valid number to find its square")
return
print(f"The square of {x} is {x * x}")
You don’t need to do the logic on this yourself. Let Python handle the error checking (it will throw an error if the user enters a string into what should be an integer).
Instead, you would use try except to decide what to do next on encountering an error.
See the documentation here: https://docs.python.org/3/tutorial/errors.html
by using .int(), you are taking a value (in this case the variable "answer") and trying to turn it into an integer. The reason your code is bringing up errors is because you are using the int() function in the wrong way. Instead of using
if answer == answer.int() :
use
try:
answer = int(answer) #this will try to turn answer into an integer
except:
print("please enter a valid number to find its square") #if answer cannot be turned into an integer, than an error will be raised resulting in the execution of this code segment
it might be worth it to research the "try" and "except" functions more...
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())
Python beginner here. I'm writing a program that uses an infinite loop and allows the user to enter key terms to access different 'tools' or 'modules'.
Within one of these 'modules', the user can enter a value and convert it to binary. I want to:
Allow the program to recognize if the value is either an int or a
float and then run code that converts the value to binary
Allow the program to recognize if the value entered is a str and the str says 'back', in which the current loop will be exited.
As far as I know this issue is occurring as input() converts whatever is entered to a str automatically (due to: http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html "First it prints the string you give as a parameter").
How can I make the code below recognize if the input is a str, float, or int and then execute the relevant if statements? Currently, this part of my code can accept 'back' to exit out of the loop but will take any int or float value as a str, making the program prompt the user to enter a decimal value once more.
#decimal to binary
while search == "d2b":
dec2bin = input("\nDecimal Value: ")
if type(dec2bin) == int:
print("Binary Value: " + "{0:b}".format(dec2bin))
elif type (dec2bin) == str:
if dec2bin == "back":
search = 0
elif type (dec2bin) == float:
#code for float to binary goes here
Edit: not the same as this thread (Python: Analyzing input to see if its an integer, float, or string), as a list is used there over input()
E2: cannot seem to use suggested duplicate as a solution to issue. However, a comment in this thread by Francisco has the solution
Use exceptions! The int and float functions throw a ValueError exception when they can't convert the value passed.
while search == "d2b":
dec2bin = input("\nDecimal Value: ")
try:
dec2bin = int(dec2bin)
except ValueError:
pass
else:
print("Binary Value: " + "{0:b}".format(dec2bin))
continue
try:
dec2bin = float(dec2bin)
except ValueError:
pass
else:
#code for float to binary goes here
continue
if dec2bin == "back":
search = 0
The order in which you try the conversions is important, since every value passed to int is valid with float, and every value passed to float is a valid to be passed to str
You can use str.isalpha() and str.isdigit() to achieve this. Hence your code will be as:
while search == "d2b":
dec2bin = input("\nDecimal Value: ")
if dec2bin.lstrip("-").isdigit():
print("Binary Value: " + "{0:b}".format(int(dec2bin))) # OR, simply bin(int(dec2bin))
elif dec2bin.isalpha(): # OR, isalnum() based on the requirement
if dec2bin == "back":
search = 0
else:
try:
_ = float(dec2bin)
except:
pass
else:
#code for float to binary goes here
Here, I am using str.lstrip() to remove - from the start of the string as .isdigit() can not check for negative number string.
Refer Python 3: String Methods for complete list of methods available with str objects.
using ast.literal_eval() you can do a similar operation. here is a sample code of converting input() str to str, float, and int.
import ast
def input_conv(strr):
try:
base = ast.literal_eval(strr)
return base
except:
return strr
>>> b = input()
hi
>>> input_conv(b)
'hi'
>>> type(input_conv(b))
<class 'str'>
>>> b = input()
1
>>> type(input_conv(b))
<class 'int'>
>>> b = input()
1.222
>>> type(input_conv(b))
<class 'float'>
Develop a Python function which either returns the float square of its parameter x if the parameter is a number, or prints the string "Sorry Dave, I'm afraid I can't do that" if the parameter is a string, and then returns 0.0.
What am I doing wrong? I'm a first year CS student and I have no previous programming background.
I created a function that takes user input, evaluates what type of input it is and print different out puts for number and strings.
For that I used eval(var) func. I also the type(var) == type to verify the type and a if-else loop.
def findt():
userin = input("Input: ") # Takes user input
inpeval = eval(userin) # Evaluates input type
if type(inpeval) == int: # If input is an int
userfloat = float(inpeval) # Modifies into a float
print(userfloat ** 2) # Prints the square of the value
elif type(inpeval) == float: # If input is a float
print(inpreval ** 2) # Prints the square of the value
elif type(userin) == str: # If input is a string
print("Sorry Dave, I'm afraid I can't do that") # Print a string
return 0.0 # Return 0.0
else:
print("Invalid Input")
findt()
When I run my code it works well when input is an int, a float or a char. But if I write more than one char it returns me an error:
NameError: name 'whateverinput' is not defined.
You're trying to eval input before you know it's needed. Get rid of it entirely:
def findt():
userin = input("Input: ") # Takes user input
if type(userin) == int: # If input is an int
userfloat = float(userin) # Modifies into a float
...
The root problem is that you can't evaluate an undefined name.
If your input is a string that is not the name of an object in your program, it will fail. eval requires everything you feed it to be defined.
I found the solution for my problem.
The way I did it I take the input from the user and i try to convert it to a float. If it is a number it will convert and print a float that is the square of the input. If the input is a string it cannot be converted to a float and will give me an error so I use an except ValueError: to print the string I want and return 0.0.
def whattype():
user_input = input(">>> ")
try:
user_input = float(user_input)
print(user_input ** 2)
except ValueError:
print("Sorry Dave, I'm afraid I can't do that")
return 0.0
whattype()
Thank you all for the suggestions and help
Here is a better way to achieve your goal by using the string method isnumeric() to test if the input is numeric or not.
def findt():
userin = input("Input: ")
if userin.isnumeric():
# userin is numeric
result = float(userin) ** 2
print(result)
else:
try:
# userin is a float
result = float(userin) ** 2
print(result)
except ValueError:
# userin is a string
print("Sorry Dave, I'm afraid I can't do that")
return 0.0
findt()
Update: a concise version:
def findt():
userin = input("Input: ")
try:
# userin is an int or float
result = float(userin) ** 2
print(result)
except ValueError:
# userin is a string
print("Sorry Dave, I'm afraid I can't do that")
return 0.0
findt()