This question already has answers here:
How do I read from stdin?
(25 answers)
Closed 17 days ago.
How do I get an input from the user to be used as grade?
def grade_converter(grade):
if grade >= 90:
return "A"
elif grade >= 80:
return "B"
elif grade >= 70:
return "C"
elif grade >= 65:
return "D"
else:
return "F"
raw_input() returns a string, but your function is comparing against integers. Convert your input to an integer before calling grade_converter():
grade = int(raw_input('Enter a grade'))
print grade_converter(grade)
Note that the conversion will raise an exception if you enter something that can't be converted to an integer.
In Python3, raw_input() was renamed to input(). You could just use it as an input to your grade_converter() function:
if __name__ == '__main__':
print('Enter a score')
print('The grade is: ', grade_converter(int(input())))
Related
This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 1 year ago.
I am a beginner to python and coding in general and have not a clue why return in the code below doesn't move across functions. Shouldn't the value for n be stored for use in all functions? print(n) is in there only for my own sake to see if it works, and it is apparently not.
def main():
print("This program tests the Goldbach's conjecture")
get_input()
print(n)
def get_input():
n = 0
while n == 0:
try:
v = int(input("Please enter an even integer larger than 2: "))
if v <= 2:
print("Wrong input!")
continue
if v%2 == 1:
print("Wrong input!")
continue
if v%2 == 0:
n = v
except ValueError:
print("Bad input!")
continue
return n
You are not storing the value returned by get_input anywhere, you should keep it in a variable (or printing it directly), e.g -
def main():
print("This program tests the Goldbach's conjecture")
val = get_input()
print(val)
n is an internal variable that stored only within the scope of get_input.
This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Closed 5 years ago.
I've recently been breaching out to Python, as C++ is fun and all, but python seems kinda cool. I want to make Python do something as long as the input is between a certain number range.
def main():
grade = float(input("“What’s your grade?”\n:"))
if grade >= 90:
print("“You’re doing great!”")
elif(78 >= grade <= 89):
print("“You’re doing good!”")
elif(77 >= grade > 65):
print("You need some work")
else:
print("Contact your teacher")
main()
The problem arises when I'm making the elif statement, I can't make it so Python only prints the "doing great" statement as long as the grade is between 65 and 89. How would you go about doing ranges of numbers?
In Python you can do something like this to check whether an variable is within a specific range:
if 78 <= grade <= 89:
pass
This question already has answers here:
Python 3- Assign grade
(2 answers)
Closed 6 years ago.
• Define a function to prompt the user to enter valid scores until they enter a sentinel value -999. Have this function both create and return a list of these scores. Do not store -999 in the list!
• Have main( ) then pass this the list to a second function which traverses the list of scores printing them along with their appropriate grade.
I am having trouble with the getGrade function, it gives the error for i in grades: name 'grades' is not defined.
def main():
grade = getScore()
print(getGrade(grade))
def getScore():
grades = []
score = int(input("Enter grades (-999 ends): "))
while score != -999:
grades.append(score)
score = int(input("Enter grades (-999 ends): "))
return grades
def getGrade(score):
best = 100
for i in grades:
if score >= best - 10:
print(" is an A")
elif score >= best - 20:
print(score, " is a B")
elif score >= best - 30:
print(score, " is a C")
elif score >= best - 40:
print(score, " is a D")
else:
print(score, "is a F")
main()
You defined your function to be getScore() but you're calling getScores(), so as would be expected this throws an error because the function you're calling doesn't actually exist / hasn't been defined.
Addendum: Since you changed your question, after fixing the previous error.
Likewise you're calling grades, but grades is defined in your other function not within the scope of the function where you're trying to iterate over grades.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The code:
#Loop to conduct program. User input required for each option.
count = 1
while count == 1:
score = input("Enter Test Score: ")
if (score >= 90) and (score <= 100):
print "A"
elif (score >= 80) and (score <= 89):
print "B"
elif (score >= 70) and (score <= 79):
print "C"
elif (score >= 60) and (score <= 69):
print "D"
elif (score <= 59):
print "F"
elif (score == quit):
print "Program Finsihed. Goodbye."
count = 0 #Count to end loop
else:
print "Please enter valid response."
All other conditions work, however, if something typed it does not meet the parameters, the code is supposed to prompt them again (which is what the while loop is for). However, an error arises whenever a string that does not match the parameters is attempted.
Don't use input. input on Python 2 tries to evaluate the input as a Python expression, so if you type something like fhqwhgads, Python thinks that's supposed to be Python code and throws an error because there's no fhqwhgads variable.
Use raw_input, which gives you the input as a string. You can then perform string operations on it, or (try to) convert it to an integer and handle the exception if the conversion fails:
while True:
user_input = raw_input("Enter Test Score: ")
if user_input == 'quit':
print "Program Finsihed. Goodbye."
break
try:
score = int(user_input)
except ValueError:
print "Please enter valid response."
continue
if 90 <= score <= 100:
print "A"
elif 80 <= score < 90:
...
Incidentally, quit is one of the few choices you could have made for your "we're done here" option that wouldn't have caused an error with your original code, because there's (usually) an actual quit object for that to resolve to when input tries to treat it as Python code.
There were many problems with your code. I think it would be much easier to see and resolve the issues if you break your code down into functional units. I made two functions: get_score deals with prompting the user for input and score_to_grade converts a number score into a letter score. Doing this makes the code much more readable and easier to refactor, debug, etc. in the future.
def get_score():
while True:
user_in = raw_input("Enter Test Score: ")
try:
return float(user_in)
except ValueError:
if user_in == "quit":
print "Program Finished. Goodbye."
raise SystemExit
print "Please enter valid response."
def score_to_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
while True:
print score_to_grade(get_score())
quit needs to be in quotes, since it is a string, not a variable:
...
elif (score == "quit")
...
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 2 years ago.
Background: total beginner to Python; searched about this question but the answer I found was more about "what" than "why";
What I intended to do: Creating a function that takes test score input from the user and output letter grades according to a grade scale/curve; Here is the code:
score = input("Please enter test score: ")
score = int(score)
def letter_grade(score):
if 90 <= score <= 100:
print ("A")
elif 80 <= score <= 89:
print ("B")
elif 70 <= score <= 79:
print("C")
elif 60 <= score <= 69:
print("D")
elif score < 60:
print("F")
print (letter_grade(score))
This, when executed, returns:
Please enter test score: 45
F
None
The None is not intended. And I found that if I use letter_grade(score) instead of print (letter_grade(score)) , the None no longer appears.
The closest answer I was able to find said something like "Functions in python return None unless explicitly instructed to do otherwise". But I did call a function at the last line, so I'm a bit confused here.
So I guess my question would be: what caused the disappearance of None? I am sure this is pretty basic stuff, but I wasn't able to find any answer that explains the "behind-the-stage" mechanism. So I'm grateful if someone could throw some light on this. Thank you!
In python the default return value of a function is None.
>>> def func():pass
>>> print func() #print or print() prints the return Value
None
>>> func() #remove print and the returned value is not printed.
>>>
So, just use:
letter_grade(score) #remove the print
Another alternative is to replace all prints with return:
def letter_grade(score):
if 90 <= score <= 100:
return "A"
elif 80 <= score <= 89:
return "B"
elif 70 <= score <= 79:
return "C"
elif 60 <= score <= 69:
return "D"
elif score < 60:
return "F"
else:
#This is returned if all other conditions aren't satisfied
return "Invalid Marks"
Now use print():
>>> print(letter_grade(91))
A
>>> print(letter_grade(45))
F
>>> print(letter_grade(75))
C
>>> print letter_grade(1000)
Invalid Marks
Functions without a return statement known as void functions return None from the function. To return a value other than None, you need to use a return statement in the functions.
Values like None, True and False are not strings: they are special values and keywords in python which are being reserved.
If we get to the end of any function and we have not explicitly executed any return statement, Python will automatically return the value None. For better understanding see the example below. Here stark isn't returning anything so the output will be None
def stark(): pass
a = stark()
print a
the output of above code is:
None
Here is my understanding. A function will return "none" to the console if a value is not given to return. Since print is not a value, if you use print() as the only thing you want your function to do, 'none' will be returned to the console, after your printed statement. So, if the function wants a value, and you want a string to be that value returned...
Give your returned statement the value of a string like this...
Here is a very basic example:
def welcome():
return str('Welcome to the maze!')
Then print the function where you intend for it to be:
print(welcome()):
Result is:
Welcome to the maze!