Issue
There are no errors in this but I can't understand how to code the condition. If I change the condition to if money != string.digits:
and run the code then input in a number, it will go into an endless loop until I insert anything except a digit which I don't want, but the condition is if it's not equal the is statement will work.
The code you see is what I mean. The condition is if the input from the user is a digit, run the if
statement, but when I run the code it doesn't do what I want. I know that's a quick fix,
but I don't feel confident at all because I can't get it, that's all.
import string
money=float(input("put you salary (year)"))
while True:
try:
if money == string.digits:
print("please enter a digit")
money = float(input("put you salary (year)"))
else:
break
except:
money = float(input("put you salary (year)"))
price = money*(2.5/100)
print(price)
Solution
You can just try
/except
to convert the input to float.
while True:
try:
money = float(input("put you salary (year)"))
break
except ValueError:
print("This is not a number. Please enter a valid number")
price = money * (2.5 / 100)
print(price)
Python mentions EAFP (easier to ask for forgiveness than permission) because it usually results in faster, cleaner code. This means you assume the input will be a float and just catch the error when it's not. Instead of validating the input before the error.
Also, when dealing with float arithmetic, be sure to keep in mind the issues and limitations outlined here: Floating Point Arithmetic: Issues and Limitations.
Answered By - mr_mooo_cow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.