How to write an if statement with an interval? - if-statement

I can't figure it out.
So far I have, but it isn't working, no matter what age I input it tells me I can be president.
import math
(x) = input("Please enter your name:")
(y) = input("Please enter your age:")
print ("Hello" + x)
print ("Your age is" + y)
if ("y")> ("0") and ("y") < ("18"):
print("You are a minor.")
if ("y")>=("18") and ("y") < ("25"):
print("You can vote.")
if ("y")>= ("25") and ("y") < ("35"):
print("You can rent a car.")
if ("y") >= ("35"):
print("You can be president.")
else:
print ("You have not entered a valid response. Must be a positive integer.")
How to get the intervals properly?

Writing an inequality range is a lot simpler in Python than doing distinct cut-offs; you can use math-style ranges.
Here's an example:
if 0 < y < 18:
print("You are a minor.")
You shouldn't quote your variable, as that will treat it like a string literal.

With help from the awesome Makoto, it's fixed! :D
import math
(x) = input("Please enter your name:")
(y) = int(input("Please enter your age:"))
print ("Hello" + x)
print ("Your age is" , y)
if 0 < (y) < 18:
print("You are a minor.")
elif 18 <= (y) < 25:
print("You can vote.")
elif 25 <= (y) < 35:
print("You can rent a car.")
elif (y) >= 35:
print("You can be president.")
else:
print ("You have not entered a valid response. Must be a positive integer.")

Related

Why is the average not calculating correctly, and why does the average letter grade remain F no matter the number?

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

How to set an input limits on list with python 3

#room B register
#matrix method
roomB = [[],[]]
I am planning to enter only 3 units in here roomB=[[ ],[ ]] and if the first unit full, the system should suggest another unit.
def func():
row = int(input("Choose 0 or 1:"))
if (row == 0): # ROW 0 IS FOR HOUSE 1:
name = input("Enter your room name: ")
print("Enter M or N") #M for master room
room_type = input("") #N for normal room
for u in roomB: #3 units in roomB[0]
if(len(u)<3):
if (room_type == "M"):
return roomB[0].append([room_type,name,140])
if (room_type == "N"):
return roomB[0].append([room_type,name,140])
roomB = [[],[]]
def update(row): # takes sublist as argument
if len(roomB[row]) < 3: # checks if sublist length is less than 3
name = input("Enter your name: ")
room_type = input("Enter room type : M (master room) or N (normal room) : ").lower()
roomB[row].append([room_type,name,140])
return "your room no. is {} at row {}".format(roomB[row].index([room_type,name,140]) + 1, row) # returns string stating status
def func():
if len(roomB[0]) < 3 and len(roomB[1]) < 3: # ask for prompt only if space available in both sublist
row = int(input("Choose 0 or 1: ")) # allow to select row
return update(row)
elif len(roomB[0]) >= 3 and len(roomB[1]) < 3: # selects default sublist if no space on other sublist
print("No room available at 0 , selected 1 ")
return update(1) # returns string stating status
elif len(roomB[0]) < 3 and len(roomB[1]) >= 3: # selects default sublist if no space on other sublist
print("No room available at 1 , selected 0 ")
return update(0)
else: # in case any error occurs it goes here
print("Errrr.......")
print("room stat....: ", roomB)
while len(roomB[0]) <= 3 or len(roomB[1]) <= 3: # loop will flow if length of both sublist is greater than or equals to 3
if len(roomB[0]) != 0 or len(roomB[1]) != 0: # won't ask for confirmation if all all lists are empty (skips prompts for initial)
cond = input("do you want to continue?(Y/N) ").lower()
if cond == "n":
break # break the loop if pressed n or N otherwise continue to execute
elif len(roomB[0]) >= 3 and len(roomB[1]) >= 3: # error message to print if no space left in sublists
print("No room available.. Sorry for inconvinience.")
print(func())

How do I get my code to repeat itself if the desired input is not entered?

