0

While taking an Intro to Python course through Plural Sight, I found that the code that worked for me was different than that of the instructor. (Different version?) There is one difference I do not understand. Why does the input function sometimes require an int or a float, but at other times it crashes with it? Here are some examples that only work this way:

AGE CALCULATOR

age = input("How old are you?\n") 
decades = int(age) // 10 years = int(age) % 10

LOAN CALCULATOR

money_owed = float(input("How much money do you own, in dollars?\n")) # 50,000 
apr = float(input('What is the annual percentage rate?\n')) # 3.0 
payment = float(input('What will your monthly payment be, in dollars?\n')) # 1,000 
months = int(input('How many months do you want to see results for? \n')) # 24
5
  • 5
    Could you be more specific about the "crash" you're asking about? Showing an example of the failure would be a good place to start. Commented Jul 16, 2021 at 16:11
  • 1
    but at other times it crashes with it what is "it"? Please provide a minimal reproducible example of your issue. And is this line correct? Seems like it's two lines combined: decades = int(age) // 10 years = int(age) % 10 Commented Jul 16, 2021 at 16:12
  • 1
    It's likely that your instructor was using Python 2, which would automatically deduce and convert the type of the result of input. This was changed in Python 3. Commented Jul 16, 2021 at 16:12
  • Note that you could certainly use age = int(input("How old are you?")) and then not need to use int(age) inside the next line. Commented Jul 16, 2021 at 16:12
  • @0x5453, if the instructor were using Python 2, would // be a valid operator? I thought that was introduced with 3. Commented Jul 16, 2021 at 16:13

4 Answers 4

1

input returns a string:

>>> x = input()
5.0
>>> x
'5.0'

If this string contains a representation of a number and you want to use it as a number, you need to call an appropriate function to parse the string and determine what number it represents:

>>> float(x)
5.0

However if the string doesn't represent a number, or if it doesn't represent a number of the type you're trying to convert it to, you will get an error:

>>> int(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'

(Technically 5.0 is an integer, but typically we think of '5.0' as representing not the number 5.0 itself but as representing some unknown number which would round to 5.0, i.e. some number between 4.95 and 5.05. Hence the failure to convert to an integer.)

And of course if the string doesn't represent a number at all, all of this is right out.

>>> float('banana')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'banana'

EDIT: 0x5453 raises a good point in the comments, which is that prior to python 3 the language would do these string-to-number conversions implicitly in some cases, which may be what you're remembering.

Sign up to request clarification or add additional context in comments.

2 Comments

If this is the OP's problem -- and it almost certainly is -- their question should be closed as duplicative rather than answered. See the bullet point regarding questions "that have already been asked and answered many times before" in the Answer Well-Asked Questions section of How to Answer.
(The only reason I haven't already closed the OP's question as duplicate of one of the many preexisting questions on this topic is that they aren't clear and unambiguous about what their problem actually is; if they provided a stack trace or similar it would be done already).
1

The function input() gets text from the user as a string, the float() function is used to convert strings to float values. In the inputs you specified any value containing a comma will cause float() to throw an error since float() does not know what to do with the comma. The function does know how to convert numbers containing decimals though so those numbers will be fine. If you wanted to take input that contains commas you would have to sanitize your input like so:

float(input("How much money do you own, in dollars?\n").replace(',','')) # 50,000 

Comments

0

That is called type conversion.The default input type is str also called string. You could learn the type of any variable by using type(variable_name). Now,in your case:

    age = input("How old are you?\n")
    print(type(age))    # would print <class 'str'>

To make calculations uisng integers you need to convert this age variable to integer type or it will raise errors,if you do:

    print(age//10)

it will throw an error like:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for /: 'str' and 'int'

So, for the conversion purpose you'd have to use built-in functions like int() or float() or list():

    age = int(age)    # this simply converts values like '39' to 39
    age = float(age)    # will convert values to decimal values i.e. 39.0
    
    # we can pass the input value to the designated method for direct conversions
    age = int(input('Enter your age: '))    # now your age variable will store an integer value
    print(type(age))   # will print <class 'int'>

Comments

0

This is because input(), by default, stores the value as a str (string). If you want to perform mathematical operations on the stored value, you can type cast it into an int or a float

Eg:

num = int(input())
print(num+10)

OR

num = input()
print(int(num)+10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.