This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 4 years ago.
I'm trying to build a code which executes the length of a string
This code should be able to accept only Strings and return their length but when integer or float values are given, it counts their length too.
def length(string):
if type(string)== int:
return "Not Available"
elif type(string) == float:
return "Not Allowed"
else:
return len(string)
string=input("Enter a string: ")
print(length(string))
Output:
Enter a string: 45
2
You expect to get output 'Not Available' for the input 45. But it won't happen because,
while reading input from keyboard default type is string. Hence, the input 45 is of type str. Therefore your code gives output 2.
input returns a string so if you check its type it will always be string. To check if its an int or a float you have to try to cast it.
try:
int(input)
except ValueError:
# not an int
return "Not Available"
try:
float(input)
except ValueError:
# not a float
return "Not Allowed"
return len(string)
Related
This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 10 months ago.
the string will be the price of some product, so it will basically come like this '1,433.10', the problem is that I need to compare it with the value that the user enters in an input that is only possible to enter integers because of the isdigit() method , used to check if the input is a number, and this causes the comparison to fail.
I already tried converting to int, to float and nothing worked, it only generated exceptions
def convert_values():
price = results['price'][2:] # here is where the string with the value is, which in this case is '1,643.10'
print(int(float(price))) # if I try to cast just to int: ValueError: invalid literal for int() with base 10: '1,643.10'
Before converting, replace the commas in the string with '' as:
price = results['price'][2:].replace(',', '')
print(int(float(price)))
This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
How can I check if string input is a number?
(30 answers)
Closed 1 year ago.
I'm trying to make a function that count the numbers of characters in a string and detect when an integer is typed, the condition is use "if" function. I'd expect that if I type any integer like"4464468" instead a string, the program displayed: "Sorry, you typed an integer". But, instead, counts the total number and displayed "The word you type has 7 characters".
My code is next:
def string_lenght(mystring):
return len(mystring)`
#Main Program
mystring = (input("Type a word: "))
if type(mystring) == int or type(mystring) == float:
print("Sorry, you typed an integer")
else:
print("The word you typed has",string_lenght(mystring), "characters")
I'm Newbie at Python. I really appreciate your help and patience.
Best regards.
input() always returns a string so you can try to convert it into int/float, if the operation is successful then it's a number, else it is a string:
try:
float(mystring)
print("Sorry you typed an integer")
except ValueError:
# Rest of the code ...
This question already has answers here:
How to check if input is float or int?
(4 answers)
Determine the type of an object? [duplicate]
(15 answers)
Closed 2 years ago.
def check(checked):
checked = {}
if checked == float:
return format(checked, '.2f')
else:
checked = "not a float"
return checked
# convert to float and check
a = input('Enter price for item 1 : ')
a = check(a)
b = input('Enter price for item 2 : ')
c = input('Enter price for item 3 : ')
d = input('Enter price for item 4 : ')
e = input('Enter price for item 5 : ')
print(a)
whenever I use input for a and expect it to change it returns as not a float even when it has a decimal point. I am trying to get a number to a 2 decimal point limit and if it's not a float value to ignore it. I put the else statement to see what's been going wrong I tried using is instead of == but I still get the same result.
You’re reassigning the checked variable. Don’t do that.
def check(checked):
if isinstance(checked, float):
return format(checked, '.2f')
else:
return "not a float"
Not sure what you were trying to achieve with checked = {} but all it seemed to be doing was ensuring that checked was always a dictionary, never a float, and never the actual bout value.
To test if something is a float you use isinstance, not == or is
And then reassigning checked to a message which was returned “not a float” is just bad practice.
See the above for a cleaner and (hopefully) working implementation
In python whatever input you take integer,float or any other ,The Input will be of String data type.
Here is the solution of your problem , It will only work if the input is positive value and the input is either float or integer.
Code:
def check(checked):
if checked.isdigit():
return checked
else:
return format(float(checked), '.2f')
a = input('Enter price for item 1 : ')
print(check(a))
This code will return float value upto 2 decimal places if float value is entered and will leave the number as it is if its not a float value
This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
How do i give a condition in which for example; if x is not an integer print("type an integer")
With your sample code, your best bet is to catch the ValueError and try again:
def get_int():
try:
return int(input('Type an integer:'))
except ValueError:
print("Not an int. Try again.")
return get_int()
The reason is because if the user enters a non-integer string, then the exception gets raised before you have a chance to check the type, so isinstance doesn't really help you too much here.
One way would be casting the value to into and handle the exception:
try:
parsed = int(user_input)
print ("int")
except:
print ("not int")
This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 9 years ago.
Which of the following is the best way of checking if a string could be represented as number?
a)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
b)
Import re
check_regexp = re.compile(“^\d*\.?\d*$”)
c)
def isNumber(token):
for char in token:
if not char in string.digits: return false
return True
d)
import re
check_replace = lambda x: x.replace(‘.’,’’,1).isdigit()
All four versions do different things. As the first version is the only one that correctly handles negatives, I would prefer it in almost all cases. Even if the other versions were adjusted to return the same values as the first version, I would prefer the first version for clarity. However, if the input format needs to be more strict than what float accepts, perhaps not allowing inputs like '123e+4', then a correctly-written regex would probably be the simplest solution.
You can this Python code, it will find string is number or float value.
def typeofvalue(text):
try:
int(text)
return 'int'
except ValueError:
pass
try:
float(text)
return 'float'
except ValueError:
pass
return 'str'
typeofvalue("1773171")