madgoat
madgoat

Reputation: 1

Why my conditions dont work inside for loop?

The task is to take the amount of stars from the user and then print it as a reverse pyramid.

The number must be odd and from 0 to 11. It always prints 11 stars and ignores the conditions no matter what given

stars = int(input("Put the odd number of stars\n"))
space = 0
for stars in range(11, 0, -2):
    if stars > 11 and stars < 1 and (stars % 2 != 0):
        print("wrong number")
print(space * " " + stars * '*')
space = space + 1
print("")

Upvotes: 0

Views: 35

Answers (1)

Barmar
Barmar

Reputation: 782488

Your test shouldn't be in the loop, it should be right after the input. And you need to use or, not and, so it will succeed if either check is true. And to prohibit an even number, the modulus test should be == 0.

Then you need to use a different variable for the input than the loop iteration variable, and use the input number as the starting point in the range() function rather than hard-coding 11.

while True:
    number = int(input("Put the odd number of stars\n"))
    if number > 11 or number < 1 or (number % 2 == 0):
        print("wrong number")
    else:
        break

space = 0
for stars in range(number, 0, -2):
    print(space * " " + stars * '*')
    space = space + 1

Upvotes: 1

Related Questions