Having errors when running a program for counting ice skating scores
the errors are as followed when running in python 3.7.0
Errors when loading in python 3.7.0
. Any help appreciated thank you
Here is the task I was given and I am required to use def and sub procedures:
Program 1
A program is to be written to process scores by competitors in an
ice-skating competition. Each skater receives a score in the range
0.0-6.0 from each of the 6 judges. A skater’s overall score is calculated from the total of the 6 scores minus the best and the worst
scores.
Create a modular program which makes use of parameter passing to
implement the specification above.
def get_scores(score,totalscore,checknumber):
loops = 0
for loops in range(0,6):
checknumber = validatescore(checknumber)
score[loops]=float(checknumber)
maxi = find_max(score)
mini = find_min(score)
totalscore = totalscore + calculate_score(score,totalscore,maxi,mini)
return score[loops],totalscore,checknumber
def find_min(score):
min = 100
for counter in range (0,len(score)):
if score[counter] < min:
mini = score[counter]
return mini
def find_max(score):
max = 100
for counter in range (0,6):
if score[counter] < max:
maxi = score[counter]
return maxi
def calculate_score(score,totalscore,maxi,mini):
for loops in range(0,6):
totalscore = totalscore + score[loops]
totalscore = totalscore - maxi - mini
return totalscore,maxi,mini
def displaydetails (totalscore,maxi,mini):
print("The competitor scored: ",totalscore, "The max was :",maxi," The min was :",mini)
def validatescore(checknumber):
valid = False
checknumber = 0
print("Please enter the score of the competitor")
checknumber = float(input())
while valid == False:
if checknumber < 0.0 or checknumber > 6.0:
print("Invalid mark - please enter a whole number between 0.0 and 6.0")
checknumber = float(input())
else:
valid = True
return checknumber
totalscore = 0.0
score = [0.0] * 6
checknumber = 0.0
score,totalscore,checknumber = get_scores(score,totalscore,checknumber)
displaydetails(totalscore,maxi,mini)
Related
The program determines who has the highest score at the end, but I am trying to incorporate a function to print who has the highest grade as the scores are being input?
#Creating function for student names and weights:
def overall_grade(student):
# inputs for each category:
dis_grade = float(input(f"{student}'s discussion score:"))
quiz_grade = float(input(f"{student}'s quiz score:"))
assign_grade = float(input(f"{student}'s assignment score:"))
#weights for each category of discussion(d), quiz(q), and assignment(a):
d_wt = 0.25
q_wt = 0.35
a_wt = 0.40
#returning average with weights incorporated:
average = (d_wt * dis_grade) + (q_wt * quiz_grade) + (a_wt * assign_grade)
return average
#creating main function to display student with highest grade:
def main():
#The list of names for the students:
students = ["Logan", "Raymone", "Timothy", "Kim"]
#Assigning starting variable for grades:
best_grade = 0
top_student = ""
#setting range to the scores for each student to give total score:
for x in range(len(students)):
total = overall_grade(students[x])
print(f"{students[x]} total score: {total:.2f}")
#I assume this is where the "if" statement starts for the checks
if x == 0 or best_grade < total:
best_grade = total
top_student = students[x]
print(f"Student with the best grade is {top_student} with a total percentage of: {best_grade:.2f}%" )
main()
#This part asks for the user input
annual_salary = float(input("Enter your annual salary:"))
#Declaring all the variables
total_cost = 1000000
High = 1.0
Low = 0.0
portion_saved = (High +Low)/2.0
semi_annual_raise = 0.07
r = 0.04 #annual investment return
portion_down_payment = 0.25
num_guesses = 0
epsilon = 100
total_saving = 0.0
months = 0
#Calculations next
while abs(total_cost - total_saving) >= epsilon:
num_guesses += 1
total_saving = 0.0
while total_saving < (total_cost*portion_down_payment):
monthly_salary = annual_salary/12
monthly_saving = monthly_salary*portion_saved
total_saving += (monthly_saving + total_saving*r/12)
months += 1
if months%6 == 0:
annual_salary += annual_salary*semi_annual_raise
if (total_saving < total_cost):
Low = portion_saved
else:
High = portion_saved
portion_saved = (Low+High)/2.0
print("Best savings rate:", portion_saved)
print("Number of steps:", num_guesses)
But the code enters an infinite loop. When checked using a print command, it turns out that the 'portion_saved' variable takes the value 1.0 on each iteration. But I can't figure out why is this happening. Can someone help?
your code always goes into the if statement, so you are always setting Low to be portion_saved:
1: Low = 0, portion_saved= 1/2
2: Low = 1/2, portion_saved= 1.5/2
3: Low = .75, portion_saved= 1.75/2
4: Low = .875, portion_saved= 1.875/2
5: and so on....
Well, I solved it. Had to make two corrections.
Multiplied the 'total_cost' by 'portions_down_payment' as I really had to calculate the rate to pay the downpayment.
I reset the value of annual sal for each iteration to the initial value.
The final code looks like this:
#This part asks for the user input
starting_salary = float(input("Enter your annual salary:"))
#Declaring all the variables
total_cost = 1000000
High = 1.0
Low = 0.0
portion_saved = (High +Low)/2.0
semi_annual_raise = 0.07
r = 0.04 #annual investment return
portion_down_payment = 0.25
num_guesses = 0
epsilon = 100
total_saving = 0.0
months = 36
print(portion_saved)
#Calculations next
while abs(total_cost*portion_down_payment - total_saving) >= epsilon:
num_guesses += 1
total_saving = 0.0
annual_salary = starting_salary
for i in range (months):
monthly_salary = annual_salary/12
monthly_saving = monthly_salary*portion_saved
total_saving += (monthly_saving + total_saving*r/12)
if i%6 == 0:
annual_salary += annual_salary*semi_annual_raise
if (total_saving > total_cost*portion_down_payment):
High = portion_saved
else:
Low = portion_saved
portion_saved = (Low+High)/2.0
print("Best savings rate:", portion_saved)
print("Number of steps:", num_guesses)
I'm learning to program with python and I came across this issue: I'm trying to make a Guessing Game, and while trying to check for the win condition, the function doesn't recognise the input variable, which I made sure I returned with a previous function. So i get the 'name << 'first_input' is not defined' >> error. I thought it had something to do with the variable not being global or sth like that.
import random
ran_int = random.randint(1,100)
guesses = 0
# here you input the number and it keeps asking unless you do so with 1 to 100
def ask():
first_input = 0
while first_input < 1 or first_input > 100:
first_input = int(input('Enter a number between 1 and 100: '))
return first_input
# this is just to increment the number of guesses stored for showing at the end # of the game
def guesses_inc():
global guesses
guesses += 1
return guesses
# here is where i get the error, as if my ask() function didn't return
# the value properly or as if I assigned it wrongly
def check_win_1():
if first_input == ran_int:
guesses_inc()
print(f'BINGO!\nYou guessed correctly after {guesses} times.')
elif (abs(ran_int - first_input) <= 10):
guesses_inc()
print('WARM!')
ask2()
elif first_input < 1 or first_input > 100:
print('Out of bounds!')
ask2()
else:
guesses_inc()
print('COLD!')
ask2()
ask()
check_win_1()
And here is the error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-bfd5497995df> in <module>
----> 1 check_win_1()
NameError: name 'first_input' is not defined
I didn't paste the whole code because while testing it it returned the error at this stage so I didn't think the rest mattered for this particular problem. I tried making the var input global and stuff like that but i don't think I did it properly.
Your method call is not correct. You should call your functions like this
def check_win_1(first_input):
if first_input == ran_int:
guesses_inc()
print(f'BINGO!\nYou guessed correctly after {guesses} times.')
elif (abs(ran_int - first_input) <= 10):
guesses_inc()
print('WARM!')
ask2()
elif first_input < 1 or first_input > 100:
print('Out of bounds!')
ask2()
else:
guesses_inc()
print('COLD!')
ask2()
first_input = ask()
check_win_1(first_input)
The error is there because you are trying to use first_input somewhere (i.e. inside check_win_1()).
A possible, not recommended, solution is to qualify your variable as global, which should be used VERY sparingly.
Instead, it is recommended to use function parameters, so as to encapsulate your code in self-contained blocks, e.g.:
def func(a, b):
return a + b
x = func(10, 5)
rather than:
def func():
global a, b
return a + b
a = 10
b = 5
x = func()
For your that may mean doing something like:
def check_win_1(first_input, ran_int):
...
and use them accordingly, e.g.:
first_input = ask()
check_win_1(first_input, ran_int)
etc.
EDIT
Following the above principle, your code could have looked like:
import random
MIN_VAL = 1
MAX_VAL = 100
WARM_LIMIT = 10
def ask_number(
min_val=MIN_VAL,
max_val=MAX_VAL):
guess = None
while guess is None:
guess = int(input(f'Enter a number between {min_val} and {max_val}: '))
if guess < min_val or guess > max_val:
print('Out of bounds!')
guess = None
return guess
def check_guess(
guess,
target,
num_guesses,
warm_limit=WARM_LIMIT):
if guess == target:
print(f'BINGO!\nYou guessed correctly after {num_guesses} times.')
return True
else:
if (abs(guess - target) <= warm_limit):
print('WARM!')
else:
print('COLD!')
return False
# : main
target = random.randint(MIN_VAL, MAX_VAL)
num_guesses = 0
won = False
while not won:
guess = ask_number()
num_guesses += 1
won = check_guess(guess, target, num_guesses)
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()
I just started to learn python(self-taught) and I'm trying to do a simulation of racquetball game.
I can run the simulation with: a==15 or b==15, but when I add the extra condition: abs(a-b)>=2 IT GOES CRAZY(the simOneGame turns to an infinite loop). Here is what I tried so far:
return a == 15 or b == 15 ------> this one works perfectly
return a == 15 or b == 15 and abs(a-b) >= 2 --> this doesn't freeze but the logic is wrong(I think)
return (a == 15 or b == 15) and abs(a-b) >= 2 --> freezing
return (a == 15 or b == 15) and (abs(a-b) >= 2) --> freezing
return ((a == 15 or b == 15) and (abs(a-b) >= 2)) --> freezing
Thanks a lot and sorry if this seems too long(maybe I should've typed just the function gameOver()?...)
Here is my code so far:
from random import random
def main():
printIntro()
n, probA, probB = getInputs()
winsA, winsB = simNGames(n, probA, probB)
displayResults(winsA, winsB)
def printIntro():
print("\nVOLLEYBALL SIMULATION\n")
print("The inputs will be the number of simulations(n),")
print(" the probability player A wins his serve(probA)")
print(" and the probability player B wins his serve(probB).")
print("The program will display how many games won player A(winsA),")
print(" how many games won player B(winsB),")
print(" and the percentages of winnings for both players.\n")
def getInputs():
n = int(input("Enter the number of simulations: "))
probA = float(input("Enter the probability player A wins his serve: "))
probB = float(input("Enter the probability player B wins his serve: "))
return n, probA, probB
def simNGames(n, probA, probB):
winsA, winsB = 0, 0
for i in range(n):
# player A serves on odd games
if i % 2 == 0:
serving = "A"
# player B serves on even games
else:
serving = "B"
scoreA, scoreB = simOneGame(probA, probB, serving)
if scoreA > scoreB:
winsA = winsA + 1
else:
winsB = winsB + 1
return winsA, winsB
def simOneGame(probA, probB, serving):
scoreA, scoreB = 0, 0
while not gameOver(scoreA, scoreB):
if serving == "A":
if random() < probA:
scoreA = scoreA + 1
else:
serving = "B"
else:
if random() < probB:
scoreB = scoreB + 1
else:
serving = "A"
return scoreA, scoreB
def gameOver(a, b):
# the game is over if a player gets to 15 AND the difference is at least 2.
# this shoud work... BUT IT DOESN'T... simOneGame turns to an infinete loop with a large number of simulations...
return (a == 15 or b == 15) and abs(a-b) >= 2
def displayResults(winsA, winsB):
print("Player A won {0} games({1:1.0%})".format(winsA, winsA/(winsA+winsB)))
print("Player B won {0} games({1:0.0%})".format(winsB, winsB/(winsA+winsB)))
if __name__ == "__main__":
main()