How do I reject all inputs that are NOT integers? - python

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

Related

Trying to validate a text input, so it allows characters in the alphabet only as the input but I'm having problems. (Python)

So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break

How to re-ask for user input if user inputted a non-integer in python

in part of one program i wanted to ensure that user inputs only
so i used:
num=int(raw_input())
while type(num)!= int:
num=int(raw_input('You must enter number only'))
print num
But by doing this , if the user inputted some non-integer like strings or anything else the whole code is displayed error.
so how can i make user re-enter the value until they input an integer.
the output was like:
input your number
hdhe
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-4b5e9a275ca4> in <module>()
1 print'input your number'
----> 2 num=int(raw_input())
3 while type(num)!= int:
4 num=int(raw_input('You must enter number only'))
5 print num
ValueError: invalid literal for int() with base 10: 'hdhe'
while True:
try:
n = int(input('input your number : '))
break
except ValueError:
print('You entered a non integer value, try again.')
continue
print('yay!! you gave the correct value as int')
Now you can do any cosmetic changes as you please.
Happy coding.
Your num = int(raw_input()) has already ensured it must be an int and would raise ValueError if not int. So your while loop never gets to execute because it'll never get a non-int variable for num. Instead remove int() from the num variable and your good to go!
You can use isinstance to check whether the input is intor not.
if input is not int loop until the user enters int.
For instance:
num = input("Enter an integer:")
if not isinstance(num, int):
while not isinstance(num, int):
try:
num = int(input('You must enter integer only'))
except ValueError as ve:
pass
Out:
Enter an integer:e
You must enter integer onlyr
You must enter integer onlye
You must enter integer only4
Process finished with exit code 0
You cast the input from the user directly to int on line 2. If this is not an integer a ValueError exception is thrown. We can modify your implementation and catch the exception when this happens, only exiting the loop when no exception occurs and num is an integer.
while True:
num=raw_input()
try:
num=int(num)
break
except ValueError:
print "Input is not an integer!"
print num
You might also be able to use a regular expression to check if the input value is an integer, or some other library function that checks whether the string from raw_input() is an integer.

Not getting the desired output (conditionals+functions)

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

type() not working with input() and always returns "str" - Python 3.x

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.

If the user input is a string how do you tell the user to input a number [duplicate]

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

Categories

Resources