-1

i just need help to convert the input of the user to float thats all

thanks

def takenum(x,y):

    print("Your first number is " + x + " your second number is " + y)

    result = (x + y)

    print(result)

x = input("put your first number: " )

y = input("Put your second number: " )

takenum(x, y)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 2
    did you google the title to your question (string need to convert it to float)? `x = float('3.5')`... – hiro protagonist Apr 18 '19 at 12:14
  • yeah its sound funny but i tried to convert this code to float in a lot of ways (im on this little thing for about an hour) its sound funny but yeah couldnt found the answer to convert it into float – FanTa 1 Apr 18 '19 at 12:16
  • Use `x = float( input("Put your first number: " )` and same for `y` and it should work. – Saad Apr 18 '19 at 12:20
  • yeah i treid this and thats the error i get and im not sure why Traceback (most recent call last): File "C:/Users/Shahar/PycharmProjects/ShaharProject/Shahar.py", line 11, in takenum(x, y) File "C:/Users/Shahar/PycharmProjects/ShaharProject/Shahar.py", line 6, in takenum print("Your first number is " + x + " your second number is " + y) TypeError: can only concatenate str (not "float") to str – FanTa 1 Apr 18 '19 at 12:30
  • You can easily format your print string using format, check my answer below to see how to do it – Devesh Kumar Singh Apr 18 '19 at 23:49

2 Answers2

0
def takenum(x,y):
    print("Your first number is " + x + " your second number is " + y)
    result = (float(x) + float(y))
    print(result)

x = input("put your first number: " )
y = input("Put your second number: " )

takenum(x, y)

enter image description here

NOTE: your input should be 3.5 not 3,6

use dot as decimal separator

Or if you want use dots and commas or just commas as separator, just remove the ,(comma) with replace():

def takenum(x,y):
    print("Your first number is " + x + " your second number is " + y)
    result = (float((x).replace(',','.')) + float((y).replace(',','.')))
    print(result)

x = input("put your first number: " )
y = input("Put your second number: " )

takenum(x, y)

what code is doing:

float((x).replace(',','.')) 

you have x which is string(input is returning string), replace , (comma) with . (dot),and convert string into float

enter image description here

ncica
  • 7,015
  • 1
  • 15
  • 37
0

You can explicitly convert your output to a float when you read it using float(input()), and then use string formatting to print it.

def takenum(x,y):
    print("Your first number is {} and your second number is {}".format(x, y))
    result = x + y
    print(result)

x = float(input("put your first number: " ))
y = float(input("Put your second number: " ))

takenum(x, y)

Your output will look like:

put your first number: 5.6
Put your second number: 6.5
Your first number is 5.6 and your second number is 6.5
12.1
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40