Python for everybody assignment 3.3 - python

Why wouldn't my for loop work? If I put in 0.85 for grade score it'd print out F and error message instead of B. Why is this?
grade=input('Score Grade:')
fg=float(grade)
for fg in range(0,1):
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')
print('error grade out of range')
quit()

You are misusing the range() function. range() is used to iterate over multiple values, not to validate if a number is in a range. You should instead check that fg greater than or equal to 0, or less than or equal to 1. Like this:
grade=input('Score Grade:')
fg=float(grade)
if 0 > fg or 1 < fg:
print('error grade out of range')
quit()
if fg >= 0.9:
print('A')
elif fg>=0.8:
print('B')
elif fg>=0.7:
print('C')
elif fg>=0.6:
print('D')
else:
print('F')

you are doing this for one time you dont need to use a loop
you can do this
grade = float(input('Score Grade:'))
if grade < 1 and grade > 0:
if grade > 0.9:
print('A')
elif grade >= 0.8:
print('B')
elif grade >= 0.7:
print('C')
elif grade >= 0.6:
print('D')
elif grade < 0.6:
print('F')
else:
print('error grade out of range')
quit()

You do not need to use for operator neither range. The simplest solution is:
'''
grade = input("Enter number:")
try:
grade = float(grade)
except:
grade = -1
if grade >= 0.9:
print("A")
elif grade >= 0.8:
print("B")
elif grade >= 0.7:
print("C")
elif grade >= 0.6:
print("D")
elif grade < 0.6:
print("F")
else:
print("Error!")
quit()
'''

Related

need help finding error on my python code

I am Writing a program to prompt for a score between 0.0 and 1.0. If the score is out of range print an error. If the score is between 0.0 and 1.0, print a grade using the following table:Score Grade >= 0.9 A>= 0.8 B>= 0.7 C>= 0.6 D< 0.6 F.
To give an example of what it should do at the end it is:
Enter score: 0.95, A
Enter score: perfect, Invalid input
Enter score: 10.0, Invalid input
Enter score: 0.75, C
Enter score: 0.5, F
This is the code I have now:
score = input("Enter Score: ")
try:
score= float(score)
if(score >= 0.0 and score <= 1.0):
if (score>= 0.9):
print("A")
elif (score>= 0.8):
print("B")
elif(score>= 0.7):
print("C")
elif (score>= 0.6):
print("D")
elif (score < 0.6):
print("F")
else:
print("Invalid input")
I cant seem to get it up and running. Any help would be appreciated.
Your try statement probably wants to do two things: verify that the user input can be converted to a float, and that the resulting float is in the range 0-100. Nothing else should be in the try statement.
If the value is not a float or out of range, you can let the loop continue to get another input. Otherwise, you can proceed with a single if statement to map the score to a letter grade.
while True:
score = input("Enter score: ")
try:
score = float(score) # Could raise ValueError
if not (0 <= score <= 1.0):
raise ValueError
except ValueError:
print("invalid input")
else:
break
if (score>= 0.9):
print("A")
elif (score>= 0.8):
print("B")
elif(score>= 0.7):
print("C")
elif (score>= 0.6):
print("D")
else: # Only option left for an in-range value.
print("F")
Strictly speaking, the range check could be moved out of the try statement as well:
while True:
try:
score = float(score)
except ValueError:
print("invalid input")
continue
if 0 <= score <= 1.0:
break
print("invalid input")
I converted the failed range check to a ValueError mainly to have one error message and one place where we use break, rather than an explicit continue. There are several ways to structure it, but the common feature is that you verify that score has a value suitable for the following grade map first.
Green-Avocado has a great answer. I would add a while loop to retry until the input is valid;
# loop until complete
while True:
score = input("Enter Score: ")
# let's try this
try:
score = float(score)
if score >= 0.0 and score <= 1.0:
if score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
elif score < 0.6:
print("F")
# exit the loop on completion
break
# else raise an exception
raise
# if problem with float(score) or exception raised
except:
print("Invalid input")
You need an except block after your try block to handle errors.
Instead of printing the error in the last elif, this can be used to handle all errors.
You can manually raise the error using raise.
score = input("Enter Score: ")
try:
score = float(score)
if score >= 0.0 and score <= 1.0:
if score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
else:
print("F")
else:
raise
except:
print("Invalid input")

