How to Make a Dictionary Accept any Integer to Trigger a Function - python

Let's say you have the following code:
def statementz():
print("You typed in", number)
digits = {
56 : statementz
}
while True:
try:
number = int(input("Enter a number: "))
except TypeError:
print("Invalid. Try again.\n")
continue
else:
digits.get(number, lambda : None)()
break
I am wondering if there is a way so that one could allow the dictionary to trigger the "statementz" function if the variable "number" holds the value of any integer/float, and not just the integer that is given in the (rather sloppy) example above.
Is it possible to do this? Thank you in advance for any guidance given!

If you want any number to be passed to statementz(), you can simply call it directly after validating it as a number. A dict is only useful if you want to map different numbers to different functions, which is not the behavior you are asking for. Also note that your statementz() should take a number as a parameter since you want to print the number in the function:
def statementz(number):
print("You typed in", number)
while True:
try:
number = float(input("Enter a number: "))
statementz(number)
except TypeError:
print("Invalid. Try again.\n")

Without try-except:
Try using:
def statementz(number):
print("You typed in", number)
while True:
number = input("Enter a number: ")
if number.isdigit():
statementz(number)
break
else:
print("Invalid. Try again.\n")
Example Output:
Enter a number: Apple
Invalid. Try again.
Enter a number: 12ab
Invalid. Try again.
Enter a number: --41-
Invalid. Try again.
Enter a number: 24
You typed in 24

Related

How to validate an integer with python that needs to be used in calculations

I'm trying to validate that a user input int is numbers only. This has been my most recent try:
while True:
NumCars = int(input("Enter the number of cars on the policy: "))
NumCarsStr = str(NumCars)
if NumCarsStr == "":
print("Number of cars cannot be blank. Please re-enter.")
elif NumCarsStr.isalpha == True:
print("Number of cars must be numbers only. Please re-enter.")
else:
break
With this, I get the following error:
line 91, in <module>
NumCars = int(input("Enter the number of cars on the policy: "))
ValueError: invalid literal for int() with base 10: 'g'
(I entered a "g" to test if it was working)
Thanks in advance!
Use try / except, and then break the loop if no exception is raised, otherwise capture the exception, print an error message and let the loop iterate again
while True:
try:
NumCars = int(input("Enter the number of cars on the policy: "))
break
except ValueError:
print("You must enter an integer number")
Thank you everyone for your suggestions! Unfortunately none of these answers did quite what I wanted to do, but they did lead me down a thought process that DID work.
while True:
NumCars = (input("Enter the number of cars on the policy: "))
if NumCars == "":
print("Number of cars cannot be blank. Please re-enter.")
elif NumCars.isdigit() == False:
print("Number of cars must be numbers only. Please re-enter.")
else:
break
After changing the NumCars input to a string, I validated with isdigit, and then when I needed the variable for the calculations, I converted it to integers at the instances where the variable would be used for calculations.
I don't know if it was the easiest or fastest way of doing this, but it worked!
if type(input) == int: do_code_if_is_numbersonly() else: print("Numbers Only")
This checks the type of the input, and if it is integer (number) it does example code, otherwise it prints Numbers Only. This is a quick fix but in my opinion it should work well.
You can utilize the .isnumeric() function to determine if the string represents an integer.
e.g;
NumCarsStr = str(input("Enter the number of cars on the policy: "))
...
...
elif not NumCarsStr.isnumeric():
print("Number of cars must be numbers only. Please re-enter.")

How to make a loop in python three that stops when you input the correct word/number