I just started python 2 weeks ago and I don't know how to make my code repeat itself when the input is something like "fox" when that is not one of the three options I'm accepting (horse, oxen, mule). Also if I want to total up the cost of 2 horse and say 3 mules by having it ask "do you want to buy any more animals", how would i do that? Any help would be very appreciated.
zoo = {}
def main():
print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
global animal_quantity
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
while True:
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
else:
cost(total_money)
def cost(total_money):
costing = animal_cost(total_money)
total_money -= costing
if total_money <= 0:
print ("No money left, resetting money to 1000.")
total_money = 1000
zoo.clear()
print ("Cost of Animals: " + str(costing))
print ("Remaining Balance:" + str(total_money))
choice = raw_input("Do you want to buy any more animals?(Y/N):")
if choice in('Y','y'):
cost(total_money)
elif choice in ('N','n'):
choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
if choice_2 in('zoo','Zoo'):
print zoo
choice_3 = raw_input("is everything correct?(Y/N):")
if choice_3 in ('Y','y'):
print ("Thank you for shopping!")
elif choice in ('N','n'):
print ("Restarting Transaction")
zoo.clear()
cost(total_money)
if __name__ == '__main__':
main()
You may try this enhanced version of your code:
zoo = {} # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
# getting total_money after animal purchase
def cost(total_money):
costing = animal_cost(total_money)
total_money = total_money - costing
if total_money <=0: # condition when money is less than or equal to 0.
print("No Money left, resetting money to 1000.")
total_money = 1000
print ("Cost of Animals:" + str(costing))
print ("Total Money Left:" + str(total_money))
# Recursion for buying more animals:
choice = raw_input("Do you want to buy any more animals?:")
if choice in ('Yes','y','Y','yes','YES'):
cost(total_money)
# you can use this commented elif condition if you want.
else: # elif choice in('no','No','n','N','NO'):
print("thankyou!!")
print("You have total animals: "+str(zoo))
# main function to initiate program
def main():
print ("Animals available to purchase: " + "horse, oxen, mule")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
if __name__ == '__main__':
main()
This might help you out.
Have a look into this for last two lines

Python Salary Program Using Conditionals

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.

(Super beginner) Can someone explain what's going wrong with my lists?

Ok, so, this is the longest code I've ever written, so I apologize if it's a bit messy. First computer science assignment ever.
def main():
#generate random value
import random
rand = random.randint(1, 99)
#instructions
print("""The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value. Enter coins as 1=penny, 5-nickel,
10-dime, 25-quarter. Hit return after the last entered coin value.""")
#defining function for 'first coin'
def firstCoin ():
coins = []
global coins
coin = int(input("Enter first coin: "))
if coin > rand:
print("Sorry, total value exceeds", rand, "cents.")
again = input("Try again (y/n): ")
if again == "y" or "Y":
main()
else:
sys.exit() #ends program
elif coin in possible:
coins.append(coin)
nextCoinplease()
#defining function for 'next coin'
def nextCoinplease ():
while True:
nextcoin = (input("Enter next coin: "))
if nextcoin in possible:
coins.append(nextcoin)
elif nextcoin == "":
break
else: print("Invalid entry.")
#making lists
possible = [1, 5, 10, 25]
print("Enter coins that add up to", rand, "cents, one per line.") #program start
firstCoin ()
sumcoin = sum(coins)
print(sumcoin)
if sumcoin == rand:
print("Correct!")
else:
print("Invalid entry.")
firstCoin()
main()
So, this is my issue. For some reason, user input in the function nextCoinplease does not get added to the list "coins", only the first input from the function firstCoin does. This means that sum(coins) is literally only the first input. I cannot for the life of me figure out why, so any input would be greatly appreciated, thanks!
You have two input statements, one to get coin and one to get nextcoin. They are different. What's the difference?
(I'm deliberately not giving the answer outright because from what you've written so far, I am sure you can figure this one out given this hint.)
The return type of input is a string, so nextcoin in possible always fails since possible only contains integers. Try using int() to parse the input as an integer.
Your code never gets to check if the rand is equal to sumCoin, so it never stopped. I've fixed the problem, this code works now.
Demo on repl.it
What did I do?
I moved your if statement that checked if rand == sumCoin at the beginning of the while loop in nextCoinPlease(), so that it will check the sumCoin value before entering each next coin value and will stop once it equals rand.
Code:
import random
import sys
def main():
rand = random.randint(1, 99)
print('''The purpose of this exercise is to enter a number of coin values \
that add up to a displayed target value. Enter coins as 1=penny, \
5=nickel, 10-dime, 25-quarter. Hit return after the last entered \
coin value.''')
coins = []
def firstCoin():
coin = int(input("Enter first coin: "))
if coin > rand:
print('Sorry, total value exceeds ', rand, ' cents.')
again = input('Try again? (y/n): ')
if again == 'y' or 'Y':
main()
else:
sys.exit()
elif coin in possible:
coins.append(coin)
nextCoinPlease()
def nextCoinPlease():
while True:
sumCoin = sum(coins)
print('Total Value: ' + str(sumCoin))
print ''
if sumCoin == rand:
print('Correct! You Win!')
sys.exit()
elif sumCoin > rand:
print('You exceeded the total value! You lose! Try again!')
sys.exit()
nextCoin = (input('Enter next coin: '))
if nextCoin in possible:
coins.append(nextCoin)
elif nextCoin == "":
break
else:
print('Invalid entry.')
possible = [1, 5, 10, 25]
print('Enter coins that add up to', rand, 'cents, one per line.')
firstCoin()
main()