Why does this code not print 4? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does this code not print 4?

Here’s my code: # Message to be displayed message = "Fasten your seat belt" # for loop to display the message 3 times for i in range(3): print(message) I think I’m just missing something obvious but the counter in the for loop starts at 0 correct? If so it should be 0,1,2,3 which is 4 times the loop should run? Sorry for missing something so simple. Thanks in advance.

29th Feb 2024, 2:03 AM
Clayton
Clayton - avatar
5 Answers
+ 8
Hi Clayton in range () function starting value is 0 by default and is included ,however the end value is not included . So variable i will iterate from start to end-1.In this case from 0 to 2.
29th Feb 2024, 2:45 AM
𝘕𝘉
𝘕𝘉 - avatar
+ 6
You can think the range() function like this: Repeat the action x times. However, if you assign the start and end values, always remember start value is included, but not the stop value. Example: for i in range(3, 10): print(i) Only 3, 4, 5, 6, 7, 8 and 9 are printed.
29th Feb 2024, 4:46 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 4
Thank you for your comments! I think i understand it better. Thanks fkr taking the time to hep explain!!
29th Feb 2024, 12:36 PM
Clayton
Clayton - avatar
0
I need help on building a landing page
1st Mar 2024, 10:46 PM
Rj Web
Rj Web - avatar
0
Hi
1st Mar 2024, 11:24 PM
Carmelina Martinez