I am making a text based adventure game in python 3 and I was wondering what the simplest loop is. Using the code I have, it continues to print "whats the number" even when you put the correct number, also giving 9 as input doesnt work. It also doesn't work when I give ("8","9"). Here is my code :
print("whats the number?")
required_number = ("8" or "9")
while True:
number = input()
if number == required_number:
print ("GOT IT")
else: print ("Wrong number try again")
Try this :
print("whats the number?")
required_number = [8,9]
while True:
number = int(input())
if number in required_number :
print('GOT IT')
break
else:
print('Wrong number try again')
Sample output in shell :
whats the number?
5
Wrong number try again
2
Wrong number try again
4
Wrong number try again
8
GOT IT
print("whats the number?")
required_number = [8,9]
while True:
number = input()
if number in required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
The word you are looking for in place of == is in since required_number is a tuple you're looking to see if the input is in required_number. Also the correct syntax for the tuple would be using a comma not or.
I also would make required_number plural to be a more accurate description of what it holds, and you probably want to use integers and not strings.
required_numbers = (8, 9)
while True:
number = int(input("whats the number?"))
if number in required_numbers:
print("GOT IT")
break #Stop asking
else:
print ("Wrong number try again")
If your required_number or the input will accommodate a string, then you can use this:
required_number = [8,9]
required_number = str(required_number)
number = None
while True:
number = input("Write a number: ")
if number in required_number:
print ("GOT IT")
else:
print ("Wrong number try again")
Output:
Write a number: 3
Wrong number try again
Write a number: 8
GOT IT
Write a number: Hi
Wrong number try again
input treats it as a str in Python 3.x
Preferably use a list for the required numbers
Using in to check for the number in the required_numbers
Put it in a try block to catch value error exceptions.
Hence:
required_number = [8,9] # a list of integer types
while True:
try:
number = int(input("whats the number? ")) # Using `int` to convert the `str`
if number in required_number:
print ("GOT IT")
break # break out when the number is found
else:
print ("Wrong number try again")
except ValueError:
print("Invalid Input, Please enter an integer only.")
Note: == determines if the values are equal, while in operator iterates over the list of elements and returns True or False.
OUTPUT:
whats the number? g
Invalid Input, Please enter an integer only.
whats the number? abc
Invalid Input, Please enter an integer only.
whats the number? 3
Wrong number try again
whats the number? 9
GOT IT
Try this Method
print('Enter a Number:')
required_number = ['8','9']
while True:
number = input()
if number in required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")

How to check every input for isdigit

I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)

creating a code that use .isdigit

I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.
You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")
Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")

Boolean return value?

def main():
num = int(input('Please enter an odd number: '))
if False:
print('That was not a odd number, please try again.')
else:
print('Congrats, you know your numbers!')
def number():
if (num / 2) == 0:
return True,num
else:
return False,num
main()
I am trying to make it so that if the number entered is odd, it congratulates the user. If not then it should tell them to try again. I am trying to return the Boolean value to main and then when I try to use the code in the main function to prompt the user, it doesn't work.
Your functions are very odd and I'm not talking about numbers that aren't divisible by 2. Try this:
num = int(input('Please enter an odd number: '))
if num % 2 == 0:
print('Better luck next time??') # no really, you should go back to school (;
else:
print('Genius!!!')
Try this:
num_entry = int(input('Please enter an odd number: '))
def number():
return num_entry % 2 == 0
def main():
if number() == True:
print('Sorry, please try again.')
else:
print('Nice! You know your numbers!')
number()
main()
This should work!
Your code does look odd like Malik Brahimi mentioned. This may be because you are trying to write your python code like Java, which requires a main method. There is no such requirement in python.
If you would like to have your check for the "odd-ness" of the number wrapped in a defined function that you can call elsewhere, you should try writing it like this.
def odd_check(number):
if number % 2 == 0:
#This is the check the check formula, which calculates the remainder of dividing number by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
num = int(input('Please enter an odd number: ')) #where variable is stored.
odd_check(num) #This is where you are calling the previously defined function. You are feeding it the variable that you stored.
If you would like a piece of code that will continue to ask your user to enter a number until they get it right, try something like this:
while True: #This ensures that the code runs until the user picks an odd number
number = int(input('Please enter an odd number: ')) #where variable is stored.
if number % 2 == 0: #the check formula, which calculates the remainder of dividing num by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
break #This stops the "while" loop when the "else" condition is met.

Categories

Resources