Python Python Basics All Together Now Gather Information

Tsering Choedhen
Tsering Choedhen
1,050 Points

Do we always have to convert the input value to integer (int)?

The following were my answer (where in I have not converted the input value to integer and that's why i was getting wrong amount). My question is do we have to convert the input value to int ALWAYS?

print ("There are {} tickets remaining.".format(tickets_remaining))

name = input("What is your name? ")

number_of_tickets = input("Hey {}, how many tickets you want today? ".format(name))

Total_Amount = (TICKET_PRICE)*(number_of_tickets)

print ("Your total purchase amount is ${}".format(Total_Amount))

Erlend Dybvik Indrelid
Erlend Dybvik Indrelid
5,843 Points

Hi! This depends on what you are supposed to do with the input value. In this case you need to convert the number_of_tickets to an integer value, because you are using the value later to compute how much the total cost will be. Remember: an integer is a whole number, however a string does not need to be a number, but is just a piece of character(s). If you would have not converted the input value to an integer, you would have multiplied the string value of the number_of_tickets with the ticket_price. This would not be what you want the program to do. Here is an example:

TICKET_PRICE = 2 #let's use a whole number to see what happens.
number_of_tickets = input("How many tickets? ") #let's say we use 3 as an input

total_amount = TICKET_PRICE * number_of_tickets

#This will result in the number_of_tickets ("3") being multiplied with the ticket_price, and will return "33" instead of 6. 

I hope this answered your question! Be sure to let me know if there is something you don't understand.


1 Answer

Steven Parker
Steven Parker
204,010 Points

As Erlend observed, converting the input is necessary if it contains a number and you want to do math or comparisons on it. But the conversion might not always be to "int", for example the input might be money and you would convert it to "float" instead.

Conversion is not needed if the input is not a number, for examples something like a person's name or a color.

name = input("What is your name? ")     # no need to convert here
age = int(input("What is your age? "))  # convert input to a number
if (age >= 21):
    print(f"Great, {name}, let's go get a beer!")
    print(f"Great, {name}, let's go get some ice cream!")
Tsering Choedhen
Tsering Choedhen
1,050 Points

Thank you Steven Parker, for the clarification and also additional informations. And also thank you Erlend Dybvik Indrelid for your explanation and support.

Very helpful, as was Erlend Dybvik Indrelid. Thanks!