Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (Retired) Things That Count Basic Numbers

Kenneth Simpson
Kenneth Simpson
1,162 Points

Why did he use the int?

I am a little confused why he put

print ("input_string * int(input_int))

I took the int(input_int) and changed it to just

print("input_string * input_int) and it work exactly the same way? So why did he put the int? Thanks.

1 Answer

Let's first clear out the syntax error: you have an extra double quotes character before the input_string and after the parenthesis that comes after the print method name. That will issue a syntax error. What you want to have is as follows:

print (input_string * int(input_int))  # without the double quotes

Now we can get to answering your question: why is the input_int variable converted to an integer before being used as the second operator in the multiplying operation?

Python has a nifty little shorthand for taking a string and producing another string consisting of the initial string repeated several times. Let's look at some example:

>>> 'ken' * 3

I don't know of any other language that supports this type of shortcut. You multiply the string with an integer and you obtain another string consisting of the initial value repeated a number of times. Note that the operator which dictates how many times the string should be repeated must be an integer. You cannot multiply a string with anything else than an integer value. If you use something else you get an error (of type TypeError).

The problem is that the input() function always returns whatever the user types in as a plain string. So if the user provides a value like 5 to the console the input() method will return the string '5' to your script.

This is why you have to convert the value of the input_int variable to an integer before using it as an operand for the multiply operation.

Hope this helps.