Juan Felipe Contreras
Juan Felipe Contreras

Reputation: 75

Having problems generating a star pattern in python suggested from a book but getting different results

I am new on Python and I am following a book that purposes the following excercise:

Write a program to generate the following pattern in Python:

*
**
***
****

The suggested code is:

n = input('Enter the number of rows: ')
m = int(n)
*k = 1
for i in range(m):
    for j in range(i, i + 2):
        print('*', end = " ")
    print()

and enter n=5.This lead me to ask to questions. The first one is the *k=1, I am asumming the '' is a typo on the book since my program does not run with it. However i am not seeing that k is being used within the loop. My second question is that I do not understand why my outcome is different than the one I get (once removed the ''). This is what I get when n=5:

**
**
**
**
**

Upvotes: 0

Views: 123

Answers (5)

Diima
Diima

Reputation: 1

yea *k = 1 cant be right, you can delete it. Your mistake or the mistake in the book is the line:

for j in range(i, i + 2):

if you type i * 2 it works:

for j in range(i, i * 2):

and if you want no spaces between the starts you need to change the print in the loop to:

print("*",end="")

i just removed the space in the "end".

and a better way you can do this is

m = int(input('Enter the number of rows: '))
for i in range(m + 1):
    print(i * "*")

Upvotes: 0

janardhan sharma
janardhan sharma

Reputation: 335

def printStarsInTriangeForm(count):
    for i in (range(1, count + 1)):
        print("*" * i)

This is one way. :)

Upvotes: 0

Vini
Vini

Reputation: 8419

Another approach if you don't want to use multiplication approach:

n = input('Enter the number of rows: ')
m = int(n)

for i in range(m):
    for j in range(1, i + 2):
        print('*', end = " ")
    print()

Upvotes: 0

irahorecka
irahorecka

Reputation: 1807

You can try this solution. I am pretty sure the *k = 1 is a typo.

n = int(input('Enter the number of rows: '))
k = 1
for i in range(n):
    print(k * '* ', end = "\n")
    k += 1

Upvotes: 0

code_vader
code_vader

Reputation: 256

This works for your problem. In python, you can multiply strings. It will be useful for the problem. *k is a typo.

n = input(' num rows: ')
n = int(n)
for i in range(1, n + 1):
    print ('*' * i)

Upvotes: 1

Related Questions