Navaneethan Arun
Navaneethan Arun

Reputation: 386

how to give the condition in for loop?

how to give condition in for loop. I want to do

for i in range(1,i <= n,1): 
for j in range(1,j <= i,1):

Those above statements are not working why i do not know. I am newbie to python. please give the suggestion.

class trianglePro:
    n = int(input("Enter number : "))
    i = 1
    j = 1
    for i in range(1,n,1):
        for j in range(1,i,1):
            print (" j: ", j)
        print("")

now output is: Enter number : 5

 j:  1

 j:  1
 j:  2

 j:  1
 j:  2
 j:  3

wanted output is:

Enter the value for n:5
  1 
  1 2 
  1 2 3 
  1 2 3 4 
  1 2 3 4 5 

Upvotes: 0

Views: 146

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476537

Range statement

Python uses a for loop with syntax:

for <pattern> in <iterable-expression>:
    # ...

So the for loop in Python is what a foreach loop is in the C/C++/Java/C# family (in Java it is usually for(Var var : iterable)).

The range(..) is a constructor that is an iterable. If you construct a range(0,5,2) object, it will emit 0, 2, and 4. There is no dedicated syntax like for(int i = 0; i < 5; i++) in Python.

Print without new lines

A print statement automatically adds a new line at the end. So if you write print(4), you write "4\n" to the output channel. You can however override the end parameter of print to prevent this: you can write print(4, end='') to only write "4" to the standard output channel. So you can rewrite your code to:

n = int(input("Enter number : "))
for i in range(1,n+1,1):
    for j in range(1,i+1,1):
        print (j, end=' ')
    print('')

Note that you also should drop the " j: " in the print statement, since otherwise it will print that to the output channel as well. For example:

>>> n=5
>>> for i in range(1,n+1,1):
...     for j in range(1,i+1,1):
...         print (j, end=' ')
...     print('')
... 
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

In , you better import the print(..) function from by writing:

from __future__ import print_function

in the head of the file.

Upvotes: 0

Esteban
Esteban

Reputation: 1815

I would do :

from __future__ import print_function

n = int(input("Enter number : "))
for i in range(n):
  for j in range(1,i+2):
    print (j,end=' ')
  print('')

Ouput :

Enter number : 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Drop the first line if you use python 3

Upvotes: 1

Related Questions