Not a floating point valid. Message error Python - python

Well, I'm learning how to use Python, I'm using turtle-graphics to do a menu, in one part I ask for a number with
def getNumber():
return screen.numinput("Title"," Enter a number...")
Running the program, when I call this function and insert a letter or nothing and , I get an error: "Not a floating point valid. Please try again" in a window. So, Is there a way to change the message?, I would like to change that message to "Enter a number, not a letter!" or something like that.

edited:
import sys, tkMessageBox
def getNumber():
try:
return screen.numinput('Title', 'Enter a number...')
except:
tkMessageBox.showerror(title='Wrong Input',message='Enter a valid number!')
sys.exit(1)

All user input is always a string. You must explicitly convert the string to a number:
result = float(getNumber())
-or-
def getNumber():
s = screen.numinput("Title"," Enter a number...")
return float(s)

Related

Python Raising an Exception within "try" block, then catching the same Exception

Came across try/except blocks, such as:
def foo(name):
try:
if name == "bad_name":
raise Exception()
except Exception:
do_something()
return
Is there a reason for doing this, instead of:
def foo(name):
if name == "bad_name":
do_something()
return
In your example specific I would also not have used try/except because as you stated, you could just use an if statement.
Try/except is for occasions where you know the program may crash, so therefore you have written some code that'll run instead of the entire program crashing. You could for example override the default error messages with custom ones.
A better example could be that you want to multiply a number the user wrote times two. Since the input function always returns a string, we need to cast it to an int using the built-in int function. This would work fine if the user had typed in an integer, but if the user had typed in a str instead, the entire program would crash. Let's say we want to print out a message if that happens, we could use try/except. If we also want to repeat the question over and over again until the user writes an integer, we can use a simple while loop. The code below is an implementation of this.
print("Write any integer and I will multiply it with two!")
while True:
# Get user input
userInput = input("Write any number: ")
try:
# Here we try to cast str to int
num = int(userInput)
# The next line will only be run if the line before
# didn't crash. We break out of the while loop
break
# If the casting didn't work, this code will run
# Notice that we store the exception as e,
# so if we want we could print it
except Exception as e:
print("{} is not an integer!\n".format(userInput))
# This code will be run if the while loop
# is broken out of, which will only happen
# if the user wrote an integer
print("Your number multiplied with 2:\n{}".format(num * 2))
Expected outcome:
Write any integer and I will multiply it with two!
Write any number: a
a is not an integer!
Write any number: b
b is not an integer!
Write any number: 4
Your number multiplied with 2:
8

unexpected function return different type / number only checker

I'm trying to make a quick and simple function to check if an entered value is an int/bool. I've had a quick look around and even the solution elsewhere comes to the same issue.
I have this in my test script and it seems to work, but when copying the exact code to my main program it will return the first value entered (say I entered hello instead of a number it will exit with "hello" after typing a number and save that to file).
Is there something with a function calling another function that causes it to fail?
I can post my actual code later, there's a lot of calls in it so it may be quite long. Will try with these short examples first and if we can't figure I can post the long one.
#option 1
import json
with open("settings.json", "r") as f:
pref_file = json.load(f)
def float_check(t):
if t.isdigit():
global prompt
prompt = float(t)
return #I have tried 'return prompt' too
else:
prompt = input ("Enter numerical value only:\n")
float_check(prompt)
prompt = input ("Enter a number: ")
float_check(prompt)
#I'm saving the value to JSON file.
#\\ settings.json
#{
# "o2_percent": 0.0
#}
pref_file["o2_percent"] = prompt
with open("settings.json", "w") as f:
json.dump(pref_file, f, indent=4)
In option 2 I tried calling a function from a function as I thought that was the issue. But this also seems to work.
#option 2
import json
def num_check(t):
if t.isdigit():
global prompt
prompt = float(t)
pref_file["o2_percent"] = prompt
with open("settings.json", "w") as f:
json.dump(pref_file, f, indent=4)
runit()
else:
prompt = input ("Enter numerical numer only:\n")
num_check(prompt)
def runit():
prompt = input ("enter a number: ")
num_check(prompt)
runit()
I found this solution (How to validate a users input to Numbers only?) and have adapted it a little but I'm having the exact same issue - my main code will return the first value entered not the number when exiting the loop.
enter number: hello
enter number: elephant
enter number: why
enter number: 5
saves value to settings.json "hello"
Also why does the first print return float as expected but the second is an str, I've done no further processing? I'm new to all this - is there some jenky thing if using variables in a function even if declared global?
def mk_float(answer):
while True:
try:
answer = float(answer)
print (type(answer)) #returns float
break
except ValueError:
answer = input ("Enter number!")
answer = input ("number: ")
mk_float(answer)
print (type(answer)) #returns int
I'm about ready to table flip.
Edit
This was my comment that I deleted, as Prune pointed out its a seperate question. But will throw it on the edit so people know what it was in reference to.
def t_check(prompt):
while True:
try:
prompt = int(prompt)
return int(prompt)
break
except ValueError:
prompt = input ("Enter a number only: ")
continue
prompt = input ("enter something: ")
t_check(prompt)
print (prompt)
print (type(prompt))
The surface problem is because, when you repeat the request for valid input, instead of using a simple loop-until-valid approach, you use recursion. As you wind back up the stack on final return, you can easily get a reversal of the data you want.
The next problem is using global variables. Use parameters for input to your function; return the result. Global variables usually indicate poor design.
Note that print returns None, not a float.
Finally, you should trace your program's execution, as well as intermediate results, using simple print commands. This is the simplest and most immediately effective debugging tool.
Does that help you get going?
I am not sure I can help with the json part of your code, however you may use this function to ask the user to input a number (float or int) :
def input_number():
try:
return float(input ("Enter numerical value only:\n"))
except ValueError:
return input_number()
When the user input something, input_number will try to return the input as a float (which cover the int type).
If the conversion to float fails, a ValueError will be catch and input_number will ask the user to enter the value again.
In your very specific case you may do pref_file["o2_percent"] = input_number()
Edit:
Looking at Prune's answer, recursion might not be the best good solution. ^_^

