Python math code greater than and less than not working - python

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 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.

You've got 2 SyntaxErrors:
There is no else if in Python, just elif
You need a : after the conditions.
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")

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

Related

Why doesn't "correct" change to False in this if-else ladder of conditions for date-checking?

I have correct = bool() declared outside any function or loop in the beginning of the script. I define a function and have the following conditions. Here is my code.
correct = bool()
...
def part1():
global date, now, m, d, query
#getting the date
raw = input("Date: (MM/DD) ")
#splitting the date by /
m, d = raw.split("/")
#checking for invalid date
if int(m) > 12 or int(m) < 1:
print("Something's wrong with your date.1")
correct = False
#February 29
if int(m) == 2 and int(d) > 29:
print("Something's wrong with your date.2")
correct = False
if int(m) in thirties and int(d) > 30:
print("Something's wrong with your date.3")
correct = False
if int(m) in thirty_ones and int(d) > 31:
print("Something's wrong with your date.4")
correct = False
if int(d) < 1:
print("Something's wrong with your date.5")
correct = False
else:
correct = True
print(correct)
#creating string of date from numbers
if correct == True:
date = months[m] + " " + d
print("Date = ", date)
#creating query
query = months[m] + " " + d
print("Query: " + query)
If I input 01/35 (January 35, obviously an invalid date), it goes through the conditions and prints "Something's wrong with your date.4", telling me it's faulty by the condition if int(m) in thirty_ones and int(d) > 31: (thirty_ones is a list of numbers representing months which have 31 days declared along with correct = bool()). Since it printed that statement, then it would've made correct = False. However, the query is generated, even if correct = False. Why is that?
(apologies for the indentation problems in the code)
You need to use elif.
if int(m) > 12 or int(m) < 1:
print("Something's wrong with your date.1")
correct = False
#February 29
elif int(m) == 2 and int(d) > 29:
print("Something's wrong with your date.2")
correct = False
elif int(m) in thirties and int(d) > 30:
print("Something's wrong with your date.3")
correct = False
elif int(m) in thirty_ones and int(d) > 31:
print("Something's wrong with your date.4")
correct = False
elif int(d) < 1:
print("Something's wrong with your date.5")
correct = False
else:
correct = True
It is because of the following condition.
if int(d) < 1:
print("Something's wrong with your date.5")
correct = False
else:
correct = True
This code is getting executed after "if int(m) in thirty_ones and int(d) > 31" condition and it goes to else and set it to True.
You apparently didn't declare global correct, so the toplevel assignment correct = bool() gets masked by the assignment inside the function. Anyway, don't use globals, it's terrible practice.
Also, your code is quite convoluted, you can make the if-elif ladder shorter and clearer with the following.
Python allows triple conditions with <, <=, so instead of int(m) > 12 or int(m) < 1, do not 1 <= m <= 12. Python gets that right and doesn't even need parens around the not ...
all your your if...elif ladder's early-terminations give False, so just set that at the top, and override it if you get to the successful clause. Or else move check_date(m, d) into a separate predicate helper function, and call it.
Code like this:
m, d = [int(_) for _ in raw.split("/")]
# checking for invalid date
if not 1 <= m <= 12:
return False
elif m == 2 and d > 29:
print("Something's wrong with your date.2")
return False
elif m > 30 and d > 30:
print("Something's wrong with your date.3")
return = False
elif m = 31 and d > 31:
print("Something's wrong with your date.4")
return False
else:
return True
Notes:
Python allows triple conditions with <, <=, >, >=, ==
you only ever use the int() values of m and d, so convert them at the top, already. Doing that in a list comprehension saves an extra line.

"out of range" else clause causes syntax error

I want to check the value range of an input number, then print the correct "size" (small, medium or large). If the value is out of my acceptable range, then I want the else statement to print out that the number is not valid.
Minimal example for my problem:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
if 5 <= n < 10:
a = "medium"
if 10 <= n <= 20:
a = "large"
print("this number is",a)
else:
print("thats not a number from 0 to 20")
According to Google, this is a problem with indentation. I've tried multiple ways of indenting this; I can fix the syntax, but I can't get the logic correct.
Let's fix your immediate issue: you have an else with no corresponding if statement. Syntactically, this is because you have an intervening "out-dented" statement, the print, which terminates your series of ifs.
Logically, this is because you have two levels of decision: "Is this a number 0-20?", and "Within that range, how big is it?" The problem stems from writing only one level of ifs to make this decision. To keep close to your intended logic flow, write a general if on the outside, and encapsulate your small/medium/large decision and print within that branch; in the other branch, insert your "none of the above" statement:
n = int(input("number= "))
if 0 <= n <= 20:
if n < 5:
a = "small"
elif n < 10:
a = "medium"
else:
a = "large"
print("this number is", a)
else:
print("that's not a number from 0 to 20")
You should try something like
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
elif 5 <= n < 10:
a = "medium"
elif 10 <= n <= 20:
a = "large"
else:
a = "not a number from 0 to 20"
print("this number is",a)
The print statement before the else statement needs to either be removed or indented to match:
a= "large"
You've syntax (indentation) error:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
if 5 <= n < 10:
a = "medium"
if 10 <= n <= 20:
a = "large"
#print("this number is",a) indentation error in this line
else:
print("thats not a number from 0 to 20")
You can use also use following code
n = int(input("number= "))
if 10 <= n <= 20:
a = "large"
print("this number is",a)
elif 5 <= n < 10:
a = "medium"
print("this number is",a)
elif 0 <= n < 5:
a = "small"
print("this number is",a)
else:
print("thats not a number from 0 to 20")
The problem is with the print statement.
It is indented on the same level as the if block and thus, the if block ends on line containing the print statement.
Thus, the else on the next line is incorrect.
To achieve what you are trying, you should do something like this:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
elif 5 <= n < 10:
a = "medium"
elif 10 <= n <= 20:
a = "large"
else:
print("not between 0 and 20")
print("The number is", a)
The print statement needs to be placed after the else block. Also, its best to use elif statements than if statements in a situation like this.
n = int(input("Enter a number between 0 and 20: "))
if 0 <= n <= 5:
a = "small."
elif n <= 10:
a = "medium."
elif n <= 20:
a = "large."
else:
a = "invalid / out of range."
print("This number is ", a)

