Coffee machine simulator - removing an empty line - python

i finished this coffee machine simulator but i have a small problem.
How can i remove the line added by the check function after i enter the 'e' or 'l' or 'c'?
Below is the code and a sample of the undesired output and the desired input.
The code:
import os
import time
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee_l": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money":0
}
def money():
quarter=0.25
dime=0.1
nickel=0.05
pennie=0.01
qu=float(input("Inset quarters: "))
di=float(input("Insert dimes: "))
ni=float(input("Insert nickels: "))
pen=float(input("Insert pennies: "))
total_paid=qu*quarter+di*dime+ni*nickel+pen*pennie
return total_paid
def check(drink):
if drink == 'espresso':
if resources['water'] >= 50 and resources['coffee'] >= 18:
return ''
elif resources['water'] <= 50:
return "​Sorry there is not enough water."
elif resources['coffee'] <= 18:
return "​Sorry there is not enough coffee."
elif drink=='latte':
if resources['water'] >= 200 and resources['milk'] >= 150 and resources['coffee'] >= 24:
return ""
elif resources['water'] < 50:
return "​Sorry there is not enough water."
elif resources['coffee'] < 18:
return "​Sorry there is not enough coffee."
elif resources['milk'] < 150:
return "​Sorry there is not enough milk."
elif drink=='cappuccino':
if resources['water'] >= 250 and resources['milk'] >= 100 and resources['coffee'] >= 24:
return ""
elif resources['water'] < 250:
return "​Sorry there is not enough water."
elif resources['coffee'] < 24:
return "​Sorry there is not enough coffee."
elif resources['milk'] < 100:
return "​Sorry there is not enough milk."
def make_drink(drink):
if drink == "espresso":
resources['water'] -= 50
resources['coffee'] -= 18
resources['money'] += 1.5
elif drink == "latte":
resources['water'] -= 50
resources['coffee'] -= 18
resources['milk'] -= 150
resources['money'] += 2.5
elif drink == "cappuccino":
resources['water'] -= 250
resources['coffee'] -= 18
resources['milk'] -= 100
resources['money'] += 3
else:
print("Not sure what drink was made")
return
def replenish():
resources['water'] += 300
resources['milk'] += 200
resources['coffee'] += 100
return
while True:
print("Welcome to the coffee machine.")
m="Espresso = 1.5$\nLatte = 2.5$\nCappuccino = 3.0$\n"
print(m)
choice=input("​What would you like? (espresso/latte/cappuccino)(e/l/c): ")
if choice=='report':
print(f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {round(resources['money'],2)}$")
elif choice=='replenish':
replenish()
elif choice=='e':
chk=check('espresso')
print(chk)
if chk=='':
mo=money()
if mo == menu['espresso']['cost']:
make_drink('espresso')
print('Here is your coffee')
elif mo > menu['espresso']['cost']:
make_drink('espresso')
print(f'Here is your coffee, and here is your change {round(mo-menu["espresso"]["cost"], 2)} $')
elif mo < menu['espresso']['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
elif choice=='l':
chk=check('latte')
print(chk)
if chk=='':
mo=money()
if mo == menu['latte']['cost']:
print('Here is your coffee')
elif mo > menu['latte']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["latte"]["cost"]} $')
resources['money']=mo+resources['money']
elif mo < menu['latte']['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
elif choice=='c':
chk=check('cappuccino')
print(chk)
if chk=='':
mo=money()
if mo == menu['cappuccino']['cost']:
print('Here is your coffee')
elif mo > menu['cappuccino']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["cappuccino"]["cost"]} $')
resources['money']=mo+resources['money']
elif mo < menu['cappuccino']['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
elif choice=='off':
break
time.sleep(3)
os.system('clear')
The undesired output:
Welcome to the coffee machine.
Espresso = 1.5$
Latte = 2.5$
Cappuccino = 3.0$
What would you like? (espresso/latte/cappuccino)(e/l/c): e
Inset quarters:
The desired output:
Welcome to the coffee machine.
Espresso = 1.5$
Latte = 2.5$
Cappuccino = 3.0$
What would you like? (espresso/latte/cappuccino)(e/l/c): e
Inset quarters:
How can I do that without ruining the code?
Thanks

change the line
print(chk)
to
if chk:
print(chk)
The empty line comes from calling check("expresso") and returning an empty line (no failure message to display)
So you only print chk if it has a message, but you don't print it if it's empty.

when check('espresso') exceuted, chk value became empty string. To solve it, you should validate if chk value is not an empty string and then print, else don't do anything. You can change the line :
print(chk)
with this:
print(chk) if chk else ''

Related

Cant check for resources

I am working on a code to make a coffee machine simulator and I want to add the money paid from each transaction to the money resources in the machine and I can't
PLease help me do it
Thanks
Here is my code:
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee_l": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money":0
}
import os
def check(drink):
if drink == 'espresso':
if resources['water'] >= 50 and resources['coffee'] >= 18:
return "enough"
elif resources['water'] <= 50:
return "​Sorry there is not enough water."
elif resources['coffee'] <= 18:
return "​Sorry there is not enough coffee."
elif drink=='latte':
if resources['water'] >= 200 and resources['milk'] >= 150 and resources['coffee'] >= 24:
return "enough"
elif resources['water'] < 50:
return "​Sorry there is not enough water."
elif resources['coffee'] < 18:
return "​Sorry there is not enough coffee."
elif resources['milk'] < 150:
return "​Sorry there is not enough milk."
elif drink=='cappuccino':
if resources['water'] >= 250 and resources['milk'] >= 100 and resources['coffee'] >= 24:
return "enough"
elif resources['water'] < 250:
return "​Sorry there is not enough water."
elif resources['coffee'] < 24:
return "​Sorry there is not enough coffee."
elif resources['milk'] < 100:
return "​Sorry there is not enough milk."
def money():
quarter=0.25
dime=0.1
nickel=0.05
pennie=0.01
qu=float(input("Inset quarters: "))
di=float(input("Insert dimes: "))
ni=float(input("Insert nickels: "))
pen=float(input("Insert pennies: "))
total_paid=qu*quarter+di*dime+ni*nickel+pen*pennie
return total_paid
report=f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {resources['money']}$"
while True:
print("Welcome to the coffee machine.")
m="Espresso = 1.5$\nLatte = 2.5$\nCappuccino = 3.0$\n"
print(m)
choice=input("​What would you like? (espresso/latte/cappuccino)(e/l/c): ")
if choice=='e':
# ~ e_w=menu['espresso']['ingredients']['water']
# ~ e_c=menu['espresso']['ingredients']['coffee']
# ~ #print(e_w)
chk=check('espresso')
print(chk)
if chk=="enough":
mo=money()
if mo == menu['espresso']['cost']:
print('Here is your coffee')
elif mo > menu['espresso']['cost']:
print(f'Here is your coffee, and here is your change {round(mo-menu["espresso"]["cost"], 2)} $')
print(f"Money in machine is: {resources['money']}")
elif mo < menu['espresso']['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
resources['money']=mo+resources['money']
print(f"Money in machine is: {round(resources['money'],2)}")
elif choice=='l':
chk=check('latte')
print(chk)
if chk=="enough":
mo=money()
if mo == menu['latte']['cost']:
print('Here is your coffee')
elif mo > menu['latte']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["latte"]["cost"]} $')
resources['money']=mo+resources['money']
print(f"Money in machine is: {resources['money']}")
elif mo < menu['latte']['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
elif choice=='c':
chk=check('cappuccino')
print(chk)
if chk=="enough":
money()
mo=money()
if mo == menu['cappuccino']['cost']:
print('Here is your coffee')
elif mo > menu['cappuccino']['cost']:
print(f'Here is your coffee, and here is your change {mo-menu["cappuccino"]["cost"]} $')
resources['money']=mo+resources['money']
print(f"Money in machine is: {resources['money']}")
elif mo < menu['cappuccino']['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
elif choice=='report':
print(report)
elif choice=='off':
break
I tried to add it under each if statement in the while loop and it worked but when i entered report there is no money in the machine.
Your variable report is a fixed string. This line:
report=f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {resources['money']}$"
is executed exactly once and will set report to the string with the values at the time of the execution. What you want instead is a function that, when called, will build the string based on the current resuorces.
def report(resources):
return f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {resources['money']}$"
Unrelated to your question, but I cannot leave this unmentioned: All your functions should use the data from the dictionary you define at the beginning. For isntance, your check function should look like below and not have any specific numbers in them:
def check(drink):
for ingredient, required_amount in menu[drink]["ingredients"].items():
if resources[ingredient] < required_amount:
return f"Sorry, there is not enough {ingredient}"
return "enough"
This will allow the function to work with new or changed coffee variations without being altered, whereas in your current code, every change has to be done at multiple places.
Last comment: Does your machine accept coins that are broken in half or why are you converting to float as opposed to int?
I see that there has been a answer to your question while I was testing out your code and doing some refactoring. Some of the bits I noticed were that some of the tests did not seem to provide the correct answers. Also, it seemed like there was a bit of repeated instructions happening for the various selections that could be streamlined. With that in mind, I offer up another possible route for your code with the following refactored version.
import os
menu = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee_l": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money":0
}
def check(drink):
response = "Enough"
if drink == 'espresso':
if resources['water'] <= 50:
response = "​Sorry there is not enough water."
elif resources['coffee'] <= 18:
response = "​Sorry there is not enough coffee."
elif drink ==' latte':
if resources['water'] < 50:
response = "​Sorry there is not enough water."
elif resources['coffee'] < 18:
response = "​Sorry there is not enough coffee."
elif resources['milk'] < 150:
response = "​Sorry there is not enough milk."
elif drink == 'cappuccino':
if resources['water'] < 250:
response = "​Sorry there is not enough water."
elif resources['coffee'] < 24:
response = "​Sorry there is not enough coffee."
elif resources['milk'] < 100:
response = "​Sorry there is not enough milk."
return response
def money():
quarter = 0.25
dime = 0.1
nickel = 0.05
pennie = 0.01
qu = float(input("Inset quarters: "))
di = float(input("Insert dimes: "))
ni = float(input("Insert nickels: "))
pen = float(input("Insert pennies: "))
total_paid = qu * quarter + di * dime + ni * nickel + pen * pennie
return total_paid
def make_drink(drink): # Added this function to consume the resources for the type of drink ordered
if drink == "espresso":
resources['water'] -= 50
resources['coffee'] -= 18
elif drink == "latte":
resources['water'] -= 50
resources['coffee'] -= 18
resources['milk'] -= 150
elif drink == "cappuccino":
resources['water'] -= 250
resources['coffee'] -= 18
resources['milk'] -= 100
else:
print("Not sure what drink was made")
return
def replenish():
resources['water'] = 300
resources['milk'] = 200
resources['coffee'] = 100
return
while True:
print("Welcome to the coffee machine.")
m = "Espresso = $1.50\nLatte = $2.50\nCappuccino = $3.00\n"
selection = ""
print(m)
choice=input("​What would you like? (espresso/latte/cappuccino)(e/l/c): ")
# Store the choice in a selection variable to streamline the choice function call
if choice == 'e':
selection = 'espresso'
elif choice == 'l':
selection = 'latte'
elif choice == 'c':
selection = 'cappuccino'
elif choice == 'report':
print("Water:" + str(resources['water']) + "\nMilk:" + str(resources['milk']) + "\nCoffee:" + str(resources['coffee']) + "\nMoney: $" + str(resources['money']))
elif choice == 'replenish':
replenish() # Add a function to replenish resources
elif choice == 'off':
break
if choice in ['c', 'e', 'l']:
chk = check(selection)
print(chk)
if chk == "Enough":
mo=money()
if mo == menu[selection]['cost']:
make_drink(selection)
print('Here is your ', selection)
elif mo > menu[selection]['cost']:
make_drink(selection)
print(f'Here is your ', selection, ', and here is your change $', "{0:.2f}".format(round(mo-menu[selection]["cost"], 2)))
mo = menu[selection]['cost']
elif mo < menu[selection]['cost']:
print(f'​Sorry that\'s not enough money. Money refunded.')
mo = 0
resources['money']=mo+resources['money']
print("Money in machine is: $", "{0:.2f}".format(resources['money']))
selection = ""
Forgive me for this being a bit verbose, but following are some of the highlights of this refactored code.
Instead of repeating a lot of the same resource checks and monetary adjustments, an additional variable called "selection" was added to be used for function calls and as an index subscript, which allowed for the streamlining of testing and function calls.
Some of the tests for monetary amounts needed follow up adjustment of the actual money being added to the machine so that the correct money was added, or not added.
Instead of keeping a separate report variable, the contents and functionality of the report value is just embedded within the printing of the report when requested.
In testing the program, I noticed that there was actually no consumption of resources occurring (just testing), so a function was added to consume the resources for the appropriate drink selection.
And just to round out the process, a replenishment option and function was added when resources begin to run out.
Following is some testing output at the terminal when running this program.
#Vera:~/Python_Programs/Coffee$ python3 Coffee.py
Welcome to the coffee machine.
Espresso = $1.50
Latte = $2.50
Cappuccino = $3.00
What would you like? (espresso/latte/cappuccino)(e/l/c): c
Enough
Inset quarters: 12
Insert dimes: 4
Insert nickels: 0
Insert pennies: 0
Here is your cappuccino , and here is your change $ 0.40
Money in machine is: $ 3.00
Welcome to the coffee machine.
Espresso = $1.50
Latte = $2.50
Cappuccino = $3.00
What would you like? (espresso/latte/cappuccino)(e/l/c): report
Water:50
Milk:100
Coffee:82
Money: $3.0
Money in machine is: $ 3.00
Welcome to the coffee machine.
Espresso = $1.50
Latte = $2.50
Cappuccino = $3.00
What would you like? (espresso/latte/cappuccino)(e/l/c):
No doubt, there could be some more polishing of the code, but I believe this heads you in the direction you want to go.
Anyway, give this code a tryout if you desire and see if it helps answer some of your questions and meets the spirit of your project.

The stay in blackjack python code doesnt work

There isnt a error in the code but when I run the code it doesn't do it the way I want it to
elif player == '-blackjack':
betted = int(input('how much would you like to gamble? : '))
your_card = random.randrange(2,21)
your_drawed = random.randrange(1,12)
opponent_card = random.randrange(2,21)
opponent_drawed = random.randrange(1,12)
if betted > player_money:
print('oye you dont have this much')
pass
elif betted <= player_money:
game = True
while game:
opponent_drawed = random.randrange(1,12)
your_drawed = random.randrange(1,12)
print(' ________________________________')
print('|Your total card : ' + str(your_card))
print('|Opponents total card : ?')
print('|h to hit, s to stay.')
player = input('|________________________________')
if opponent_card < 15:
opponent_card += opponent_drawed
elif opponent_card >= 15:
pass
if player == 'h':
your_card = your_card + your_drawed
if your_card > 21:
if opponent_card > 21:
print('BOTH BUSTED! tie')
game = False
elif opponent_card <= 21:
print('BUSTED! You lost ' + str(betted))
player_money -= betted
game = False
elif your_card == 21:
if opponent_card == 21:
print('Both 21! Tie')
game = False
elif opponent_card < 21 or opponent_card > 21:
print('You win! you won ' + str(betted))
player_money += betted
game = False
elif opponent_card > 21:
if your_card > 21:
print('man opponent busted tho, you should have stayed TIE!')
game = False
elif your_card <= 21:
print('opponent busted! you won ' + str(betted))
player_money += betted
game = False
elif player == 's':
if opponent_card == 21:
if your_card == 21:
print('both 21! tie!')
game = False
elif your_card < 21:
print('opponent reached 21 in this turn you lose ' + str(betted))
player_money -= betted
game = False
elif opponent_card > 21:
print('opponent busted you win ' + str(betted))
player_money += betted
game = False
When I run this code, the hit for blackjack works but the 's' button stay doesn't work
this happens when I try to stay, why does it do this? When I do hit it does successfully go up and everything works fine but just the stay part doesn't seem to be working
You need another conditional for the case where opponent_card < 21.

I am trying to write a grade calculator with functions in Python

I am new to python and trying to make a grade calculator with functions. I want to check the users input so that when they put a number in it will check and see if it is between 1 and 100, but don't know how to do that. can anyone help? I also want to make it at the end so that it says for 'subject' and a score of 'number' you get a 'grade'.
here is what i have so far:
class_list = ['math', 'art', 'P.E.', 'science', 'english']
my_dict = {}
for idx,subject in enumerate(class_list):
print ("What is your score for ", class_list[idx])
my_dict[subject] = int(raw_input())
print my_dict
def assign_letter_grade(grade):
if 93 <= grade <= 100:
return 'A'
elif 90 <= grade < 93:
return 'A-'
elif 87 <= grade < 90:
return 'B+'
elif 83 <= grade < 87:
return 'B'
elif 80 <= grade < 83:
return 'B-'
elif 77 <= grade < 80:
return 'C+'
elif 73 <= grade < 77:
return 'C'
elif 70 <= grade < 73:
return 'C-'
elif 67 <= grade < 70:
return 'D+'
elif 63 <= grade < 67:
return 'D'
elif 60<= grade < 63:
return 'D-'
else:
return 'F'
Try it:
def raw_input():
while True:
score = input()
if score in [str(i) for i in range(101)]:
return score
class_list = ['math', 'art', 'P.E.', 'science', 'english']
my_dict = {}
for idx,subject in enumerate(class_list):
print ("What is your score for ", class_list[idx])
my_dict[subject] = assign_letter_grade(int(raw_input()))
print( my_dict)
def assign_letter_grade(grade):
if 93 <= grade <= 100:
return 'A'
elif 90 <= grade < 93:
return 'A-'
elif 87 <= grade < 90:
return 'B+'
elif 83 <= grade < 87:
return 'B'
elif 80 <= grade < 83:
return 'B-'
elif 77 <= grade < 80:
return 'C+'
elif 73 <= grade < 77:
return 'C'
elif 70 <= grade < 73:
return 'C-'
elif 67 <= grade < 70:
return 'D+'
elif 63 <= grade < 67:
return 'D'
elif 60<= grade < 63:
return 'D-'
else:
return 'F'
You can use the try and except functions.
For example:
data_valid = False
score = input("What is your score?")
while data_valid == False:
score = input("Enter your score: ")
try:
score = float(score)
except:
print("Invalid input. Please type an decimal or integer.")
continue
if score < 0 or score > 100:
print("Invalid input. Score should be between 0 and 100.")
continue
else:
data_valid = True

Function with branch

Define function print_popcorn_time() with parameter bag_ounces. If bag_ounces is less than 3, print "Too small". If greater than 10, print "Too large". Otherwise, compute and print 6 * bag_ounces followed by "seconds". End with a newline. Example output for bag_ounces = 7:
42 seconds.
For this program I'm getting suck on an error:
"File "main.py", line 6
elif bag_ounces = bag_ounces * 6"
^
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print("Too small")
elif bag_ounces > 10:
print("Tool large")
elif bag_ounces = bag_ounces * 6
else:
print(bag_ounces)
print_popcorn_time(7)
Your last condition should just be else
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print("Too small")
elif bag_ounces > 10:
print("Tool large")
else:
print('{} seconds'.format(bag_ounces * 6))
Here is the proper code. Tested in ZyBooks. The "else" print statement needed to be reformatted. Cheers.
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print('Too small')
elif bag_ounces > 10:
print('Too large')
else:
print((bag_ounces * 6), 'seconds')
print_popcorn_time(7)
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print('Too small')
elif bag_ounces > 10:
print('Too large')
else:
print(f'{bag_ounces * 6} seconds')
user_ounces = int(input())
print_popcorn_time(user_ounces)
def print_popcorn_time(bag_ounces):
if bag_ounces < 3:
print("Too small")
return
if bag_ounces > 10:
print("Too large")
return
else:
print(str(6 * bag_ounces)+ " seconds")
user_ounces = int(input())
print_popcorn_time(user_ounces)

How to create a grading system in Python?

I have an assignment for school and one of the tasks is to display the grades that the students will be receiving. The grades are:
A: 90% +
B: 80% - 89%
C: 70% - 79%
D: 60% - 69%
E: 50% - 59%
Here is some of the file, it's a comma-separated CSV file:
StudentName Score
Harrison 64
Jake 68
Jake 61
Hayley 86
I would like to know/get some guidance so I have a better understanding how to create the grade calculator.
I have spent ages trying to work it out but have had no hope.
My code:
def determine_grade(scores):
if scores >= 90 and <= 100:
return 'A'
elif scores >= 80 and <= 89:
return 'B'
elif scores >= 70 and <= 79:
return 'C'
elif scores >= 60 and <= 69:
return 'D'
elif scores >= 50 and <= 59:
return 'E'
else:
return 'F'
You can use bisect from Python's standard library for this purpose.
import bisect
def determine_grade(scores, breakpoints=[50, 60, 70, 80, 90], grades='FEDCBA'):
i = bisect.bisect(breakpoints, scores)
return grades[i]
You can use pandas and numpy to do it. Similar to this:
import pandas as pd
import numpy as np
#Create a DataFrame
d = { # Creating a dict for dataframe
'StudentName':['Harrison','Jake','Jake','Hayley'],
'Score':[64,68,61,86]}
df = pd.DataFrame(d) # converting dict to dataframe
# Keys get converted to column names and values to column values
#get grade by adding a column to the dataframe and apply np.where(), similar to a nested if
df['Grade'] = np.where((df.Score < 60 ),
'F', np.where((df.Score >= 60) & (df.Score <= 69),
'D', np.where((df.Score >= 70) & (df.Score <= 79),
'C', np.where((df.Score >= 80) & (df.Score <= 89),
'B', np.where((df.Score >= 90) & (df.Score <= 100),
'A', 'No Marks')))))
print(df)
result:
StudentName Score Grade
0 Harrison 64 D
1 Jake 68 D
2 Jake 61 D
3 Hayley 86 B
try this:
def determine_grade(scores):
if scores >= 90 and scores <= 100:
return 'A'
elif scores >= 80 and scores <= 89:
return 'B'
elif scores >= 70 and scores <= 79:
return 'C'
elif scores >= 60 and scores <= 69:
return 'D'
elif scores >= 50 and scores <= 59:
return 'E'
else:
return 'F'
in every if u have to compare scores with values this is why if scores >= 90 and <= 100: is incorrect, but after short editing it works
For scores >= 90 and <= 100 you can write 90 <= scores <= 100
i don't know, if the score is a float or integer number. If the score is a float, your comparison isn't enough.
if scores >= 90 and <= 100:
return 'A'
elif scores >= 80 and <= 89:
return 'B'
What happen if the score is 89.99?
This is my solution. There are a GRADES_PATTERN. So you must not change your function, if something is changed.
GRADES_PATTERN = {'A':[90, float('inf')], 'B':[80, 90], 'C':[70, 80], 'D':[60, 70], 'E':[50, 60], 'F':[0, 50]}
def check_grade(score, pattern):
for grade, score_range in pattern.iteritems():
if score_range[0] <= score < score_range[1]:
return grade
raise Exception("score is out of pattern range")
print check_grade(89.99, GRADES_PATTERN)
students = {'Harrison':64, 'Jake': 68, 'Hayley':86}
for name, score in students.iteritems():
print("Student {} hat score {} and grade {}".format(name, score, check_grade(score, GRADES_PATTERN)))
Another option...
If you didn't want an integer, you could change this for a float.
grade = int(input("What was your score?"))
if grade >=90 and grade <=100:
print("A*")
elif grade >=80 and grade <=89:
print("A")
elif grade >=70 and grade <=79:
print("B")
else:
print("Unknown grade")
You may just do this, noting the order of the if comparison.
def determine_grade(scores):
if scores >= 90:
return 'A'
elif scores >= 80:
return 'B'
elif scores >= 70:
return 'C'
elif scores >= 60:
return 'D'
elif scores >= 50:
return 'E'
else:
return 'F'
# Score Grade
# if > 1.0 error Bad score
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# ss (string score)
ss = input ("Enter your score: ")
# fs (float score)
try:
fs = float (ss)
except:
print("Error Bad score")
quit()
#print(fs)
if fs >= 1.0:
print("Error Bad Score")
if fs >= 0.9 :
print ("A")
elif fs >= 0.8 :
print ("B")
elif fs >= 0.7 :
print ("C")
elif fs >= 0.6 :
print ("D")
else:
print ("F")
I try to solve it referenced by this great site: https://www.py4e.com/html3/03-conditional
You could use this for the grading system but it doesn't put it into a nice array. Instead, it gives you a percentage and a grade letter.
def main():
a = input("Enter amount of questions... ")
b = input("Enter amount of questions correct... ")
def calc(a, b):
c = 100 / a
d = c * b
return d
r = calc(int(a), int(b))
print(f"Result: {int(r)}%")
if int(r) < 80:
print("Result is not passing, test will require Parent Signature.")
t = 0
if int(r) > 79:
print("The test has passed!")
if int(r) == 100 or int(r) > 92:
print('Grade Letter: A')
t += 1
if int(r) > 91:
if t != 0:
return
print('Grade Letter: A-')
t += 1
if int(r) > 90:
if t != 0:
return false
print('Grade Letter: B+')
t += 1
if int(r) > 87:
if t != 0:
return false
print('Grade Letter: B')
t += 1
if int(r) > 83:
if t != 0:
return false
print('Grade Letter: B-')
t += 1
if int(r) > 80:
if t != 0:
return false
print('Grade Letter: C+')
t += 1
if int(r) > 77:
if t != 0:
return false
print('Grade Letter: C')
t += 1
if int(r) > 73:
if t != 0:
return false
print('Grade Letter: C-')
t += 1
if int(r) > 70:
if t != 0:
return false
print('Grade Letter: D+')
t += 1
if int(r) > 67:
if t != 0:
return false
print('Grade Letter: D')
t += 1
if int(r) > 63:
if t != 0:
return false
print('Grade Letter: D-')
if int(r) > 60:
if t != 0:
return false
print('Grade Letter: F')
t += 1
else:
if t != 0:
return false
print('Grade Letter: F')
t += 1
main()
def determine_grade(scores):
if scores >= 0 and <= 39:
return 'U'
elif scores >= 40 and <= 49:
return 'D'
elif scores >= 50 and <= 59:
return 'C'
elif scores >= 60 and <= 69:
return 'B'
elif scores >= 70 and <= 79:
return 'A'
else:
return 'No Marks'

Categories