Home > Back-end >  Can any one explain the logic behind this code
Can any one explain the logic behind this code

Time:05-14

Sorry for asking this very basic question - but I cannot understand why it does what it does.

a = int(input('Enter No. of rows'))
for i in range (a,0,-1):
  print(i*'*')

Thank you taking time to review and answer this question.

CodePudding user response:

The range function accepts three arguments. The first arg. represents the starting integer, the second arg. represents the integer at which to stop, and the 3 arg. represents how much should the numbers increase by. Therefore, in this case, (start, stop, step) = (a, 0, -1). This basically means start from a (the inputted value), move till 0 and increment by -1.

Then, in each iteration, the asterisk symbol (*), repeated i many times, is printed.

You can refer the range function here and here.

CodePudding user response:

Step by step.

In the first line you have:

a = int(input('Enter No. of rows'))

First you a have a variable, a, that's being attributed the int value of input from the user. Both int() and input() are functions.

That means that whatever number the user types will be cast to an int type and the result will be attributed to a variable called a

Then you have a for loop (See docs here):

for i in range (a,0,-1):

for loops are used when you have a block of code which you want to repeat a fixed number of times. It iterates over a sequence (either a list, a tuple, a dictionary, a set, or a string).

The syntax of a for loop is as such:

for <item> in <iterable>:
    <loop body>

So for each item in the iterable, the code inside the body of the for loop will be executed.

Then you have the range() function (see doc here). It takes 3 arguments: range(<starting int>, <stopping int>, <step int>)

starting int: integer starting from which the sequence of integers is to be returned

stopping int: integer before which the sequence of integers is to be returned.

step int: integer value which determines the increment between each integer in the sequence

A negative step value in just means the range() function will generate the sequence of numbers in reverse order.

In the case of range (a,0,-1) it means the sequence of numbers returned from the range() function should start at the value of a, stop at 0 and decrease by 1.

Then in the last line you have:

print(i*'*')

The (i*'*') bit means that the string '*' should be printed i times on the console (check out this explanation).

  • Related