This is a simple code where the script would ask for the user's name, age, sex, and height and give an output based on that. My current code is as follows:
print "What is your name?"
name = raw_input()
print "How old are you?"
age = raw_input()
print "Are you male? Please answer Y or N"
sex = raw_input()
if sex == "Y" or sex == "y":
sex = "Male"
else:
sex = "Female"
print "How tall are you? Please enter in feet such as 5.5"
height = raw_input()
if sex == "Male" and height >= 6.0:
t = "You are tall for a male"
elif sex == "Male" and height < 6.0:
t = "You are below average for a male"
elif sex == "Female" and height >= 5.5:
t = "You are tall for a female"
else:
t = "You are below average for a female"
print "Hello %s. You are %s years old and %s feet tall. %s." % (name, age, height, t)
I am getting hung up on the if, elif, else statement:
if sex == "Male" and height >= 6.0:
t = "You are tall for a male"
elif sex == "Male" and height < 6.0:
t = "You are below average for a male"
elif sex == "Female" and height >= 5.5:
t = "You are tall for a female"
else:
t = "You are below average for a female"
The code will differentiate if sex is Male or Female, but will always return "You are tall for a xxx". I can not figure out how to get the "You are below average" return.
That's because raw_input() returns a string, not a float, and comparison is always the same way between a string and a float in Python 2.
>>> "1.0" > 6.0
True
Do this:
height = float(raw_input())
height = input() would have worked too but is discouraged (security issues because of evaluation)
Note: this has been fixed in Python 3 (probably because it wasn't very useful, and error-prone): trying to do this results in
TypeError: unorderable types: str() > float()
which is explicit and would have allowed to realize your mistake.
Note: same issue if you try to compare age (age = raw_input() should be age = int(raw_input()))
Related
This is my code for the program that calculates 5 user inputs of test scores, displays the letter grade, and then calculates the average score and letter grade. However, the grade comes back as the wrong average, and the letter grade stays F no matter the number.
import os
#constants
PROG_ID = "\nFilename: Average_Grade.py\n"\
"Homework: 09\n"\
"Source Code Author: \n"\
"Reference: Chapter 5\n"\
"Date: 9 April 2022\n"
USER_PROMPT = "Please enter a test score. "
GRADE_TAG = "The letter grade is "
OUTPUT_TAG = "The average grade is "
#display program id
def progId ():
print(PROG_ID)
print()
#prompt user
def getInput(testScore, gradeList):
for item in range (5):
testScore = int(input(USER_PROMPT))
gradeList.append(testScore)
determineGrade(testScore)
print()
#letter grade
def determineGrade(testScore):
if testScore >= 90: print (GRADE_TAG, "A")
elif testScore >= 80: print (GRADE_TAG, "B")
elif testScore >= 70: print (GRADE_TAG, "C")
elif testScore >= 60: print (GRADE_TAG, "D")
else: print (GRADE_TAG, "F")
#show average
def calculateAverage(testScore, gradeList):
avg = sum(gradeList)/len(gradeList)
print(OUTPUT_TAG, format(avg, ".0f"))
avg = testScore
determineGrade(testScore)
def housekeeping():
input ("Press enter to exit.")
os._exit(1)
#control
def main():
#variables
testScore = avg = 0
gradeList = [testScore]
#calls
progId()
getInput(testScore, gradeList)
calculateAverage(testScore, gradeList)
main()
housekeeping()
If for some reason your main does not get called before the rest your gradeList is never initialised and calling methods on it would do nothing? I would initialise the array at the beginning of the file. You should test if at any point your array does not only contain 0, or nothing at all with a console.log().
I'm trying to write a script that takes in a character (M) OR (F) and returns output as male OR female. I was wondering how I could do this with a while loop. What I have currently is if statements which do not loop back.
gender = input('What is your gender? M/F: ').capitalize()
mGender = ''
if gender == 'M':
mGender = 'Male'
elif gender == 'F':
mGender = 'Female'
else:
#how do I go back to make sure only F/f or M/m were input by the user?
You are trying to do when user input M/m or F/f program display male/female. If you enter any other character system should display "please enter gender again message" and user asked again what is your gender. You can try this
gender = input('What is your gender? M/F: ').capitalize()
mGender = ''
while gender != 'M' or gender != 'F':
if gender == 'M':
mGender = 'Male'
break;
elif gender == 'F':
mGender = 'Female'
break;
else:
print("Wrong input please enter gender again")
print()
gender = input('What is your gender? M/F: ').capitalize()
print('Your gender is = ' +mGender)
In this code If you enter wrong character system ask your gender again and again until you enter M/m or F/f.
def BMI_calculator(inches, weight):
""" This function takes a persons height in feet and inches and their
weight in pounds and calculates their BMI"""
# Now we can just convert and calculate BMI
metric_height= inches* .025
metric_weight= weight* .45
BMI = int(metric_weight/(metric_height)**2)
print BMI
return BMI
def BMI_user_calculator():
""" This function will ask the user their body information and calulate
the BMI with that info"""
# First we need to gather information from the user to put into the BMI calculator
user_weight = int(raw_input('Enter your weight in pounds: '))
user_height = int(raw_input('Enter your height in inches: '))
print "Youre BMI is",
BMI_calculator(user_height, user_weight)
If BMI < 18.5:
print "You're BMI is below the healthy range for your age"
elif BMI > 24.9:
print "You're BMI is above the healthy range for your age"
else:
print "You are in the healthy BMI range!"
Here is the code I have so far, but when run I get a syntax error within my if statement saying BMI is not defined. BMI was returned from the first function so I really don't understand what is happening
You don't have BMI declared in your BMI_user_calculator() that's why it says BMI is not defined. You should declare BMI first before using it for comparison in if-elif statement.
In addition, your If should be if. Python is case-sensitive.
Your code should then read something like this:
def BMI_calculator(inches, weight):
metric_height= inches* .025
metric_weight= weight* .45
BMI = int(metric_weight/(metric_height)**2)
# No need to print BMI here anymore since you're returning it anyway
# print BMI
return BMI
def BMI_user_calculator():
user_weight = int(raw_input('Enter your weight in pounds: '))
user_height = int(raw_input('Enter your height in inches: '))
BMI = BMI_calculator(user_height, user_weight)
print "Your BMI is", BMI
if BMI < 18.5:
print "Your BMI is below the healthy range for your age"
elif BMI > 24.9:
print "Your BMI is above the healthy range for your age"
else:
print "You are in the healthy BMI range!"
if __name__ == '__main__':
BMI_user_calculator()
I get an error # line 19, the Bonus function and I can't figure out why. I'll probably get an error for the other functions too. I've checked my spaces, my numbers vs. my strings, and my DOM. My first problem were about my globals and I fixed it from global comrate to `comrate = 0; . I've got debugging blindness. Thank you guys in advance!
def main():
#Welcome user and get sales number
print("Welcome to the Bonus Qualification Calculator! Please honestly answer the following questions:")
name = str(input("What is your name? "))
sales = float(input("What is your sales total? "))
jobtime = float(input("How many months have you been with the company? "))
vacationtime = float(input("How many vacation days have you taken? "))
#Define Global Vars
comrate = 0;
compedsalary = 0;
bonussalary = 0;
finalsalary = 0;
#Begin calculations
Bonus(sales, jobtime)
vacation(vacationtime)
print(str(name) + ", your salary based on the information you provided is " + str(format(finalsalary,'.2f'))
def Bonus(sales,jobtime):
#Calcultate commission
if sales < 10000:
comrate = 0
elif sales > 10000 and sales <= 1000000:
comrate = .02
elif sales >= 100001 and sales <= 500000:
comrate = .15
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 1000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
elif sales >= 500001 and sales <= 1000000:
comrate = .28
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 5000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
elif sales > 1000000:
comrate = .35
compedsalary = float(comrate * 2000)
if jobtime > 3:
bonussalary = float(compedsalary + 100000)
elif jobtime > 60:
bonussalary = float(compedsalary + 101000)
else:
print("You don't qualify for a bonus due to your limited time at the company.")
def vacation(finalsalary):
if vacation > 3:
finalsalary = float(bonussalary - 200)
else:
finalsalary = bonussalary
main()
You're using full quotes where you should be using apostrophes. You're using contractions in your print statements, which confuses Python. Just put "do not" instead of "don't" in your print statements.
I'm writing something in python, and I don't understand why this section of code isn't working.
m = 1
f = 0
gender_choice = False
while gender_choice == False:
gender = input('Are you male or female? Type m for male or f for female. ')
if gender == m or gender == f:
print
gender_choice = True
else:
print
print "Hey, this is a text based game. Read and follow bro."
print gender
I think I understand that there is an issue with setting a string to "m" or "f", but unless I change raw_input to input, the loop will continue. Also, as is currently written, if the user enters anything other than a number, m, or f, I will get an error that the string is undefined, for example, if they enter "y".
Ok, first of check your indentation!
This is how I would think that you'd like it to look:
m = 1
f = 0
gender_choice = False
while gender_choice == False:
gender = input('Are you male or female? Type m for male or f for female. ')
if gender == m or gender == f:
print
gender_choice = True
else:
print
print "Hey, this is a text based game. Read and follow bro."
print gender
Then your else statement will only get executed when your if statement gets evaluated as False, which is always at the moment since it evaluates whether gender == 1 or gender == 0 which will only happen if your user does not "Read and follow bro." I do not know if you need the m and f variables later in your code but I'm going to assume that you do, so what I'd do is this:
gender_choice = False
while gender_choice == False:
gender = raw_input('Are you male or female? Type m for male or f for female. ')
if gender == "m":
print
gender_bool = 1
gender_choice = True
elif gender == "f":
print
gender_bool = 0
gender_choice = True
else:
print "\nHey, this is a text based game. Read and follow bro.\n"
print gender
That way your logic works and the m and f variable has been put into one variable (gender_bool) that can be evaluated in later logic, the if statements evaluates something that makes more sense (imho) and you use raw_input so that you can enter anything in there without raising errors (and I added some \n (linebreaks) to please my OCD :P).