Home > Back-end >  Just started learning functions. What am I doing wrong here?
Just started learning functions. What am I doing wrong here?

Time:08-01

This is the result I was supposed to get:

1
1   2
1   2   3
.....
1   2   3   4 ...  n    

And this is my code:

def __init__(self) -> None:
        pass
    
    def calculo(a):
        for x in range(a):
            for y in range (x):
                print (f"{x}")
                x =1
    
    n = int(input('Digite um valor para n: '))
    calculo(n)

And, this is what I'm getting:

1
2
3
3
4
5
4
5
6
7

The numbers in my result are being displayed one per line(that's also wrong).One more thing: Why is the 3 being repeated over there?

CodePudding user response:

You're printing x, not y.

fix:

def calculo(a):
    for x in range(a):
        for y in range (x):
            print (y)
    
    n = int(input('Digite um valor para n: '))
    calculo(n)

edit:

If you want every count to be displayed on one line, use this code:

def calculo(a):
    for x in range(a   1):
            print(" ".join([ str(z) for z in range(x   1) ]))

calculo(5) # example
>>> 0
>>> 0 1
>>> 0 1 2
>>> 0 1 2 3
>>> 0 1 2 3 4
>>> 0 1 2 3 4 5

CodePudding user response:

Have you considered unpacking a range() ?

def calculo(n):
    for i in range(n 1):
        print(*range(1, i 1))

n = int(input('Digite um valor para n: '))
calculo(n)

If the input is, for example, 10 then the output will be:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
  • Related