UnboundLocalError when making sure the input is an integer

def main():
prompt = input('How many players? ')
if prompt.isdigit():
num_players = int(prompt)
else:
print('Invalid input!')
main()
print(num_players)
main()
If I enter a valid integer from the first time, everything works as expected, but if I enter a string first, the 'else' executes and I get prompted again, However, I get the UnboundLocalError when I actually input an integer. Any help is appreciated
The problem is because this function is recursive. When you correctly enter an integer the second time, the innermost instance of main returns to the outer instance of main just after your else block. The next thing it tries to do is print(num_players) which worked fine in the inner instance but is unbound in the outer one.
Try moving the print inside the if
Note, it's not really the recursion that's the issue, it will still error if you remove the recursive call to main . The recursion just means you don't see the error until you finally enter an integer
You shouldn't be using recursion for this at all.
def main():
while True:
prompt = input('How many players? ')
if prompt.isdigit():
break
print('Invalid input!')
print(num_players)
There's no reason to use isdigit and int; you never use the int value, as it is immediately turned into a str again by print.
You can, however, use int instead of isdigit (especially if plan to use the int value later, rather than just printing it.
def main():
while True:
prompt = input('How many players? ')
try:
num_players = int(prompt)
break
except ValueError:
pass
print(num_players)

Challenges with guessing game of integers

I am brand new to programming and I'm building a guessing game for fun as a first program. I've already figured out the following:
How to set a specific number for them to guess between 1-50 (for example)
What happens when they guess outside the parameters
Number of guesses and attempts to "break the game"
Included while loops full of if statements
What I can't seem to figure out though is how to stop the user from inputting anything other than a number into the game. I want them to be able to, but I'd like to print out a personal error message then exit the while loop. (Essentially ending the game).
This is as close as I've been able to guess:
if guess == number:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
I get the error: "ValueError: invalid literal for int() with base 10" and I'm clueless on how to figure this out. I've been reading about isdigit and isalpha and have tried messing around with those to see what happens, but I get the same error. Maybe I'm just putting it in the wrong section of code
Any hints? :)
Thank you!
Use try/except to handle exceptions:
try:
guess = int(input("What's your guess? "))
except ValueError:
print("Hey wait! That's not a number!")
print("Try again tomorrow.")
guessed = True
break
# otherwise, do stuff with guess, which is now guaranteed to be an int
You can use a try / except to attempt the cast to an integer or floating point number and then if the cast fails catch the error. Example:
try:
guessInt = int(guess)
except ValueError:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break

2 codes work, the third doesn't

Beginner here. :)
So I want to achieve is this:
User enters a number. It spits out the ^3 of the number. If user enters a letter instead, it prints out a error message.
Code #1 works great:
def thirdpower():
try:
number = int(raw_input("Enter a number : "))
n=number**3
print "%d to the 3rd power is %d" % (number,n)
except ValueError:
print "You must enter an integer, please try again."
thirdpower()
thirdpower()
But I want to try doing the same thing with a while statement since I want to practice with it. I know its a bit more verbose this way, but I think it's good practice nonetheless.
number=raw_input("Please Enter an integer")
while number.isalpha():
print "You have entered letter. Please try again"
number=raw_input("Please Enter an integer")
n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)
My question is this. If I remove the number=raw_input("Please Enter an integer") under the while statement and replace it with a break, the code doesn't work.
Here is what I mean:
number=raw_input("Please Enter an integer")
while number.isalpha():
print "You have entered letter. Please try again"
break #This break here ruins everything :(
n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)
Can anyone explain why?
The break exits out of the while loop, at which point number is still whatever letter was entered so you get an error trying to make it an int.
A break statement jumps out of a loop.
In this case, if the user types in a letter, the loop runs the print statement, then immediately reaches the break and terminates instead of looping over and over. (break is more useful when you put it inside an if statement that the program doesn't always reach.)
But using break doesn't stop the rest of your program from running, so Python still tries to run line 6. Since the number variable contains a letter, the program crashes when it tries to convert it to a number.
You were probably trying to end the program if the user typed in a letter. In that case, you could use the built-in sys module to do something like this:
import sys
number=raw_input("Please Enter an integer")
if number.isalpha():
print "You have entered letter. Please try again"
sys.exit()
#...

Categories

Resources