How can I fix an integer checking function? [duplicate] - python-3.x

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm trying to make a simple quiz for a project, but I can't get an integer checker to work.
I'm trying to make it so it prints an error for floats and strings, then lets you enter another thing for the same question. My previous one gave a python error and ended the program when entering a float / string.
def int_checker(question):
user = input(question)
passcheck = False
while passcheck is False:
if isinstance(user, int) is True:
passcheck = True
return passcheck
elif isinstance(user, int) is True:
print()
print("Whole numbers only, please.")
passcheck = False
return passcheck
else:
print()
print("Numbers only, please.")
passcheck = False
return passcheck
return user
When I type anything, it gives me the final print statement, then lets me type another input in.
So, is there anyway I can make it say the correct message for each input type, and have it so if I type in an integer, it lets the code use that input?
Thanks in advance.

Since you are using Python 3, user variable will always be a string object, because input function in Python 3 always returns string, so using isinstance function won't help. That's why interpreter won't ever execute if and elif block. If you need to check if user input is a number, then you should implement something like this:
def isValidInt(stringInput):
try:
int(stringInput)
return True
except ValueError:
return False
and use isValidInt(user) instead of isinstance(user, int).
Few things I want to point out:
I noticed that condition in both if and elif are same. Probably, you wanted to do something else and wrote it by mistake.
Having while loop in your function won't make any difference. If you drop it, it will work same.
Refer this implementation if you face any problems:
def intChecker(question):
while True:
userInput = input(question)
if isValidInt(userInput):
return int(userInput)
if isValidFloat(userInput): # Refer isValidInt for implementation of isValidFloat
print("Whole numbers only, please.")
else:
print("Numbers only, please.")

Related

Check if a string startswith any element in a tuple, if True, return that element

I have a tuple of values as follows:
commands = ("time", "weather", "note")
I get an input from the user and I check if the input matches any value in the tuple as follows:
if user_input.startswith(commands):
# Do stuff based on the command
What I would like to do is exactly as the above, but with the matched item returned. I tried many methods, but nothing really worked. Thank you in advance.
Edit:
At some point I thought I could use the Walrus operator, but you would figure out it wouldn't work.
if user_input.startswith(returned_command := commands):
command = returned_command
# actually command only gets the commands variable.
This function takes a function of one argument and a list of arguments, and will return the first argument that makes the function return a truthy value. Otherwise, it will raise an error:
def first_matching(matches, candidates):
try:
return next(filter(matches, candidates))
except StopIteration:
raise ValueError("No matching candidate")
result = first_matching(user_input.startswith, commands)
Try this. You can store your functions inside a dictionary and call them.
def print_time():
print("Time")
def exit_now():
exit()
def print_something(*args):
for item in args:
print(item)
command_dict = {
"time": print_time,
"something": print_something,
"exit": exit_now
}
while True:
user_input = input("Input command: ")
command, *args = user_input.split()
command_dict[command](*args)
output:
Input command: time
Time
Input command: something 1 2 3
1
2
3
Input command: exit
You can use any.
user_input = input()
if any(user_input.startswith(s) for s in commands):
# The input is valid.
If you want to ask for user inputs until their reply is valid, shove that in a while loop.
match = None
while True:
user_input = input()
if any(user_input.startswith(s) for s in commands): # Make sure there is a match at all.
for c in commands:
if user_input.startswith(c):
match = c # Find which command matched in particular.
break # Exit the loop.
else:
print(f"Your selection should be one of {commands}.")
# ...
# Do something with the now valid input and matched element.
# ...
With Python 3.8 or later this should work:
if any(user_input.startswith(returned_command := c) for c in commands):
print(returned_command)

How can I call a function using the user's input [duplicate]

This question already has answers here:
Execute function based on function's name string
(4 answers)
Closed 2 years ago.
I want to call the function A() based on the userinput
def main_func():
def A():
print("A")
i = 0
userinput = input(": ")
letter = userinput.split()
number = len(letter)
while (i < number):
letter[i]()
i = i + 1
main_func()
thanks in advance!
First of all, you should put the printing function def A() outside your original function since it runs separately. Furthermore it is better to use a for loop instead of a while loop here. The following more simple code should work for you.
def A(letter):
print(letter)
def main_func():
userinput = input(": ")
for letter in userinput:
A(letter)
main_func()
Here your main function calls your A() function for every letter in the userinput. It also gives the function the specific letter as a parameter. The function A() then receives the parameter and prints it. Hope this helps