data type error on 'if' conditional statement

I am trying to print a grade with the score value for instance 0.85
At first I tried like this below:
score = input("Enter Score: ")
float(score)
if 0.0 <= score <= 1.0:
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score >= 0.6:
print('D')
else:
print('F')
else:
print("ERROR")
But this returns an ERROR message.
Does anyone know why?
I know I can do this like: score = float(input("Enter Score: "))
What the difference?
you didn't store your float(score) in a variable . you can do it this way .
score_string = input("Enter Score: ")
score = float(score_string)
if 0.0 <= score <= 1.0:
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score >= 0.6:
print('D')
else:
print('F')
else:
print("ERROR")
You can use isinstance(score, float) or type(score).__name__ to check, for example:
score = input("Enter Score: ")
print(type(score).__name__) # str
print(isinstance(score, float))
And you can use the method of eval that parsed and evaluated the variable as a Python expression.
for cur_exp in ('12345', '"abc"', '[1, 3, 5]', '("a", "b", "c")'):
var = eval(cur_exp)
print(type(var).__name__) # int, str, list, tuple
By the way, I think this way is more readable, just for your reference
while 1:
score = float(input("Enter Score: "))
rank = (print('error'), exit()) if not 0.0 <= score <= 1.0 else \
'A' if score >= 0.9 else \
'B' if score >= 0.8 else \
'C' if score >= 0.7 else 'D'
print(rank)

