[SOLVED] How to use floats in a calculator


This Content is from Stack Overflow. Question asked by NotM1zzel

**I have this code, i want to use floats as an option for a calculator, when i run the code and attempt to enter my first value as a decimal, it throws me this error message invalid literal for int() with base 10: '3.4'

#loop while True: input_mult = "*" input_div = "/" input_add = "+" input_sub = "-" first = input('Please enter your first value: ') one = int(first) if one is float: continue onef = float(first) operator = input('Please enter your operator: ') second = input('Please enter your second value: ') twof = float(second) two = int(second) if operator == input_mult: print(one * two) if operator == input_div: print(one / two) if operator == input_add: print(one + two) if operator == input_sub: print (one - two)


Look up the help for the int() function, which opens with:

Convert a number or string to an integer, or return 0 if no arguments are given.

i.e. the input to int() needs to be a number, so convert it first:

one = int(float(first))  

i.e. the int() function doesn’t change change the type of a variable: it performs an operation upon it too (i.e. rounding if required). Rounding isn’t defined for a string variable, so that first needs to be converted to a float before int() can operate on it.

This will then free you up to experience further issues, such as this line not being great Python:

if one is float:

That needs to be something like:

if type(one) is float:

Python is a dynamic language, but it still does really care about types: they need to match expectations. When it comes to dealing with numbers, this isn’t JavaScript.

Having said that, it isn’t really clear what your logic is intending here. e.g. First you create one as an int, and then immediately test to see if it is a float? This script needs more critical evaluation.

This Question was asked in StackOverflow by NotM1zzel and Answered by Michael MacAskill It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?