Validation for int(input()) python - python

def is_digit(x):
if type(x) == int:
return True
else:
return False
def main():
shape_opt = input('Enter input >> ')
while not is_digit(shape_opt):
shape_opt = input('Enter input >> ')
else:
print('it work')
if __name__ == '__main__':
main()
So when the user input a value that is not an integer, the system will repeat the input(). Else, it does something else. But it won't work, may I know why?

Check this. Input always returns a string. So isdigit() is better to use here. It returns True if all characters in a string are digits and False otherwise.
return x.isdigit() will evaluate to True/False accordingly, which will be returned
def is_digit(x):
return x.isdigit()
def main():
shape_opt = input('Enter input >> ')
while not is_digit(shape_opt):
shape_opt = input('Enter input >> ')
else:
print('it work')
if __name__ == '__main__':
main()

An easy way to test if an string is an int is to do this:
def is_digit(x):
try:
int(x)
return True
except ValueError:
return False

You must use try except when trying to convert to int.
if it fails to convert the data inside int() then throw the exception inside except which in your case with makes the loop continue.
def is_digit(x):
try:
int(x)
return True
except:
return False
def main():
shape_opt = input('Enter input >> ')
while not is_digit(shape_opt):
shape_opt = input('Enter input >> ')
else:
print('it work')
if __name__ == '__main__':
main()

Related

Make the input from string to integer in a defined function

this is my current code, however the the input doesn't change to an integer
can someone help me pls
score = [0,20,40,60,80,100,120]
def validate_credits(input_credits):
try:
input_credits = int(input_credits)
except:
raise ValueError('integer required')
if input_credits not in score:
raise ValueError('out of range')
while True:
try:
mark1 = input('Enter your total PASS marks: ')
validate_credits(mark1)
mark2 = input('Enter your total DEFER marks: ')
validate_credits(mark2)
mark3 = input('Enter your total FAIL marks: ')
validate_credits(mark3)
except ValueError as e:
print(e)
This is a scoping issue. Consider:
def the_function(_the_input):
_the_input = int('2')
if __name__ == "__main__":
the_input = '1'
the_function(the_input)
print(the_input)
What do you think the_input will be? '1' or 2?
Output is '1'
How about a list?
def the_function(_the_input):
_the_input.append('2')
if __name__ == "__main__":
the_input = ['1']
the_function(the_input)
print(the_input)
Output is ['1', '2']
At the risk of not explaining this correctly, I'd instead refer you to this thread on the topic
To get your input as an integer, you need to return the value:
def the_function(_the_input):
# + other function logic...
return int(_the_input)
if __name__ == "__main__":
the_input = '1'
the_input = the_function(the_input)
print(the_input)

Python: How to determine if a String can be converted to an integer with no issues

I am writing a program that has multiple functions to execute, and the user selects which one runs by inputting a number. I also want the user to be able to let the user cancel the request by typing "cancel".
Right now this is my code:
func = input("Requested Operation: ")
if func == 'Cancel' or func == 'cancel':
break
elif func == '' or func == ' ' or func == '0':
func = 0
elif type(int(func)) is int:
func = int(func)
else:
fail = True
Context: Function 0 displays a list of the available items to choose from, so I want whitespace or 0 to work as displaying the project list. If the user types "Cancel" or "cancel" it will end the program.
The problem I am having is line 6 (the 2nd elif). My goal is to set the fail variable to True if the user inputs a string that isn't a cancel command, so the code breaks right there and starts over. The problem is, how do I preemptively check if a string can be converted to an integer in the first place? My current iteration returns the error invalid literal for int() with base 10: 'asdg' (asdg being the random nonsense that should make fail = True).
Also, I understand this method is probably super inefficient. Essentially, I want the conditional to be "if func is cancel, break. If func is whitespace or '0', then it equals 0. If func is some non-0 integer, convert the string to an integer and continue. Otherwise, set fail to True and break."
My knowledge of python is minimal so I would very much appreciate a full explanation or link to documentation so I can learn as much as possible.
Thanks in advance :)
Edit: This is the entire module
import projects.dice_app as dice_app
import projects.text_to_math as text_to_math
def main():
f = open("readme_files/index.txt")
p = open("readme_files/projects.txt")
print(f.read())
func = 0
while True:
fail = False
func = input("Requested Operation: ")
if func == 'Cancel' or func == 'cancel':
break
elif func == '' or func == ' ' or func == '0':
func = 0
elif type(int(func)) is int:
func = int(func)
else:
fail = True
break
if func == 0:
p = open("readme_files/projects.txt")
print(p.read())
elif func == 1:
dice_app.dice_func()
elif func == 2:
text_to_math.ttm_func()
else:
print("Invalid operation. Please try again.")
if __name__ == "__main__":
fail = False
main()
while fail == True:
main()
elif func.isnumeric():
func = int(func)
try :
func = int(func)
except ValueError:
print('not a number')
This should work

how to print getValidInteger? python