Allowing only integers and floaters as a user input, otherwise give the user a [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 3 years ago.
As a user input on a Else,If, Elif statements, I only want to allow the user input to get a positive response from a number instead of letters or special characters. I have created a simple grading calculator. I am learning the basics and just playing around with different options.
So far I haven't tried anything
grade = input('what is your grade?')
if grade >= '90':
print('A')
elif grade < '90' and grade > '79':
print('B')
elif grade < '80' and grade > '69':
print('C')
elif grade < '70' and grade > '59':
print('D')
elif grade <'60':
print('F')
else:
print('Please enter your grade')
I inserted a word instead of a number and the return is 'F'. I want the return to be "error" or any message I choose if a number is not inserted after the question.
Use try and except. Complete code change is below.
check = True
grade = 0
while(check):
grade = input('what is your grade?')
try:
if float(grade) >= 0:
check = False
except:
print("Bad entry.")
if grade >= '90':
print('A')
elif grade < '90' and grade > '79':
print('B')
elif grade < '80' and grade > '69':
print('C')
elif grade < '70' and grade > '59':
print('D')
elif grade <'60':
print('F')
else:
print('Please enter your grade')

Grade computing program

I am learning python. The question is "Write a grade program using a function called computegrade that takes a score as its parameter and returns a grade as a string."
# Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
# < 0.6 F
How do I get the grades when I run this program? As I am not assigning the grades to any variable. Hence, unable to get the output.
def computegrade():
if score >=0.9:
print('Grade A')
elif score >=0.8 and score<0.9:
print('Grade B')
elif score >=0.7 and score<0.8:
print('Grade C')
elif score >=0.6 and score<0.7:
print('Grade D')
else:
print('Grade F')
score = input('Enter the score: ')
try:
score = float(score)
except:
print('Enter numbers only')
No Error messages, but I unable to see the grades when entering a value
You're not seeing the grades because you're not telling python to run computegrade. If you do
try:
score = float(score)
computegrade()
It'll be done with.
Some observations about the computegrade method. I advise you to make it accept score as an argument
def computegrade(score):
# grade calculations...
Although it works without this - as long as there is a score variable in the same scope, Python takes it - it feels counterintuitive to call a function that requires as score, not passing a score to it.
Also, currently your program accepts grades bigger than 1.0 and smaller than 0.0, which is something you may want to raise an AssertionError in the future. I don't know if that is in the scope of your learning program, but having an
def computegrade():
if score > 1.0 or score < 0.0:
raise AssertionError('Scores must be within the 1.0 and 0.0 range!')
Is a good practice.
def compute_grade(marks):
try:
if float(marks)>1.0 or float(marks)<0.0:
print("Invalid enteries")
else:
if float(marks) >= 0.9:
print("Grade A")
elif float(marks) >= 0.8:
print("Grade B")
elif float(marks) >= 0.7:
print("Grade C")
elif float(marks) >= 0.6:
print("Grade D")
elif float(marks) < 0.6:
print("Grade F")
except:
print("Please enter numeric value")
compute_grade(input("Please enter your marks\n"))
sco = float(input('Enter your score: '))
def compute_grade(score):
if score > 1.0:
s = 'Out of Range!'
return s
elif score >= 0.9:
s = "A"
return s
elif score >= 0.8:
s = 'B'
return s
elif score >= 0.7:
s = 'C'
return s
elif score >= 0.6:
s = 'D'
return s
elif score >= 0.5:
s = 'E'
return s
else:
s = 'Bad score'
return s
sc = compute_grade(sco)
print(sc)
You aren’t calling the function; you have told Python what the function is, but not called it.
What you need to do is
score = float(score)
grade = computegrade()
print(‘Score :’, score,’ Grade :’, grade)
It is better practice to define your function so that it takes a parameter ;
def computegrade( score):
Instead of your current ‘def’ line, and then when you call the function:
grade = computegrade( score)
It is far better practice to write functions with parameters rather than rely on external variables.
You forgot to call the function.
The following is only a definition of the wanted function.
def computegrade():
if score >=0.9:
print('Grade A')
elif score >=0.8 and score<0.9:
print('Grade B')
elif score >=0.7 and score<0.8:
print('Grade C')
elif score >=0.6 and score<0.7:
print('Grade D')
else:
print('Grade F')
You need to call the function for it to be "activated".
You do so by writing:
computegrade()
So i would guess that the resulting code should look like this:
score = input('Enter the score: ')
try:
computegrade()
except:
print('Enter numbers only')
(no need to convert to float, the command input() does it for you...)

How may I get the desired output in my code?

I was attempting to solve some python excercise. I came across a question and that has made me feel bored. Please will you resolve it?
A school has following rules for grading system:
Below 25 - F
25 to 45 - E
45 to 50 - D
50 to 60 - C
60 to 80 - B
Above 80 - A
Ask user to enter marks and print the corresponding grade.
print("My mark is ")
a = input()
if '25 > a':
print('F')
elif a < 25 and a > 45:
print('E')
elif 45 <= a and a >|= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
My expected result was different grades for different numbers but instead got only F for every input I do...
print("My mark is ")
a = int(input())
if a < 25:
print('F')
elif a >= 25 and a < 45:
print('E')
elif a >= 45 and a < 50:
print('D')
elif a >= 50 and a < 60:
print('C')
elif a >= 60 and a < 80:
print('B')
else:
print('A')
first of all, you should cast input to int. then, you just compare it and "a" should be the first in comparing like a > 25, not 25 < a
Multiple issues..
Remove the outside quotes of your if statements as those are strings.
elif '45 <= a and a => 50': the order must be >=
And you must compare with an int so you need to do int(input()) or another variation of converting to int type.
a = int(input('What is the grade?'))
print("My mark is ")
if 25 > a:
print('F')
elif a <= 25 and a > 45:
print('E')
elif 45 <= a and a >= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
your code needs a little clean up. Dont use quotation around the condition which is supposed to be Boolean
a = input("My mark is ")
a=int(a)
if (25 > a):
print('F')
elif a <= 25 and a > 45:
print('E')
elif 45 <= a and a >= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')

Categories

Resources