Need help,writing a python BMI calc - python

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.

Related

How to read data from keyboard using input() with a ( ) for input?

I am a beginner at programming, and now I have a problem changing the input of ( ) to the users' input.
Given a person’s weight (in kilograms) and height (in meter), his/her BMI (Body Mass Index) is calculated based on this formula:
BMI = Weight / Height2
Write a function compute_bmi() that reads in that order, the user's height (in meter) and weight (in kilogram), and returns a string that shows the body type of the user:
"Under" : if the BMI is lower than 18.5 (exclusive)
"Normal": if the BMI is higher than 18.5 (inclusive) but lower than 25 (exclusive)
"Over": if the BMI is higher than 25 (inclusive) but lower than 35 (exclusive)
"Obese": if the BMI is higher than 35 (inclusive)
For example, suppose height is 1.7 (meters) and weight is 68 (kilograms), function call compute_bmi() will read 1.7 and 68 from the keyboard and then return string "Normal".
Be reminded that both height and weight should be converted to float type.
Note that in this question, we read data from the keyboard using input(). For other questions in this assignment, data are passed to our functions as parameters (i.e. they don't use input()). These are two different designs.
This is my programming, I tried it on IDLE and it works. but the assignment page shows it doesn't work.
def check_bmi():
mass = float(data[1])
height = float(data[0])
BMI = mass/height**2
if BMI < 18.5:
return 'under'
elif 18.5 <= BMI < 25:
return 'Normal'
elif 25 <= BMI < 35:
return 'Over'
else:
return 'Obese'
Can anyone give me some advice? Thanks a lot :D
A note on comparisons:
if BMI < 18.5:
return 'under'
elif 18.5 <= BMI < 25:
return 'Normal'
elif 25 <= BMI < 35:
return 'Over'
else:
return 'Obese'
Consider that if the first condition isn't true, BMI must be greater than or equal to 18.5. And if the second isn't true, BMI must be greater than or equal to 25.
if BMI < 18.5:
return 'under'
elif BMI < 25:
return 'Normal'
elif BMI < 35:
return 'Over'
else:
return 'Obese'
You would read height and weight using input, but you have to convert that to float. Remember that BMI is weight divided by height squared.
def compute_bmi():
height = float(input())
weight = float(input())
BMI = weight / height ** 2
if BMI < 18.5:
return 'under'
elif BMI < 25:
return 'Normal'
elif BMI < 35:
return 'Over'
else:
return 'Obese'

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)

Python - Multiple Elif Statements Being Skipped Over in If Statement

I'm trying to get my program to return different statements based off the hour the user inputs. If I input a number for hour between he first two statements ((hours < 6) and (hours <= 10) or (hours >= 6)), it will return the correct string but if I input anything greater than 10 for the hour, it won't return the intended string for that hour but it will keep repeating the second string.
Any help is appreciated!
Here's my program:
https://i.stack.imgur.com/uQzBi.png
def food(hours, boolean):
if boolean == "True" or boolean == "true":
if (hours < 6):
return "no food"
elif (hours <= 10) or (hours >= 6):
return "breakfast, marmalade"
elif (hours <= 15) or (hours >= 11):
return "lunch, true,dessert"
elif (hours < 22) or (hours >= 15):
return "dinner, dessert"
else:
return "no food"
else:
if (hours < 6):
return "no food"
elif (hours <= 10) or (hours >= 6):
return "breakfast,coffee"
elif (hours <= 15) or (hours >= 11):
return "lunch, false"
elif (hours < 22) or (hours >= 15):
return "dinner"
else:
return "no food"
x = food(15, "true")
print(x)
You should be using “and” instead of “or”. Anything > 10 will also be >= 6 so the second condition always matches.
Python have boolean value True and False. Their is no need to use strings 'True' or 'False'. You can also use the power of if-elif-else logic. Python executes from top to bottom, when condition is met, it breaks. Your function can be rewritten to this:
def food(hour, boolean):
'''Food
Takes in hour as int and boolean as bool
E.g. x = food(15,True)
# TODO:
Ensure that input data types are correct.
'''
if boolean:
if hour >= 22 or hour >= 0:
return 'no food'
elif hour >= 15:
return 'dinner, dessert'
elif hour >= 11:
return 'lunch, true,dessert'
elif hour >= 6:
return 'breakfast, marmalade'
else:
raise ValueError('something wrong')
else:
if hour >= 22 or hour >= 0:
return 'no food'
elif hour >= 15:
return 'dinner'
elif hour >= 11:
return 'lunch, false'
elif hour >= 6:
return 'breakfast, coffee'
else:
raise ValueError('something wrong')
x = food(15, True)
print(x)
Looks like the first elif statement is your problem. You should use and instead of or. By using or, anything >= 6 will return breakfast marmalade, not just anything between 6 and 10.
Welcome to StackOverflow! As mentioned by the other answers, using 'and' instead of 'or' would solve your issue. However, it is redundant to include more than one condition for each meal if they are all sequential as by writing:
if (hours < 6):
return "no food"
you are already saying to only output the return value if the hour input is less than 6, hence only values more than 6 would make it to the next elif statement.
Do let me know if I misunderstood something about your program's use case that required you to write the code as such!

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

Categories

Resources