Tkinter text entry validation in python - python

I have created a simple program which asks for a user's name and age. The program will then take the details from a textbox and work out how old they will be in 5 years time.
The interface is fine. It's the validation that I am having difficulty with. When a user enters a letter instead of a number the program shows an error message, but continues to run regardless. I have tried using a while True: loop but this seems to just crash the program.
Here's what I have written already:
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
if age.isalpha():
tkinter.messagebox.showinfo("Error", "The Age is invalid")
textboxAge.delete("0","end")
newAge = int(age)+5
print("Hello",name)
print("In 5 years time you will be",newAge)
I have looked at a few other tutorials but they are a little confusing. I am going to extend this by adding another elif in and the following code
elif age >= 100:
tkinter.messagebox.showinfo("Error", "You have entered a number greater than 100")
textboxAge.delete("0","end")
but this doesn't like the fact it is a string not an integer.
What would be the best way to check to see if a number has been entered into a textbox?

def calculate():
name = (textboxName.get())
age = (textboxAge.get())
try:
newAge = int(age)+5
except ValueError:
tkinter.messagebox.showinfo("Error", "The Intended Reading Age is invalid")
textboxAge.delete("0","end")
return
print("Hello",name)
print("In 5 years time you will be ",newAge)
# ...
If an error occurs somewhere in the try-section, python will not crash, but rather jump to the except part. The critical step is converting age into integer. This throws a ValueError if it is a string. In this case, the message box is shown and the text in your textbox is deleted. return then will stop the function, so the rest of it won't be processed. If nothing happens in the try-section, then except will be skipped.

Related

TypeError: ">” not supported between instances of "str' and int‘

I know I’m missing something with this code. Can someone please help me? I’m new to coding and I’ve struggling with this all day. I don’t want to keep emailing my instructor so maybe I can get help from here. I’m trying to get it to run through the if statements with user input and then calculate the amount but I don’t know what I’m missing.enter image description here
You should post code you're asking about as text in your question.
Going over your code with some comments:
print("Welcome") # no issue here, although Python default is single quotes, so 'Welcome'
print = input("Please enter company name:")
After that last line, print is a variable that has been assigned whatever text was entered by the user. (even if that text consists of digits, it's still going to be a text)
A command like print("You total cost is:") will no longer work at this point, because print is no longer the name of a function, since you redefined it.
num = input("Please enter number of fiber cables requested:")
This is OK, but again, num has a text value. '123' is not the same as 123. You need to convert text into numbers to work with numbers, using something like int(num) or float(num).
print("You total cost is:")
The line is fine, but won't work, since you redefined print.
if num > 500:
cost = .5
This won't work until you turn num into a number, for example:
if int(num) > 500:
...
Or:
num = int(num)
if num > 500:
...
Also, note that the default indentation depth for Python is 4 spaces. You would do well to start using that yourself. Your code will work if you don't, but others you have to work with (including future you) will thank you for using standards.
Finally:
print = ("Total cost:, num")
Not sure what you're trying to do here. But assiging to print doesn't print anything. And the value you're assigning is just the string 'Total cost:, num'. If you want to include the value of a variable in a string, you could use an f-string:
print(f"Total cost: {num}")
Or print them like this:
print("Total cost:", num) # there will be a space between printed values

I dont know how to do error handling with incorrect inputs

im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)

Looping the function

