this is a GPA calculator code in my textbook. I'd like to ask about a few this I don't understand here.
# Semester GPA Calculation
def convertGrade(grade):
if grade == 'A+':
return 4
if grade == 'A':
return 3.7
if grade == 'A-':
return 3.3
if grade == 'B+':
return 3.0
if grade == 'B':
return 2.7
if grade == 'B-':
return 2.3
if grade == 'C+':
return 2.0
if grade == 'C':
return 1.7
if grade == 'C-':
return 1.3
if grade == 'D+':
return 1.0
if grade == 'D':
return 0.7
if grade == 'D-':
return 0.3
else:
return 0
def getGrades():
semester_info = []
more_grades = True
empty_str = ''
while more_grades:
course_grade = input('Enter grade (hit Enter if done): ')
while course_grade not in ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'E+', 'E', 'E-', 'F', empty_str]:
course_grade = input('Enter letter grade you received: ')
if course_grade == empty_str:
more_grades = False
else:
num_credits = int(input('Enter number of credits: '))
semester_info.append([num_credits, course_grade])
return semester_info
def calculateGPA(sem_grades_info, cumm_gpa_info):
sem_quality_pts = 0
sem_credits = 0
current_cumm_gpa, total_credits = cumm_gpa_info
for k in range(len(sem_grades_info)):
num_credits, letter_grade = sem_grades_info[k]
sem_quality_pts = sem_quality_pts + \
num_credits * convertGrade(letter_grade)
sem_credits = sem_credits + num_credits
sem_gpa = sem_quality_pts / sem_credits
new_cumm_gpa = (current_cumm_gpa * total_credits + sem_gpa * \
sem_credits) / (total_credits + sem_credits)
return (sem_gpa, new_cumm_gpa)
# ---- main
# program greeting
print('This program calculates new semester and cumulative GPAs\n')
# get current GPA info
total_credits = int(input('Enter total number of earned credits: '))
cumm_gpa = float(input('Enter your current cummulative GPA: '))
cumm_gpa_info = (cumm_gpa, total_credits)
# get current semester grade info
print()
semester_grades = getGrades()
# calculate semester gpa and new cumulative gpa
semester_gpa, cumm_gpa = calculateGPA(semester_grades, cumm_gpa_info)
#display semester gpa and new cummulative gpa
print('\nYour semester GPA is', format(semester_gpa, '.2f'))
print('Your new cummulative GPA is', format(cumm_gpa, '.2f'))
What does current_cumm_gpa, total_credits = cumm_gpa_info mean below? Does it create a new array? I tried simpler but it doesn't work.
def calculateGPA(sem_grades_info, cumm_gpa_info):
sem_quality_pts = 0
sem_credits = 0
current_cumm_gpa, total_credits = cumm_gpa_info
From this line:
cumm_gpa_info = (cumm_gpa, total_credits)
We can see that cumm_gpa_info is a tuple of two values. Then current_cumm_gpa, total_credits = cumm_gpa_info unpacks the values in the tuple to two variables, the first to current_cumm_gpa and the second to total_credits. It's a simpler way of doing:
current_cumm_gpa = cumm_gpa_info[0]
total_credits = cumm_gpa_info[1]
From the docs:
This is called, appropriately enough, sequence unpacking and works for
any sequence on the right-hand side. Sequence unpacking requires that
there are as many variables on the left side of the equals sign as
there are elements in the sequence. Note that multiple assignment is
really just a combination of tuple packing and sequence unpacking.
Tracing your program we see the following :
>>> total_credits = int(input('Enter total number of earned credits: '))
#3.2
>>> cumm_gpa = float(input('Enter your current cummulative GPA: '))
#4.6
>>> cumm_gpa_info = (cumm_gpa, total_credits)
>>> cumm_gpa_info
(3.2 , 4.6)
>>> type(cumm_gpa_info)
Tuple
So we see that cumm_gpa_info is a Tuple. Now this is passed to the function.
>>> ... = calculateGPA(semester_grades, cumm_gpa_info)
#inside function
>>> current_cumm_gpa, total_credits = cumm_gpa_info
#current_cumm_gpa, total_credits = (3.2 , 4.6)
>>> current_cumm_gpa
3.2
>>> total_credits
4.6
So as we can see, the values were unpacked from the tuple and assigned to current_cumm_gpa & total_credits respectively.
It is similar to doing :
>>> current_cumm_gpa = cumm_gpa_info[0]
>>> total_credits = cumm_gpa_info[1]
Note : sorry if its not exactly how it would look on a console. Can't get to my PC, writing it out on my mobile right now. So have put it approximately how it would look.
Related
I am creating a slot machine using python and i don't have any idea how to print the slot machine but i want to print the slot machine from spin_slot_machine(symbols) there i have nine letters from symbol_count who were randomly chosen. For example if this is output from parameter columns of spin_slot_machine(symbols)-->['A', 'B', 'E', 'A', 'C', 'B', 'C', 'F', 'B'] i want to make like that like this ex:
import random
MAX_VALUE = 100
MIN_VALUE = 1
ROWS = 3
COLUMNS = 3
symbols_count = {
"A":2,
"B":4,
"C":3,
"E":3,
"F":2
}
def spin_slot_machine(symbols):
all_symbols = []
columns = []
length_of_spin = 9
for symbol,symbol_count in symbols.items():
for i in range(symbol_count):
all_symbols.append(symbol)
for i in range(length_of_spin):
get_random = random.choice(all_symbols)
columns.append(get_random)
return columns
def print_slot_machine(columns):
pass
def deposit():
while True:
deposit_money = input("How much money would you like to deposit?: $")
if deposit_money.isdigit():
deposit_money = int(deposit_money)
if deposit_money > 0:
break
else:
print("You should deposit more than 0$")
print("Enter a digit")
return deposit_money
def bet_on_lines():
while True:
lines = input("On how many lines would you like to bet(1-3)?: ")
if lines.isdigit():
lines = int(lines)
if lines >= 1 and lines <= 3:
break
else:
print("Number of lines should be between 1-3")
print("Enter a number of lines")
return lines
def get_bet():
while True:
bet = input("How much money would you like to bet(1$-100$): ")
if bet.isdigit():
bet = int(bet)
if bet <= MAX_VALUE and bet >= MIN_VALUE:
break
else:
print("Money should be between 1-100$")
else:
print("Enter a digit")
return bet
def main():
balance = deposit()
lines_number = bet_on_lines()
while True:
bet_money = get_bet()
total_bet = bet_money * lines_number
if total_bet > balance:
print(f"Your balance is {balance}$.Balance shoudn't be less than betting money , bet less!")
else:
break
print(f"You are betting {total_bet}$ on {lines_number} lines.")
slot_machine = spin_slot_machine(symbols_count)
print_slot_machine(slot_machine)
main()
If you just need to print them you can use something like this:
symbols = ['A', 'B', 'E', 'A', 'C', 'B', 'C', 'F', 'B']
print(' | '.join(symbols[0:3]))
print(' | '.join(symbols[3:6]))
print(' | '.join(symbols[6:9]))
It will give you what you wanted
def find_gpa(sem=1):
sub = int(input("Enter the no of subjects: "))
credits = []
grade = []
temp = []
for i in range(0,sub):
a=i+1
x = int(input("Enter the credits for subject {}".format(a)))
credits.append(x)
grade = input("Enter the Grade for subject {}".format(a))
y = gpa_convert(grade)
print(type(y))
grade.append(y)
temp.append(x*y)
gpa = sum(temp)/sum(credits)
tup = (gpa,sum(credits))
print ("The Gpa of semester {} is: {}".format(sem,gpa))
return tup
def gpa_convert(z):
if z.lower() == 'o':
return 10
elif z.lower() == 'a+':
return 9
elif z.lower() == 'a':
return 8
elif z.lower() == 'b+':
return 7
elif z.lower() == 'b':
return 6
else :
return 0
AttributeError:
'str' object has no attribute 'append'
I'm trying to append an integer in grade but its showing string
can you help me in rectifying the error?
You start with
grade = []
but in your loop you have :
grade = input("Enter the Grade for subject {}".format(a))
your list doesn't exist anymore, grade is now an int
int don't have append method, so this doesn't work :
grade.append(y)
Solution :
replace grade = [] by grades = [] and then use plural where a list is expected
def find_gpa(sem=1):
sub = int(input("Enter the no of subjects: "))
credits = []
grades = []
temp = []
for i in range(0,sub):
a=i+1
x = int(input("Enter the credits for subject {}".format(a)))
credits.append(x)
grade = input("Enter the Grade for subject {}".format(a))
y = gpa_convert(grade)
print(type(y))
grades.append(y)
temp.append(x*y)
gpa = sum(temp)/sum(credits)
tup = (gpa,sum(credits))
print ("The Gpa of semester {} is: {}".format(sem,gpa))
return tup
Please note however that you declare a list in the scope of the function, but never use it or return it ! This code can be simplified a lot
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()
Hello I am trying to run a program that will return back students grades and their average. ALSO I KNOW I AM A BASIC BRAINLESS FIRST YEAR PROGRAMMER. I WILL PROBABLY BE HORRIBLE AT PROBABLY. HOWEVER PLEASE HELP THE BEST YOU CAN IT WOULD BE GREATLY APPRECIATED.
THANK YOU.
The error says to be in line 49.
saying that"
line 49, in <module>
while ids > STOP:
TypeErrorL unorderable types: str() > int()
XXXX
def assigngrades(scores):
avg = sum(scores)/len(scores)
print(avg)
for val in scores:
if val > avg + 10:
grade = 'A'
elif val > avg + 5:
grade = 'B'
elif val > avg -5:
grade = 'C'
elif val > avg - 10:
grade = 'D'
else:
grade = 'F'
grades.append(grade)
print("in assigngrades, grades: ",grades)
return grades
def printsummary(grades, ave):
print('ID Score Average Grade')
print('===========================================')
print( )
for val in range(len(ids)):
print('val', val)
print(ids,' ',scores, ' ', grades)
return
#main
ids = []
scores = []
grades = []
STOP = 0
ids = input("Enter an ID:")
while ids > STOP:
ids.append(ids)
score = eval(input("Enter a score:"))
scores.append(score)
id = (input("Enter an ID number, 0 to STOP:"))
grades = assigngrades(scores)
print("after while loop")
print("Ids:", ids, "Scores:", scores, "Grades:", grades)
printsummary(grades, avg)
Nonetheless, I am confused on what is the issue.I appreciate your time and help looking at this. Thank you so so so much. Yes I know I am stupid.
The input() function returns a string, so you should convert it to an integer with int() so you can compare its value with another integer. You should also name the variable that stores the user input something other than ids since you already define it as a list:
ids = []
scores = []
grades = []
STOP = 0
id = int(input("Enter an ID:"))
while id > STOP:
ids.append(id)
score = eval(input("Enter a score:"))
scores.append(score)
grades = assigngrades(scores)
print("after while loop")
print("Ids:", ids, "Scores:", scores, "Grades:", grades)
printsummary(grades, avg)