簡體   English   中英

為什么我的條件在 for 循環中不起作用?

[英]Why my conditions dont work inside for loop?

任務是從用戶那里獲取星星的數量,然后將其打印為反向金字塔。

數字必須是奇數,從 0 到 11。它總是打印 11 顆星並忽略條件,無論給定什么

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("")

你的測試不應該在循環中,它應該在輸入之后。 並且您需要使用or ,而不是and ,因此如果任一檢查為真,它就會成功。 為了禁止偶數,模數測試應該是== 0

然后您需要為輸入使用與循環迭代變量不同的變量,並在range()函數中使用輸入編號作為起點,而不是硬編碼 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM