I’m trying this question where i need to make this triangle pattern only using the codes given below:
*
***
*****
*******
*********
These are the codes that are allowed to be used:
count += 1
star = "*"
continue
count = 10
elif:
print (star,end="")
print()
print (star)
break
i % 2 == 0
i % 2 == 1
This i what i managed to make and I can’t seem to find a way to get the above output with the codes given:
count=10
star="*"
for i in range (count):
if i%2==0:
print(star)
else:
for x in range (i):
print(star,end="*")
count+=1
>Solution :
Okay, first things first : you got your definition correctly in your first lines :
count=10
star="*"
for i in range(count):
If you look closely at the pattern, you can notice if you look closely at the pattern that every line is made of an odd number of stars : 1,3,5… so bascially, you want to "skip" every iteration with an even number of stars, and that’s what continue is for, to bring you to the next iteration loop.
Keep in mind tho that Python range iteration starts at 0, so every line contains one more star than its index. To sum up, you want to print even lines (with an odd number of stars) and skip odd lines (with an even number of stars) :
if (i%2 == 1): # if you're looking at an odd line (with an even number of stars)
continue # skip this iteration
else: # we're now sure we're on an even line
Now we have our even lines only. For each of these lines, we want to keep as many stars as the line index (the i index) + 1. When using the print method, the default value for end is \n, the character for a newline, so when you use print by default it prints a line and goes to the next line. The print(star, end="") instruction will help us by forcing the code to stay on the same line and not going to a new line. Remember how we said we wanted to print (i+1) stars ? Then we can print i starts, and for the i+1st one, we can go to a new line.
for x in range(i):
print(star,end="") #print our star and prevents the new line
print(star) #once we printed our i stars, we print the i+1 and go to a new line
To sum up :
count=10
star="*"
for i in range (count):
if (i%2 == 1): # if you're looking at an odd line (with an even number of stars)
continue # skip this iteration
else: # we're now sure we're on an even line
for x in range(i):
print(star,end="") #print our star and stay on the same line
print(star) #once we printed our i stars, we print the i+1 and go to a new line
