-2

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)

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
mr_mooo_cow
  • 1,098
  • 1
  • 6
  • 16
0

I am not sure I completely understand the question, but this seems like confusing == and in, as well as maybe other things. But central to the problem is:

if money == string.digits:

which probably means you want to check if the money string is only made of digits, and it won't work, because you're checking for equality, not that all the characters of money are in string.digits:

if all(char in string.digits for char in money):

Edit:

As @martineau pointed out, the test above is a long version of str.isidigit()

if money.isdigit():
ljmc
  • 4,830
  • 2
  • 7
  • 26
  • thanks man this was my first code in my first solo project in python, can tell that this will go on horribly – مستر شعلة May 13 '22 at 21:44
  • You can check if all the characters in a string are digits by simply calling [`str.isdigit()`](https://docs.python.org/3/library/stdtypes.htm#str.isdigit) — i.e. `if money.isdigit():` – martineau May 14 '22 at 00:28
  • True, much simpler, I’ll add it to my response. – ljmc May 14 '22 at 07:30