Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
'kenkenken'

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.