I'm a new to Python and a piece of code doesn't seem to work as desired.
Here is the code:
#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.
def length_function(string):
length = len(string)
return length
string_input=input("Enter the string: ")
if type(string_input) == int:
print("Input can not be an integer")
else:
print(length_function(string_input))
Whenever I type an integer in the result, it gives me the the number of digits in that integer. However, I want to display a message that "Input can not be an integer".
Is there any error in my code or is there another way of doing this. Please respond. Thank You!
Any input entered is always string. It cannot be checked for int. It will always fail. You can do something like below.
def length_function(string):
length = len(string)
return length
string_input=input("Enter the string: ")
if string_input.isdigit():
print("Input can not be an integer")
else:
print(length_function(string_input))
Output:
Enter the string: Check
5
Enter the string: 1
Input can not be an integer
I'm not sure why you're wrapping len() in your length_function but that's not necessary. The result of input() will always be a string so your if cannot evalue to true. To turn it into a number use int(). This will fail if the input can't be parsed into an integer, so rather than an if...else you probably want to do sth like
try:
int(string_input)
print("Input cannot be an integer")
except ValueError:
print(length_function(string_input))
Even integers are taken as strings for example instead of 10 it is taking "10".
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
def length_function(string):
length = len(string)
return length
string_input=input("Enter the string: ")
if RepresentsInt(String_input):
print("Input can not be an integer")
else:
print(length_function(string_input))
Related
I'm working on a project for university, and I need to use an integer from a user input. However I'm trying to make sure my code doesn't break as soon as someone types something the code wasn't expecting, a letter or word instead of a number for example.
After asking, I was told I'm not to use isdigit() or similar functions. Is there a way out of this or should I ignore this weak point in my code?
Technically this doesn't use any functions like isdigit()...
all(c in "0123456789" for c in string)
Examples:
>>> string = "239a0932"
>>> all(c in "0123456789" for c in string)
False
>>> string = "9390239"
>>> all(c in "0123456789" for c in string)
True
You can either just try to convert the input to an int, and if it fails with an exception, it wasn't a number. Or you use a regular expression.
import re
entered = input("Enter a text: ")
# Check as regular expression
pattern = re.compile(r"^\d+$")
if pattern.match(entered):
print("re says it's a number")
else:
print("re says it's not a number")
# Try to convert
try:
asNum = int(entered)
print("can be converted to a number")
except ValueError:
print("cannot be converted to a number")
Use try/except:
try:
num = int(input("Enter a number"))
except ValueError:
# do whatever you want to do if it wasn't a valid number
If you want to re-prompt the user until they enter a number, and then go ahead with whatever you needed num for, that looks like:
while True:
try:
num = int(input("Enter a number"))
break # end the loop!
except ValueError:
print("nope, try again!")
# loop continues because we didn't break it
print(f"{num} + {num} = {num * 2}!")
For example:
if len(my_probably_digits_str) == len("".join([x for x in my_probably_digits_str if x in "0123456789"])):
print("It's convertable!")
Python type() always returns str even if I input an int or float.
I want to return length only if the input value is a valid string. The code that I've written always returns length regardless of the input being string or int.
I am using python3.
Suspect: input(). As it always returns string. But, is there any way I can get my code running with input() and type()?
Approach 1:
def calc_length(s):
if type(s) == int:
print("Only Strings Have Lengths!!! Please enter a string!!")
elif type(s) == float:
print("Only Strings Have Lengths!!! Please enter a string!!")
else:
print(len(s))
calc_length(input("Please enter a String: "))
---------------------------------------------------------------------
Approach 2:
def calc_length(s):
if type(s) != str:
print("Only Strings Have Lengths!!! Please enter a string!!")
else:
print(len(s))
calc_length(input("Please enter a String: "))
Output:
Function input() always returns string. If you want to check if input is integer and/or float you can try casting it to int/float using int(input("Please enter a String: ")) or float(input("Please enter a String: ")) and checking for ValueError exception. If user does not enter integer/float int()/float() throws exception.
user_input = input ("Enter a string: ")
try:
val = float(user_input)
print("Only Strings Have Lengths!!! Please enter a string!!")
except ValueError:
print(len(user_input))
You can also use isdigit() method to check if input is integer. Note that this method assumes float to be string and display its length as float has '.' character which is non-numeric.
user_input = input ("Enter a string: ")
if (user_input.isdigit()):
print("Only Strings Have Lengths!!! Please enter a string!!")
else:
print(len(user_input))
As you suspect, input() returns a string. I found another answer somewhere which suggested eg.,
import ast
type(ast.literal_eval("5"))
>> <class 'int'>
You could adapt this for your code. But I find it pretty objectionable! The user should be giving some specific type of input, and you should deal with parsing that type or else throw an error.
I need help to solve the following problem:
Expected output:
Please input an integer: sfasf;jk
Error. Please input an INTEGER: 1
You input 1
My code:
num=input("Please input an integer: ")
while type(num)!=int:
num=input("Error. Please input an INTEGER: ")
print("You input",num)
Problem:
I want my code to keep looping until an integer is input. But, no matter what input I give, the code keeps rejecting it even if my input is an integer. How do I check whether my input is an integer or not? Inputs like string and floats must all be rejected according to my question.
input return value will always be of type str. You can check if it's an integer by trying to cast it to int and handling the exception, or better use str.isdigit() method:
num = input("Please input an integer: ")
while not num.isdigit():
num = input("Error. Please input an INTEGER: ")
print("You input", int(num))
Also, if you want to support signs without messing with exceptions, you can use
num[0] in '+-' and num[1:].isdigit() or num.isdigit()
as the condition.
Why not use a try : except block, that way you can handle all non-integers
EDIT:: Example
num = False # This can be anything bool/float/etc.. as long it is not an int
while type(num) is not int:
try:
# Cast input as int
num=int(input("Please input an integer: "))
except ValueError:
# Handles all non int's I catch the right exception
# Leaving except empty is considered bad form
print('Not correct format')
# Input passes converting so it must be an int
print("Num is correct type")
Output
>>> Please input an integer: 1.13 # Floats
>>> Not correct format
>>> Please input an integer: 1.1 # Doubles
>>> Not correct format
>>> Please input an integer: dfsdf # Strings
>>> Not correct format
>>> Please input an integer: 9 # Int = Correct
>>> Num is correct type
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
user_input = float(input("Please enter a multiplier!")
if user_input == int:
print " Please enter a number"
else:
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
The program will run effectively, as for any number entered by the user the result will be effective, yet I wish to know a function that allows the user to ask for a number when they enter a letter.
Use a try/except inside a while loop:
while True:
try:
user_input = float(raw_input("Please enter a multiplier!"))
except ValueError:
print "Invalid input, please enter a number"
continue # if we get here input is invalid so ask again
else: # else user entered correct input
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
break
Something that's a float is not an int. They're separate types. You can have a float that represents an integral value, like 1.0, but it's still a float.
(Also, user_input == int isn't checking whether user_input is an int, it's checking whether user_input is actually the type int; you wanted isinstance(user_input, int). But since that still won't work, let's skim over this part…)
So, can you check that a float has an integral value? Well, you can do this:
if int(user_input) == user_input
Why? Because 1.0 and 1 are equal, even though they're not the same type, while 1.1 and 1 are not equal. So, truncating a float to an int changes the value into something not-equal if it's not an integral value.
But there's a problem with this. float is inherently a lossy type. For example, 10000000000000000.1 is equal to 10000000000000000 (on any platform with IEEE-854 double as the float type, which is almost all platforms), because a float can't handle enough precision to distinguish between the two. So, assuming you want to disallow the first one, you have to do it before you convert to float.
How can you do that? The easiest way to check whether something is possible in Python is to try it. You can get the user input as a string by calling raw_input instead of input, and you can try to convert it to an int with the int function. so:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
If you need to ultimately convert the input to a float, you can always do that after converting it to an int:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
else:
user_input = float(user_input)
You could use the assert-statment in python:
assert type(user_input) == int, 'Not a number'
This should raise an AssertionError if type is not int. The function controlling your interface could than handle the AssertionError e.g. by restarting the dialog-function
How do I find out if my user's input is a number?
input = raw_input()
if input = "NUMBER":
do this
else:
do this
What is "NUMBER" in this case?
Depends on what you mean by "number". If any floating point number is fine, you can use
s = raw_input()
try:
x = float(s)
except ValueError:
# no number
else:
# number
If you're testing for integers you can use the isdigit function:
x = "0042"
x.isdigit()
True
string = raw_input('please enter a number:')
Checking if a character is a digit is easy once you realize that characters are just ASCII code numbers. The character '0' is ASCII code 48 and the character '9' is ASCII code 57. '1'-'8' are in between. So you can check if a particular character is a digit by writing:
validNumber=False
while not validNumber:
string = raw_input('please enter a number:')
i=0
validNumber=True
while i
if not (string[i]>='0' and string[i]<='9'):
validNumber=False
print 'You entered an invalid number. Please try again'
break
i=i+1
An answer I found elsewhere on StackOverflow [I forget where] gave the following code for checking if something was a number:
#This checks to see if input is a number
def is_number(s):
try:
float(s)
return True
except ValueError:
return False