Welcome to the Treehouse Community
Looking to learn something new?
Kenneth Simpson1,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.
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 (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
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.