I have this function below, which I have done something wrong in somewhere.
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = input("Please enter the amount of this item you would like to purchase: ")
for i in quantity:
try:
int(i)
return int(quantity)
valid = True
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
return True
return False
To run through, the function is called from the main part of the program like so: quantity = quantityFunction(product)
The return False at the bottom of the code is to do with if product is None, which is needed after a bit of code in another function but has had to go in this function.
If the user input for quantity is a number, all works fine. If it is anything else, the Value Error is printed and you can enter another input. If you put another letter etc in, it repeats again, if you put a number in, it accepts it.
However, it does not return the number you inputted after the letters. It just returns 0.
I suspect this is something to do with how I am repeating the code, i.e. the code should loop back to the start of the function if it hits the Value Error.
Any Ideas?
You said:
the code should loop back to the start of the function if it hits the Value Error.
Then you should not use return statements, otherwise the function will terminate, returning True or False.
Few issue:
1) return statement returns control to the calling function.
2) You are looping over the input, which is wrong.
3) valid=True isn't executed at all.
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity)
#valid = True (since it is never run)
except ValueError:
print("We didn't recognise that number. Please try again.")
#If I get here, I want to loop back to the start of this function
#return True
return False
quantityFunction("val")
Note : Use raw_input() in case of Python 2.7 and input() in case of 3.x
Try this (some formatting included too, but the functionality should be the same):
def determine_quantity(product): # descriptive function name
if not product: # avoiding nesting
return False
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity) # try to convert quantity straight away
except ValueError:
print("We didn't recognise that number. Please try again.")
# nothing here means we simply continue in the while loop
Ideally, you'd take product out. A function should do as little as possible, and this check is better off somewhere else.
def determine_quantity():
while True:
quantity = input("Please enter the amount of this item you would like to purchase: ")
try:
return int(quantity)
except ValueError:
print("We didn't recognise that number. Please try again.")
First, let's address the code. Simply stated, you want a function that will loop until the user enters a legal quantity.
product doesn't do much for the function; check it in the calling program, not here. Let the function have a single purpose: fetch a valid quantity.
Let's work from there in the standard recipe for "loop until good input". Very simply, it looks like:
Get first input
Until input is valid
... print warning message and get a new value.
In code, it looks like this.
def get_quantity():
quantity_str = input("Please enter the amount of this item you would like to purchase: ")
while not quantity_str.isdigit():
print("We didn't recognise that number. Please try again.")
quantity_str = input("Please enter the amount of this item you would like to purchase: ")
return quantity
As for coding practice ...
Develop incrementally: write a few lines of code to add one feature to what you have. Debug that. Get it working before you add more.
Learn your language features. In the code you've posted, you misuse for, in, return, and a function call.
Look up how to solve simple problems. try/except is a more difficult concept to handle than the simple isdigit.
You should try this..
def quantityFunction(product):
valid = False
while True:
if product is not None:
quantity = raw_input("Please enter the amount of this item you would like to purchase: ")
if quantity.isdigit():
return int(quantity)
valid = True
else:
print("We didn't recognise that number. Please try again.")
continue
return False
quantity = quantityFunction("myproduct")

Program asks twice for number if wrong data is input first

I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.

Having trouble requesting input in python

i have troubling handling input in python. I have a program that request from the user the number of recommendations to be calculated.He can enter any positive integer and blank(""). I tried using the "try: , except: " commands,but then i leave out the possibility of blank input. By the way blank means that the recommendations are going to be 10.
I tried using the ascii module,but my program ends up being completely confusing. I would be glad if anyone could get me on the idea or give me an example of how to handle this matter.
My program for this input is :
while input_ok==False:
try:
print "Enter the number of the recommendations you want to be displayed.\
You can leave blank for the default number of recommendations(10)",
number_of_recs=input()
input_ok=True
except:
input_ok=False
P.S. Just to make sure thenumber_of_recs , can either be positive integer or blank. Letters and negative numbers should be ignored cause they create errors or infinite loops in the rest of the program.
while True:
print ("Enter the number of the recommendations you want to " +
"be displayed. You can leave blank for the " +
"default number of recommendations(10)"),
number_of_recs = 10 # we set the default value
user_input = raw_input()
if user_input.strip() == '':
break # we leave default value as it is
try:
# we try to convert string from user to int
# if it fails, ValueError occurs:
number_of_recs = int(user_input)
# *we* raise error 'manually' if we don't like value:
if number_of_recs < 0:
raise ValueError
else:
break # if value was OK, we break out of the loop
except ValueError:
print "You must enter a positive integer"
continue
print number_of_recs

Categories