簡體   English   中英

Python數學代碼大於和小於不起作用

[英]Python math code greater than and less than not working

import numpy as np
import random
i = random.randint(1,100)
if i > 0 and i <16:
    print ("Broken")
else if i > 16 and i > 100
    print ("Not broken")

我正在嘗試使數字在1到15之間,但球拍壞了,但如果是16-100,則拍子沒有壞。 它說這是python中的無效語法。 為什么語法無效?

您有2個SyntaxErrors:

還有一個邏輯錯誤:

  • i > 100永遠不可能是True

然后,您也不需要and在這里,您可以使用:

import random
i = random.randint(1,100)
if i < 16:
    print ("Broken")
else:
    print ("Not broken")

還有i > 0 and i < 16的縮寫:

if 0 < i < 16:
    print ("Broken")
elif 16 < i <= 100:  # compare to "<= 100" instead of "> 100"
    print ("Not broken")

您似乎正在嘗試將嵌套的if語句“折疊”為C風格的包含if語句:

if (i > 0 && i < 16)
    printf("Broken\n");
else
    if (i > 16 && i < 100)
        printf("Not broken\n");

由於空格不重要,因此上述內容等效於

if (i > 0 && i < 16)
    printf("Broken\n");
else if (i > 16 && i < 100)
    printf("Not broken\n");

給出else if子句的錯覺。


在Python中,縮進非常重要,因此您不能像在C中那樣使用相同的技巧。相反,Python具有顯式的elif子句,可用於在單個if語句中檢查多個條件。

if i > 0 and i < 16:
    print("Broken")
elif i > 16 and i < 100:
    print("Not broken")

這在語義上等同於

if i > 0 and i < 16:
    print("Broken")
else:
    if i > 16 and i < 100:
        print("Not broken")

但看起來更好。

在Python中,您可以使用elif代替else if 您還需要在else if行的末尾添加一個冒號。

它應該是:

elif i > 16 and i > 100:

elif並以“:”結尾

暫無
暫無

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

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