Home > Software engineering >  error in a simple python code: couldn't multiply 2 float variabales
error in a simple python code: couldn't multiply 2 float variabales

Time:09-27

money = input("how much are you paying ")

discount = 0.2
num = 20

float(money)

payment = money*discount

if money > num:
    print("you are paying "   money)
else:
    print("you are paying "   payment )

CodePudding user response:

You aren't assigning float(money) to anything.

With minimal changes to your existing code, try:

money = float(input("how much are you paying "))
discount = 0.2
num = 20
payment = money*discount

if money > num:
    print("you are paying "   str(money))
else:
    print("you are paying "   str(payment))

Alternatively, you can reduce the last four lines of your code to a single line using f-strings:

money = float(input("how much are you paying "))
discount = 0.2
num = 20
payment = money*discount

print(f"you are paying {money if money>num else payment}")

CodePudding user response:

You can either directly take in the input as a float like this.

money = float(input("how much are you paying "))

Or assign the converted value into the money variable.

money = float(money)

You also need to modify the print statements if you are not changing the type of money and payment to str before concatenating them.

if money > num:
    print("you are paying " , money)
else:
    print("you are paying " , payment )

CodePudding user response:

1: You need to cast money to float so you can perform mathematical operations on it such as multiplication, you can do that by

money = float(input("..."))

2: You are adding a number to a string, You can't do print("you are paying " money) because "you are paying" is a string type and money should be a number (after you follow my first comment), instead, you can remove the last space in the string so it would be "you are paying" instead of "you are paying " and then you can use print's ability to concatenate items with a space in between: print("you are paying", money).

CodePudding user response:

You cannot calculate between a string and int type.

Try this and see for yourself :

money = input("how much are you paying ")
print(type(money))
...

So, you need to "cast" the variable "money".

money = input("how much are you paying ")

discount = 0.2
num = 20
cast_money = float(money)

payment = cast_money*discount

if cast_money > num:
    print("you are paying "   money)
else:
    print("you are paying "   payment )
  • Related