简体   繁体   中英

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

I am trying to make it if the number is between 1 to 15 the racquet is broken but if it is 16-100 it is not broken. It says it is invalid syntax in python. Why is it invalid syntax?

You've got 2 SyntaxErrors:

And a logical mistake:

  • i > 100 can never be True .

Then you also don't need and here, you could just use:

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

There is also the shortened version of i > 0 and i < 16 :

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

You appear to be trying to "fold" a nested if statement into its containing if statement, C-style:

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

Because the whitespace isn't significant, the above is equivalent to

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

giving the illusion of an else if clause.


In Python, indentation is significant, so you can't pull the same trick as in C. Instead, Python has an explicit elif clause that you can use to check multiple conditions in a single if statement.

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

This is semantically equivalent to

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

but nicer looking.

In Python, you use elif instead of else if . You also need a colon at the end of your else if line.

It should be:

elif i > 16 and i > 100:

elif and with ":" in the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM