Python Forum
Beginner: I need help understanding few lines of a code.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Beginner: I need help understanding few lines of a code.
#1
num=int(input('Enter the looping number: '))
for i in range(num):
    for j in range(i):
        print(i, end=' ')
    print(" ")
I wrote a program myself to get a pattern of user prompted number. It worked as I hoped. But I came across above given code. I need help in understanding both the print part and how it works to give following output.

Enter the looping number: 5

1
2 2
3 3 3
4 4 4 4
Reply
#2
range returns a number that is incremented for each iteration, and starts at zero unless otherwise directed.
So range(5) returns 0, 1, 2, 3, 4 (5 values)

It's syntax is: class range(start, stop[, step])
so you can control what it starts with, when it stops, a skip value
example:
for i in range(1,10,2):
    print(i, end=', ')
print()
Output:
1, 3, 5, 7, 9,
the print part uses end = ' ' which tells print not to add a newline, but substitute what's in the quotes instead.
In your code that is ' '
the final print adds the new line to complete the process.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code understanding: Need help in understanding dictionary code jt123 0 471 Jul-09-2023, 01:13 PM
Last Post: jt123
  Beginner: Code not work when longer list raiviscoding 2 822 May-19-2023, 11:19 AM
Last Post: deanhystad
  New to python/coding Need help on Understanding why this code isn't working. Thanks! mat3372 8 1,751 May-09-2023, 08:47 AM
Last Post: buran
  Regular Expression search to comment lines of code Gman2233 5 1,685 Sep-08-2022, 06:57 AM
Last Post: ndc85430
  Understanding a piece of code Michael1 4 1,411 Jan-20-2022, 07:14 PM
Last Post: Michael1
  I want to simplify this python code into fewer lines, it's about string mandaxyz 5 2,130 Jan-15-2022, 01:28 PM
Last Post: mandaxyz
  python seems to be skipping lines of code alansandbucket 1 4,163 Jun-22-2021, 01:18 AM
Last Post: Larz60+
  Running a few lines of code as soon as my timer ends nethatar 3 2,426 Feb-26-2021, 01:02 PM
Last Post: jefsummers
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,254 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Making new lines of code AvioxyYT 1 1,806 Jan-22-2021, 07:02 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020