When i change True to False in the first code my output stays same.Why is that?

My code:
liste = ["345","sadas","324a","14","zxc"]
for i in liste:
try:
int(i) == True #(make it false for example)
print(i)
except:
pass
for i in liste:
try:
i = int(i)
print(i)
except:
pass
output:
345
14
Here as you can see there are two different codes and the question is only write the numbers not letters.(By using try-except). But my question is when i change True to False in the first code my output stays same.Why is that?
This:
int(i) == True #(make it false for example)
first try to make an int of i, and if the operation succeeds, compares it with True, then discard the result of the test. IOW, the whole comparison ends up being a no-op ((functionally speaking - the code is still executed), and could as well be replaced with just
`int(i)`
Of course since the result of the comparison is discarded, you could test against just any value that's comparable with an int (another int, a float, a bool etc), this would make absolutely no difference.
As a side note: this:
try:
something()
except:
pass
is pure evil - it catches absolutely everything (including a SystemExit) and ignore it. I understand this is just a quick test code snippet, but do yourself a favour and never do this in real code - always specify the exact exception(s) you expect and can handle at this point in the code, and if you want to ignore them, at least log them somewhere so you know what really happens in your code.
when i change True to False in the first code my output stays same
Because you're not doing anything with that result, as compared to
if int(i) == True:
print(i)
Or simply
if int(i):
print(i)
But, more appropriate would be
if i.isdigit():
print(i)

function_name is not defined error

I want to write a function in python that tells if the number I give is prime, my code so far is:
def enter_input():
n=input("Enter the number to be checked\n")
return n
def check():
o=int(enter_input())
r=o
print(type(o))
print(type(r))
bool=True
for i in range(2,r,1):
if(o%i==0):
return False
return True
def display():
print("Entered Number Is {0}".format(p))
print("The Number is a Prime:{0}".format(check()))
enter_input()
check()
display()
But I get this error after input the numer:
RunTime:-
Enter the number to be checked
23
Traceback (most recent call last):
File "Chech_Prime.py", line 8, in check
o=int(enter_input())
NameError: name 'enter_input' is not defined
Repl Closed
Where did I go wrong? This was my first try with function calling, It seems like the place i called the enter_input() function could not find it. Thanks for any help
You write somethings a little odd, so I will explain why this should do what you are specting:
This is your code, I will comment between lines:
def enter_input():
n=input("Enter the number to be checked\n")
return n
def check(): # you create the check function, and then a display function, and is not necesary, because you want to do both thinks in the same function
o=int(enter_input()) # you call this function a lot of times, and you only want to input the value once, so, is better to call the input method inside the function
r=o # is better to name variables more descriptive, I mean, check() as a function, what checks? maybe you want to call it is_prime(), more descriptive, o and p... doesn't say anything, but input sounds better
print(type(o))
print(type(r)) #this auxiliar variable is not needed
bool=True
for i in range(2,r,1):
if(o%i==0):
return False
return True
def display():
print("Entered Number Is {0}".format(p))
print("The Number is a Prime:{0}".format(check()))# here you again call the function, and again it ask to you to add a input... not good
enter_input()
check() # and again.. three times, that's so confusing even to follow when you are adding the inputs
display()
My way to do it will be:
def print_is_prime():
value_to_eval=int(input("Enter the number to be checked\n"))
print("the type of the value is " + str(value_to_eval.__class__.__name__))
is_prime =True #initial value is correct
for i in range(2,value_to_eval,1):
if(value_to_eval%i==0):
is_prime = False #here, you detect is not prime
break # so with break you can avoid to execute innecesary all the loop
is_prime = True and is_prime # with and operator, true is the neutral, so the value will be always the other value, in this case, is_prime, this like 0 + x, the value will be always x
print("Entered Number Is {0}".format(value_to_eval))
print("The Number is a Prime:{0}".format(is_prime))
print_is_prime()

While loop not executing else statements in python

I am new to python and i have written the code below but there are 2 to 3 problems with it .
While loop does not print the else statement when
ever i enter 6 or 7 it again asks for input .
Once while loop was started for one function for
example addTwoNumbers it would remain in it that i have handled
through the return is there any other way to do that also ?
Thanks
def main():
choice=menu()
while choice!='5':
num1=int(input("enter first number: "))
num2=int(input("enter the second number: "))
if choice=='1':
total= addTwoNumber(num1,num2)
print("sum of two numbers is: ",total)
conti=contin()
return
elif choice=='2':
sub=minTwoNumber(num1,num2)
print("num1-num2",sub)
conti=contin()
return
elif choice=='3':
quo,remain=qrTwoNumber(num1,num2)
print(quo)
print(remain)
conti=contin()
return
else:
print("Wrong Option.Kindly choose between 1 to 4 : ")
choice=menu()
def menu():
print("Welcome to the menu.Kindly choose from below: ")
print("1.To add two numbers: ")
print("2.To subtract two numbers: ")
print("3.For quotient and remainder :")
print("4.Exit Program")
opt=input("Enter number between 1-4")
if opt=='4':
print('Exiting program')
return opt
def addTwoNumber(n1,n2):
sum=n1+n2
return sum
def minTwoNumber(a1,a2):
minus=a1-a2
return minus
def qrTwoNumber(q1,q2):
quotient=q1//q2
remainder=q1%q2
return quotient,remainder
def contin():
con=input("Do you want to continue (Y/N):")
if con=='y' or con=='Y':
choice=menu()
else:
print("Exiting program")
sys.exit()
main()
These are some mistakes:
while choice!='5' should be while choice!='4'
You are returning after if statements. That exits from the loop.
In that if statements you are calling contin() but storing the return value in conti but you are not using it. It should be choice.
In the contin() you are not returning the choice.
Your problems are related, the control flow of your program is mixed up, and you need to be aware of variable scope. As a short example your menu is doing this:
def main():
choice = 5
print(choice)
contin()
print(choice)
def contin():
choice = 10
main()
It sets 'choice' in the top main function, and then tries to change it later on in the contin function. Those are actually two different variables with the same name. The variable scope is only inside the function where the value was set.
Therefore, since the value of choice never changes in main(), the while loop can never quit, the math function can never be different, and you are stuck doing the same math function over and over again.
And the way the program needs to work is like this:
menu
-> choice
-> numbers
-> math
<-
menu
-> choice
-> numbers
-> math
<-
menu
-> choice
-> numbers
-> math
<-
menu
# you quit here, and the program exits
But your code goes into conti() which then goes into main() again, so it gets more and more nested, like this:
menu
-> choice
-> numbers
-> math
-> menu
-> choice
-> numbers
-> math
-> menu
-> choice
-> numbers
-> math
-> menu
# you try to quit here but end up
choice #back at this level
That means that when you eventually press 7 to quit the menu, instead of exiting the program, you exit the last conti() call and are put back up to the top of the while loop, and prompted for more numbers.
The real issue with your code is that the control flow doesn't work how you think it does.
Pretend to be your computer. Take a hard look at your code, looking at it line by line.
The first bit of code that is run is main(). So look at that function.
Inside main, you first call your menu and get a number from your user.
Next, you set up a loop. As long as this first number from the user isn't 5, your loop will run. For now, we'll pretend the user entered 1.
Then you get two numbers as input from your user. That works fine.
Since they entered 1 as the choice, the condition for your first if statement (choice=='1') is true, so the code inside gets run.
You addTwoNumber function is run, and the returned output is stored in total.
Next, you call contin() and store its output in conti. But take a look inside contin(), let's go line-by-line in this function.
You ask the user if they want to continue, and if they enter y (or Y), you call menu() again and store its output in choice, which your loop checks, right? Well, that's not quite right. The thing is, whenever you define a variable in a function, that variable only exists inside that function. Functions can't see the variables inside other functions (unless you pass them as parameters, or you use global variables... but you really shouldn't use global variables). So the choice variable you're using in contin belongs to that function, but there's another, separate variable that also has the name choice for the main function!
To fix this, you can change the choice=menu() line to return menu(). Then change conti=contin() to choice=contin().
Also, you don't need those returns after you call contin(). If you return there, your function will exit, and your loop will stop running.
Here's a portion of your code with the fixes I mentioned. Do you understand why it works? Can you figure out what else has to be changed for everything to be fixed?
def main():
choice = menu()
while choice != '5':
num1 = int(input("enter first number: "))
num2 = int(input("enter the second number: "))
if choice == '1':
total = addTwoNumber(num1, num2)
print("sum of two numbers is: ", total)
choice = contin()
elif choice == '2':
and
def contin():
con = input("Do you want to continue (Y/N):")
if con == 'y' or con == 'Y':
return menu()
else:

Resources