Need help,writing a python BMI calc

I am new to python and and currently learning to use functions properly.
h = 1.75
w = 70.5
bmi = float(w / h ** 2)
if bmi < 18.5:
print('过轻')
elif 18.5 <= bmi < 25:
print('正常')
elif 25 <= bmi < 28:
print('过重')
elif 28 <= bmi < 32:
print('肥胖')
else bmi >= 32:
print('严重肥胖')
Every time I run this program as an attempt I come into this error
File "/Users/frank/Coding/bmimyself.py", line 17
else bmi >= 32:
^
SyntaxError: invalid syntax
I would appreciate any assistance with my coding errors I must have made
You can't apply a condition like bmi >= 32 in an else statement. An else statement handles the case when none of the previous if/elif statements were True, so it's already associated with an implicit condition.
You should have:
if bmi < 18.5:
print('过轻')
elif 18.5 <= bmi < 25:
print('正常')
elif 25 <= bmi < 28:
print('过重')
elif 28 <= bmi < 32:
print('肥胖')
else:
print('严重肥胖')
To avoid the SyntaxError.
This statement is not "else", it is another "elif".
elif bmi >= 32:
print 'foo'
else:
print 'bar'
You need to use
elif bmi >= 32:
with just "else" you cannot have conditional expression. It instead means if none of the condition above satisfied then do this.
Just simply change the last "else" to "elif"
else statement is something like last resort option if none of the above elif conditions are met.

Python 3 else for all previous ifs

Say I have the following Python 3 code:
def foo(number_a, number_b):
if number_a >= 0:
print("a is Positive")
if number_b <= 100:
print("b is <= 100")
else:
print("a is negative and b > 100")
How can I have the else fire if and only if both conditions are false?
I could do something like this:
doElse = True
if condition1:
doElse = False
# do something
if condition2:
doElse = False
# do something
# condition3...conditionN
if doElse:
# do the else
But that would require setting the variable, then changing it for every if
Is there a better way to do this?
As long as your first and second condition are mutally exclusive, you should always solve this with a single if/elif/else construct. Using your original example:
if word == "banana":
print("word is banana")
elif word == "apple":
print("word is not banana, but it is apple")
else:
print("word is neither banana, nor apple, but something else")
If you have conditions which are not mutally exclusive, then this obviously doesn’t work as you want to continue checking the other conditions as well.
In that case, you should try to find a common condition for all of them. This can be as simple as combining the conditions with or:
if number >= 0 or number <= 100:
if number >= 0:
print("Positive")
if number <= 100:
print("<= 100")
else:
print("x < 0 or x > 100")
But you could also combine them if that’s possible:
if 0 <= number <= 100:
…
Or you could replace the else by an inverted condition:
if number >= 0:
print("Positive")
if number <= 100:
print("<= 100")
if number < 0 or number > 100:
print("x < 0 or x > 100")
For everything more complicated than that, you will have to keep track of this in another way, involving more code.
You can just reorder the if statements like so:
def foo(number_a, number_b):
if number_a < 0 and number_b > 100:
print("a is negative and b > 100")
elif number_a >= 0:
print("a is Positive")
else:
print("b is <= 100")

Python greater than or less than

I have an 'if-elif-else' block and if a value is within that range it is assigned a certain value. However it when I run it just assigns it the value in the else block. This is my code:
if mile < 300:
mileInfo['miles'] = 1
elif mile>=300 and mile <2000:
mileInfo['miles'] = 2
elif mile>=2000 and mile <5000:
mileInfo['miles'] = 3
else:
mileInfo['miles'] = 4
Mile returns a float, but I thought that this didn't matter as much as in Java for example.
Thanks
Maybe mile is a string containing a number? It will not be automatically converted.
>>> "1" < 100
False
>>> "1" == 1
False
You don't need to have the elif re-check that the previous if was false. If the value wasn't < 300, it is guaranteed to be >=300.
The issue was that 'mile' was a string and as pointed out by other members string is not automatically converted. So I changed code to:
mileInt = int(float(mile))
if mileInt < 300:
mileInfo['miles'] = 1
elif mileInt < 2000:
mileInfo['miles'] = 2
elif mileInt < 5000:
mileInfo['miles'] = 3
else:
mileInfo['miles'] = 4
Using print type(mile) helps check what the type is.

Categories

Resources