I'm a beginner in the Python language. I have my getValidInteger function which is:
def getValidInteger():
isValid = False
#initialize strInput
strInput = ""
while (not isValid):
#get string input from the user
strInput = input('Enter an integer: ')
isValid = IsValidInteger(strInput)
if (not isValid):
print('Invalid integer was entered: try again')
#after exiting the loop return strInput cast to an int
return int(strInput)
However, I cannot call that function in the line code below. It shows Typererror: TypeError: getValidInteger() takes 0 positional arguments but 1 was given
setSizeSmall = um.getValidInteger('Enter a small size of each subset:')
I want the output to look like :
Enter a small size of each subset:
I dont know what is your IsValidInteger() function but it doesn't seem to take arguments.
Instead, you can use the isdigit() method like this
def getValidInteger():
isValid = False
#initialize strInput
strInput = ""
while (not isValid):
#get string input from the user
strInput = input('Enter an integer: ')
isValid = strInput.isdigit()
if (not isValid):
print('Invalid integer was entered: try again')
#after exiting the loop return strInput cast to an int
return int(strInput)

Function returns "NoneType" after error check for one input, but not in another

Both functions use the same check(x) function and almost identical to each other, except the argument the second function have to take in order to use print.
Entering int as inputs showed no problem.
However, if alphabets were entered, the return result of enter_num() becomes NoneType, but this does not happen in enter_amount().
Where and how did it went wrong?
def check(x): #check if user input is integer
try:
int(x)
return True
except ValueError:
return False
def enter_num(): #get user input for lotto numbers
x = input("buy num:")
if check(x) == True: #check int
x = int(x)
return x
else:
print("Please enter integer")
enter_num()
def enter_amount(x): #get user amount of the lottos
print(x) ##if enter_num errored once, this will show None##
y = input("How many?")
if check(y) == True: #check int
y = int(y)
print("%s for %s copies" % (x,y))
return y
else:
print("Please enter integer")
enter_amount(x)
buy_num = enter_num()
amount = enter_amount(buy_num)
You never return the recursive result from enter_num():
def enter_num():
x = input("buy num:")
if check(x) == True:
x = int(x)
return x
else:
print("Please enter integer")
enter_num() # ignoring the return value
# so None is returned instead
The same applies to enter_amount(); it too ignores the recursive call.
You need to explicitly return the recursive call result, just like you would for any other expression:
def enter_num():
x = input("buy num:")
if check(x) == True:
x = int(x)
return x
else:
print("Please enter integer")
return enter_num() # ignoring the return value
Do the same for enter_amount(); change the last line to return enter_amount(x).
You really should not be using recursion however; all the user has to do is hold the ENTER key for a short amount of time for your code to end up breaking the recursion limit. See Asking the user for input until they give a valid response for better techniques; a while loop would be fine here.
There is also no need to test for == True; if already tests for truth:
if check(x):
I'd also inline the check test; no need to convert to int() twice if the string can be converted. The following won't run out of recursion depth, but just returns int(x) directly if x contained a convertible value, or prints an error message otherwise and loops right back to ask for the number again:
def enter_num():
while True:
x = input("buy num:")
try:
return int(x)
except ValueError:
print("Please enter integer")

How to redo an input if user enters invalid answer

I'm new to programming, and I was wondering how I can repeat an input section, if the user types in invalid data.
I want the application to just repeat the input section, instead of having to run the function all over again and making the user type everything all over again.
My guess is that I would have to change the "return main()" into something else.
condition = input("What is the condition of the phone(New or Used)?")
if condition not in ["New", "new", "Used", "used"]:
print("Invalid input")
return main()
gps = input("Does the phone have gps(Yes or No)?")
if gps not in ["Yes", "yes", "No", "no"]:
print("Invalid input")
return main()
You can make a method to check it in a loop:
def check_input(values, message):
while True:
x = input(message)
if x in values:
return x
print "invalid values, options are " + str(values)
You can generalise the code to use a message prompt and a validating function:
def validated_input(prompt, validate):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = validate(value)
return value
eg:
>>> def new_or_used(value):
... return value.lower() in {"new", "used"}
>>> validate_input("New, or used?", new_or_used)
Or, simpler, but less flexible, pass in the valid values:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = value.lower() in valid_values
return value
And use:
>>> validate_input("New, or used?", {"new", "used"})
You could even use the valid values to create the input prompt:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt + ': ' + '/'.join(valid_values))
valid_input = value.lower() in valid_values
return value
Which gives a prompt:
>>> validate_input("What is the condition of the phone?", {"new", "used"})
What is the condition of the phone?: new/used
Here is a good reading about Control Flows.
Also in your case, you can use strip() and lower() for user inputs.
>>> 'HeLLo'.lower()
'hello'
>>> ' hello '.strip()
'hello'
Here is the solution for Python 3:
while True:
condition=input("What is the condition of the phone(New or Used)?")
if condition.strip().lower() in ['new', 'used']:
break
print("Invalid input")
while True:
gps=input("Does the phone have gps(Yes or No)?")
if gps.strip().lower() in ['yes','no']:
break
print("Invalid input")

Categories