So I'm able to divide the variable I asked earlier (thank you). But I guess I didn't put enough code so here's the whole thing, I'm getting errors all over the place but whatever I change to try to fix it I get the same response. And yes I am new to python and this is due in an hour.
# grade: The student's grade level Ex. 12
# first: 1st six-weeks grade Ex. 98
# second: 2nd six-weeks grade Ex. 78
# third: 3rd six-weeks grade Ex. 89
# num_exemptions: The number of exemptions that the student has already applied for this semester. Ex. 3
# absences: The number of absences that the student has accrued for the semester. Ex. 4
# tardies: The number of tardies that the student has accrued for the semester. Ex. 5
# previously_taken_exemptions: Has the student taken an exemption for the same course in the fall. Ex. True
print('Enter your 1st 6 weeks grade. Ex. 98')
first = input()
print('Enter your 2nd 6 weeks grade. Ex. 78')
second = input()
print('Enter your 3rd 6 weeks grade. Ex. 89')
third = input()
print('Enter the number of exemptions that you have already applied for this semester. Ex. 3')
num_exemptions = input()
print('Enter your grade. Ex. 12')
grade = input()
print('Enter how many absences you have had this semester. Ex. 4')
absences = input()
print('Enter how many times you have been tardy this semester. Ex. 5')
tardies = input()
print('Have you taken and exemption for this course in the fall. Ex. no')
previously_taken_exemptions = input()
real_absences = float(tardies) // 3 + float(absences)
first = int(first)
sum = float(first) + float(second) + float(third)
average = sum/3
if(average >= 81 and average <= 100):
print("Your Grade is an A")
elif(average >= 61 and average <= 80):
print("Your Grade is an B")
elif(average >= 41 and average <= 60):
print("Your Grade is an C")
elif(average >= 0 and average <= 40):
print("Your Grade is an F")
else:
print("You did something wrong, try again")
if float(grade == '11') and float(num_exemptions) <= 2 and float(real_absences) <= 3 and float(previously_taken_exemptions) == 'no' and float(average) >= 84:
print('You are eligable!')
elif float(grade == '12') and float(num_exemptions) <= 4 and float(real_absences) <= 3 and float(previously_taken_exemptions) == 'no' and float(average) >= 84:
print('You are eligable!')
elif float(grade == '9' or '10') and float(num_exemptions) <= 1 and float(real_absences) <= 3 and float(previously_taken_exemptions) == 'no' and float(average) >= 84:
print('You are eligable!')
else:
print('You are not eligable')
**
It's because it's a string, use:
real_absences = float(tardies) // 3 + float(absences)
You can turn your strings into integers using int.
you have to just declare integer.
here is an example
Tardies = int(“15”)
Absences = int(“5”)
real_absences = Tardies // 3 + Absences
Related
I'm new to python and have been trying to create a simple grade calculator which tells the user what grade they've achieved based on their final score they've inputted.
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except score not in range (0,101) or ValueError:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
However when I try to run the program, it disregards the range and value error and gives it a grade anyway. Is there any way to rectify this, and if possible how could I make the program more efficient. As I said, I'm new to python, so any feedback would be useful.
Just for fun, let's make it a Match Case statement:
Since you only accept integers, we can take and assign score to input with :=, then check if it's valid with str.isnumeric. If that's true then we'll make score an integer := and check if it's between 0 and 100.
We'll change the input statement if they don't put valid input the first time around.
def grades():
text = "Please enter your score between 0 and 100: "
while True:
if ((score := input(text)).isnumeric() and
(score := int(score)) in range(0, 101)):
break
else:
text = "Incorrect value. Please enter your score between 0 and 100: "
match score:
case x if x >= 90 : grade = 'A'
case x if x >= 80 : grade = 'B'
case x if x >= 70 : grade = 'C'
case x if x >= 60 : grade = 'D'
case x if x >= 50 : grade = 'E'
case _ : grade = 'F'
print(f'Grade: {grade}')
Please note that this will only work in Python 3.10 or greater.
Just do this:
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score > 100:
while True:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
if score <= 100:
pass
else:
break
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except:
print("Oops. sommthing went wrong")
grades();
I made some corrections to your code. I added some comments to help explain what is going on. Let me know if this solution works for you:
def grades():
while True:
# Start a loop to ask for user input:
score = int(input("Please enter your score between 0 and 100:"))
# If not in range 1, 100, print error message
if score in range(0, 101):
break
print('Incorrect value. Please enter your score between 0 and 100:')
# calculate grade:
if score >= 90:
print("Grade:A")
elif score >= 80:
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
if __name__ == '__main__':
grades()
Simply assert that the input is in the determined range before checking through score ranges. Really, there is no need for a try/except statement.
def grades():
while True:
score = int(input(...))
if 0 <= score <= 100:
break
# Invalid score
# Check score ranges
...
I have made changes to your code, please test to ensure it performs to expectations.
I have added a while True loop, which attempts to validate the score to be between 0 - 100. If a non-integer value is entered it will hit the ValueError exception. This loop will only exit when a number within the range is entered.
The if statements use interval comparators X <= score < Y. You can read more about interval comparators here.
The if statement was also removed out of the try - except to make debugging easier. The idea is to have the least code possible in try - except so that when an exception triggers, it would be caused by the intended code.
Lastly, you don't want to ask for the user input inside the exception as the user might enter something which may cause another exception which will go uncaught.
def grades():
while True:
# Perform basic input validation.
try:
# Gets the user input.
score = int(input("Please enter your score between 0 and 100: "))
# Checks if the number entered is within 0 - 100. Note that range is non-inclusive for the stop. If it is within 0 - 100 break out of the while loop.
if 0 <= score <= 100:
break
# If a non-integer is entered an exception will be thrown.
except ValueError:
print("Input entered is not a valid number")
# Checking of scores using interval comparison
if score >= 90:
print("Grade:A")
elif 80 <= score < 90:
print("Grade:B")
elif 70 <= score < 80:
print("Grade:C")
elif 60 <= score < 70:
print("Grade:D")
elif 50 <= score < 60:
print("Grade:E")
else:
print("Grade:F")
A Python(3.7) beginner here. This guessing game gives range clues:
Cold
Warm
Hot
Depending on how close to answer player is.
Problem: how to add extra 3 incremental clues:
Colder
Warmer
Hotter
Colder is used if the next guess is further from answer.
Warmer is used if the next guess is closer to answer.
Hotter is used instead of Warmer if its in the Hot range.
The first guess produces the range clues Cold, Warm or Hot.
The subsequent guesses will produce incremetal clues Colder or Warmer/Hotter if while they land in same range as previous guess.
If they fall out of the range, the range clues Cold, Warm or Hot will be produced first and then Colder or Warmer/Hotter while in that range. in other words Cold, Warm or Hot range clues have higher priority than incremental Colder or Warmer/Hotter.
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
while user_input is not 41 and count < 4:
count = count + 1
how_close_to_answer = 41 - user_input
if 5 < how_close_to_answer.__abs__() < 20:
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif how_close_to_answer.__abs__() >= 20:
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
if user_input is not 41:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
For example (in case of infinite guesses n):
player guesses = 10 , desired outcome 'Cold. Remaining guesses (n-1) '
next guess = 15 , desired outcome 'Warmer. Remaining guesses (n-2) '
next guess = 12 , desired outcome 'Colder. Remaining guesses (n-3) '
next guess = 36 , desired outcome 'Hot. Remaining guesses (n-4) '
next guess = 37 , desired outcome 'Hotter. Remaining guesses (n-5) '
next guess = 30 , desired outcome 'Warm. Remaining guesses (n-6) '
In 4. example - number 36 is Warmer than previous 12, but it also falls in the Hot range so the Hot clue is given instead.
in 6. example - number 30 is Colder than previous 37, but it also falls in the Warm range so the Warm clue is given instead.
I took num as a random generated number instead of 41.
import random
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
num = random.randint(1,101)
while user_input is not num and count < 4:
#uncomment the line below to see random generated number
#print('Generated Random Number= '+str(num))
count = count + 1
how_close_to_answer = num - user_input
if abs(how_close_to_answer)>5 and abs(how_close_to_answer) <20 :
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif abs(how_close_to_answer) >= 20 :
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
if user_input is not num:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
As far as i understood , the above program generates a random number and you need to guess that number ,
if your guessed number is less then or equivalent to 5 digits closer to that random number it will tell you hot
if its greater than 5 and less than 20 then it will tell you warm
on greater than 20 it will give you cold
Hope this will help you !!
This is the closest I could get to what you asked for. The comments on your original question are worth a read in my opinion but I think this does exactly what you asked for in the question.
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
last_distance = -1
while user_input is not 41 and count < 4:
count = count + 1
how_close_to_answer = (41 - user_input)
how_close_to_answer = how_close_to_answer.__abs__()
if how_close_to_answer <= 5 and last_distance > 5:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
elif last_distance == -1:
if 5 < how_close_to_answer < 20:
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif how_close_to_answer >= 20:
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
elif how_close_to_answer <= 5:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
else:
if how_close_to_answer < last_distance:
if how_close_to_answer <= 5:
user_input = int(input(f'Hotter. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Warmer. Remaining guesses {5 - count} '))
elif how_close_to_answer > last_distance:
user_input = int(input(f'Colder. Remaining guesses {5 - count} '))
last_distance = how_close_to_answer
if user_input is not 41:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
Hope this is what helps
I am in need of assistance on a coding question in Python.
I have to calculate a student’s GPA. The program must ask them how many classes they are taking, then ask them to enter the grades for each class and if it is weighted.
The program should then output the averaged GPA including the decimal place, and my main program must call the function.
The question gives a chart for the non-weighted and weighted number scores that correlates with the given letter grade:
gpa chart
Here's what I have so far:
def average (c):
div = c
avg =(1.0*(sum(scores))/div)
#****************MAIN********************
c = input("How many classes are you taking?")
print ("You are taking " + str(c) + " classes.")
x = input("Enter your letter grade.")
w = int(input("Is it weighted? (1 = yes)")
while (c <= 7): #Here it is saying that there is a syntax error because I input a while loop. I don't know why it is saying this.
if (x == A):
if (w == 1):
print ("Your GPA score is 5")
else:
print ("Your GPA score is 4")
elif (x == B):
if (w == 1):
print ("Your GPA score is 4")
else:
print ("Your GPA score is 3")
elif (x == C):
if (w == 1):
print ("Your GPA score is 3")
else:
print ("Your GPA score is 2")
elif (x == D):
if (w == 1):
print ("Your GPA score is 2")
else:
print ("Your GPA score is 1")
elif (x == F):
if ( w == 1):
print ("Your GPA score is 1")
else:
print ("Your GPA score is 0")
scores = []
list.append(x)
average(c)
Any help would be much appreciated! :)
Not sure about what you are asking for, but fixing just after the function definitions might be a good start
Don't
def classes(c):
print ("You are taking " + c + " classes.")
Do
def classes(c):
print ("You are taking " + c + " classes.")
Something like that maybe? I didn't divide anything in classes but I want you to understand the logic:
number_class=None
while number_class==None:# I set-it up number_class=None so it will keep asking the number of classes until you introduce an integer value
try:
number_class=input("How many classes are you taking?")
except:
print "Error, the input should be a number!\n"
total_result=0#your score start from 0
i=0
while i<number_class:# i create a loop to insert the score for each class
grade=raw_input("Enter your letter grade for the %s class." %(str(i+1)))
grade=grade.upper()#convert the grate to upper so you are able to introduce a or A without make too many check
if grade== 'A' or grade== 'B' or grade== 'C' or grade== 'D' or grade== 'F':#if you introduce a correct score we add it to the total sum and we go ahead with next class
i+=1#next iteration
if grade== 'A':
total_result+=4
elif grade== 'B':
total_result+=3
elif grade== 'C':
total_result+=2
elif grade== 'D':
total_result+=1
#elif: grade== 'F':#we can omitt F seeing that it's =0
# total_result+=0
print total_result
else:# if you introduce a wrong input for the grade we ask you again without pass to next iteration
print "Error, the grade should be: A, B, C, D or F!\n"
average="%.2f" % (float(total_result)/float(number_class))#we divided the total score for the number of classes using float to get decimal and converting on 2 decimal places
print "Your GPA is: %s" %(str(average))
Example:
How many classes are you taking?5
Enter your letter grade for the 1 class.A
4
Enter your letter grade for the 2 class.B
7
Enter your letter grade for the 3 class.C
9
Enter your letter grade for the 4 class.A
13
Enter your letter grade for the 5 class.B
16
Your GPA is: 3.20
I'm writing a python program that drops the lowest of four test scores. The program first prompts the user to enter their first four test scores, then the program should drop the lowest test score and take the average of the remaining three test scores. The program should then print the final letter grade. This is what I have so far and I keep receiving an error when dropping the lowest score.
#Enter four test scores as percentages (%)
test1 = int(input("Enter grade 1: 90"))
test2 = int(input("Enter grade 2: 80"))
test3 = int(input("Enter grade 2: 70)")
test4 = int(input("Enter grade 2: 80)")
#Drop lowest test score
print("The average, with the lowest score dropped" )
total =(test1 + test2 + test3)
#Calculate average
def calc_average(total):
return total /3
#Grade scale
def determine_score(grade):
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >=70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
#Calculate final letter grade
print("The final grade is")
main()
I tried to write a program with the things that I understood from you.
Here is the explanation:
Taking four grades from user.
Dropping the lowest one.
Taking average.
Giving a letter grade according to the average.
Here is the code:
test1 = int(input("Enter grade 1: "))
test2 = int(input("Enter grade 2: "))
test3 = int(input("Enter grade 3: "))
test4 = int(input("Enter grade 4: "))
x = min(test1,test2,test3,test4)
total = float(test1 + test2 + test3 + test4 - x)
avg = total / 3
print("Your average is " + str(avg))
def determine_letter(grade):
letter =""
if grade >= 90:
letter = "A"
elif grade >= 80:
letter = "B"
elif grade >= 70:
letter = "C"
elif grade >= 60:
letter = "D"
else:
letter = "F"
print("The final letter grade is " + letter)
determine_letter(avg)
I have been at this for a while, and I am stuck. I have to write a program that asks the user for each score and the average test score. I need the functions calcAverage which accepts five test scores and returns the average of the scores. determineGrade which accepts a score and returns the grade as a string based off the standard grading scale (90-100 is an A, 80-89 is a B, 70-79 is a C, etc). But I also need a function for getValidScore which prompts and reads a single valid test score and once the score is has been input it returns to the calling module. And finally isInValidScore is a function that checks whether a passed test score is in range from 0-100 and returns a Boolean letting me know if it's valid.
Here's what I have:
def main():
test1 = int(input('Enter test grade 1: '))
test2 = int(input('Enter test grade 2: '))
test3 = int(input('Enter test grade 3: '))
test4 = int(input('Enter test grade 4: '))
test5 = int(input('Enter test grade 5: '))
grade = (test1 + test2 + test3 + test4 + test5)
input('press enter to continue')
print(calc_average)
print(determine_grade)
print(getValidScore)
print(isInvalidScore)
return;
def calcAverage():
grade / 5
return averageScore
def determinGrade(score):
if grade >= 90 and grade <= 100:
return 'A'
elif grade >= 80 and grade <= 89:
return 'B'
elif grade >= 70 and grade <= 79:
return 'C'
elif grade >= 60 and grade <= 69:
return 'D'
else:
return 'F'
def getValidScore():
grade = int(input('input score'))isInvalidScore(score)
while isInvalidScore == false:
print('ERROR')
grade = int(input('input correct score'))
return score
def isInvalidScore(score):
status = True
if score < 0 or score > 100:
status = True
else: status = False
return status
main()
So I added returns and when I run the program, I get this:
Enter test grade 1: 99
Enter test grade 2: 88
Enter test grade 3: 77
Enter test grade 4: 66
Enter test grade 5: 55
press enter to continue
function calc_average at 0x02BAD228>
function determine_grade at 0x02BAD270>
function getValidScore at 0x02BAD2B8>
function isInvalidScore at 0x02BAD300>
There are a few things wrong here:
You're printing out the function itself which is represented by the location in memory, not the result of execution. Add parentheses to the ends of your calls to print out the result.
You should be calling getValidScore and return an integer result instead of reading in input without validation (see main).
Some of your functions take parameters, but you aren't passing any (hint: determinGrade, isInvalidScore).
Some of your functions should take parameters (hint: calcAverage).
calcAverage should return a real number with the actual average. (hint: return grade/5)
Your while loop should start with while isInvalidScore(grade), making the call on the previous line unnecessary.
In main, you're calling an undefined function (determine_grade, is it a typo?)
That's all I can see on a quick look of it. Good luck!
The answer from #tdlive aw'sum is actualy really good (I just upvoted it). Read his comments and work with the stuff. I will supply you with a correction implementation.. I hope you study the aspects you dont understand but take away some good parts from it. Best of luck.
isValidScore = lambda n: 0 <= n <= 100
calcAverage = lambda *args: sum(args)/len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(60, 99)/10)-5)]
def getValidScore():
while True:
try:
if isValidScore(int(raw_input('Input score: '))):
return score
except ValueError:
pass
print('Score has to be an integer in the range 0 to 100')
if __name__ == "__main__":
scores = []
for _ in range(5):
scores.append(getValidScore())
print('\nThe scores are: ' + str(scores))
print('The average is: ' + str(calcAverage(*scores)))
print('The grade is: ' + determinGrade(calcAverage(*scores)))