-4

I'm studying python. And I'm a beginner. Reading a book, I came to look at this code.

for num in range(101):
    print('Hello ('+str(num)+')')
    num = num + 1

It's the result of this code...

Hello (0)
Hello (1)
Hello (2)
.
.
.
Hello (99)
Hello (100)

Is the code below necessary?

print('Hello ('+str(num)+')')

I don't understand why there's +str(num)+.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 2
    Did you try it without the `str`? – quamrana Jul 08 '21 at 09:47
  • 1
    Also, which book did you get this code from? You need to throw it away as soon as possible - and destroy it first so that no one else can see it. – quamrana Jul 08 '21 at 09:48
  • 7
    Best thing to do when you have questions like that is to change the code and see what happens. – mcsoini Jul 08 '21 at 09:48
  • 1
    Python is *strongly-typed* language meaning that there are restrictions on intermingling, among others you must not add string (`str`) to integer (`int`). Also I suggest taking look at *string formatting* (python has many ways to do this) which allow you to place numbers inside string without need to explicitly call `str`. – Daweo Jul 08 '21 at 10:00

3 Answers3

1

You can't add an int (or a numeric) to a string. Thus, once you print a string (here 'Hello'), you only can add a string (or a char) to that word, so you use str(num) to convert num to a string.

num = 3
'Hello' + str(num) => 'Hello 3'
Gaston
  • 185
  • 7
1

The function str() transforms num into a string. Then, the strings are concatenated using the + operator, and then printed.

A modern and elegant way to do this would be to use f-strings:

for num in range(101):
    print(f'Hello ({num})')
    

will produce the same result.


Side-note : you do not need to do num = num + 1 : num is already automatically incremented in the for loop.

1

Python, internally, keeps track of your types, which means that the types you use are tracked by python itself without you needing to explicitly declare them. What you are doing by using print('Hello ('+str(num)+')') is saying to the computer: "print on the screen the following value"; but since there is no sum operation between strings and numbers, you need to convert your number into a string, which is what you are doing by using str(num). This constructs for you a string from the given number; so what you are doing is practically making the value 3 as a number become the value '3' as a string; then the previous line of code, when num == 3, is equivalent to:

print('Hello (' + '3' + ')' )

which of course now is about a bunch of operations between strings, that are now accepted; here is some more information about python's types handling.

Also, check the answer by Louis-Justin Tallot which provides a solution using f-strings (where f stands for format) that allows you to use the f'{variableName}' syntax, evaluating the value between the curly brackets directly to a string.

quamrana
  • 37,849
  • 12
  • 53
  • 71