Home > database >  If statement requires float, terminal returns error if datatype is string
If statement requires float, terminal returns error if datatype is string

Time:12-01

I am a beginner programmer, working on a project for an online course. I am trying to build a tip calculator. I want it to take input from the user for three values: Bill total, how many are splitting the bill, and the percent they would wish to tip. My conditional statement only has one if:

if meal_price >= 0.01: example(example) else: example(example)

There are no elifs, only an else clause, stating to the user to enter only a numerical value. The program is designed to loop if the else clause runs, or continue if the 'if' condition is met. I would like this program to be completely user-friendly and run regardless of what is typed in. But instead of the else clause being ran when a user enters a string value, the terminal returns an error. How would I check the datatype the user enters, and run my conditional statement based off of that instead of the literal user response?

Note, I've tried:

  • if isinstance(meal_price, float):
  • Converting the user input into a string, but then the conditional statement becomes the problem

Thank you all for the help. I started my coding journey about 3 months ago and I am trying to learn as much as I can. Any feedback or criticism is GREATLY appreciated.

enter image description here

def calculation():
    tip_percent = percentage / 100
    tip_amount = meal_price * tip_percent
    meal_and_tip = tip_amount   meal_price
    total_to_return = meal_and_tip / to_split
    return total_to_return


print("\nWelcome to the \"Bill Tip Calculator\"!")
print("All you need to do is enter the bill, the amount of people splitting it, and the percent you would like to tip.\n")

while True:
    print("First, what was the total for the bill?")
    meal_price = float(input("Bill (Numerical values only): "))
    if meal_price >= 0.01:
        meal_price2 = str(meal_price)
        print("\nPerfect. The total is "   "$"   meal_price2   ".")

        while True:
            print("\nHow many people are splitting the bill?")
            to_split = int(input("People: "))
            if to_split >= 1:
                to_split2 = str(to_split)
                print("\nAwesome, there is", "\""   to_split2   "\"", "person(s) paying.")

                while True:
                    print("\nWhat percent would you like to tip?")
                    percentage = float(input("Percentage (Numerical values only, include decimals): "))
                    if percentage >= 0:
                        percentage2 = str(percentage)
                        print("\nGot it.", percentage2   '%.')
                        calculation()
                        total = str(calculation())
                        #total2 = str(total)
                        print("\n\nEach person pays", "$"   total   ".")
                        exit()
                    else:
                        print("\nPlease enter only a numerical value. No decimals or special characters.")


            else:
                print("\nPlease respond with a numerical value greater than 0.\n")

    else:
        print("Please remember to enter only a numerical value.\n")

Included image snapshot in case copy & paste isn't accurate.

CodePudding user response:

The user's input will be a string, so you need to check if the parse to the float was successful. You can do that with a try/except, and then loop back over asking for more input:

print("First, what was the total for the bill?")

meal_price = None
while meal_price == None:
    try:
        meal_price = float(input("Bill (Numerical values only):"))
    except ValueError:
        print("That didn't look like a number, please try again")
print(meal_price)

CodePudding user response:

Adding on to @OliverRadini's answer, you use the same structure a lot for each of your inputs that could be generalized into a single function like so

def get_input(prompt, datatype):
    value = input(prompt)
    try:
        a = datatype(value)
        return a
    except:
        print("Input failed, please use {:s}".format(str(datatype)))
        return get_input(prompt, datatype)

a = get_input("Bill total: ", float)
print(a)

CodePudding user response:

Perhaps the main point of confusion is that input() will always return what the user enters as a string.

Therefore trying to check whether meal_price is something other than a string will always fail.

Only some strings can be converted into floats - if you try on an inappropriate string, an exception (specifically, a ValueError) will be raised.

So this is where you need to learn a bit about exception handling. Try opening with this block:

meal_price = None

while meal_price is None:

    try:
        meal_price = float(input("Bill (Numerical values only): "))
    except ValueError:
        print("Please remember to enter only a numerical value.\n")

This will try to execute your statement, but in the event it encounters a value error, you tell it not to raise the exception, but to instead print a message (and the loop restarts until they get it right, or a different kind of error that you haven't handled occurs).

CodePudding user response:

Thank you all! After looking into your comments and making the amendments, my program works perfectly! You lot rock!!

def calculation():
    tip_percent = tip / 100
    tip_amount = bill * tip_percent
    meal_and_tip = tip_amount   bill
    total_to_return = meal_and_tip / to_split
    return total_to_return

def user_input(prompt, datatype):
    value = input(prompt)
    try:
        input_to_return = datatype(value)
        return input_to_return
    except ValueError:
        print("Input failed, please use {:s}".format(str(datatype)))
        return user_input(prompt, datatype)


print("\nWelcome to the \"Bill Tip Calculator\"!")
print("\nAll you need to do is:\n1.) Enter your bill\n2.) Enter the amount of 
people (if bill is being split)\n3.) Enter the amount you would like to 
tip.")
print("\n\n1.) What was the total for the bill?")
bill = user_input("Total Bill: ", float)
print("\nAwesome, the total for your meal was "   "$"   str(bill)   ".")
print("\n\n2.) How many people are splitting the bill?")
to_split = user_input("Number of People: ", int)
print("\nSo the bill is divided", str(to_split), "way(s).")
print("\n\n3.) What percent of the bill would you like to leave as a tip? 
(Enter a numeral value only. No special characters.)")
tip = user_input("Tip: ", int)
print("\nYou would like to tip", str(tip)   "%! Nice!")
total = calculation()
print("\n\n\n\nYour total is "   "$"   str(total), "each! Thank you for using 
the \"Bill Tip Calculator\"!")
  • Related