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
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 8 months ago.
I can't figure out how to handle any exceptions for non-int or float inputs on the program below. Could you guys please point me in the right direction?
def GradeAverager(): #Creating the function of the grade averager
#User initiation input
response = input("\n\nWould you like to average your grades? Press Y for "
"Yes or N to exit: ")
#Defined controlled repsonse variables
y="Y"
n="N"
if response in ["y","Y"]: #If statement based on response (allows for
#different variatios of the inputs)
# User input the # of grades to average
numOfGrades = float(input("\n\nEnter number of grades to be averaged: "))
if type(numOfGrades) is not float:
#Handles non-int exception (NOT WORKING)
raise TypeError("Only Numbers please!")
#Defining the variables for the while statement
x=0
grades = 0
rounded_average = 0
while x < numOfGrades: # While loop to keep asking the user for grades
# based on "numOfGrades"
grades += float(input("\n Enter Grade: ")) # User input is taken
# and added to grades
if not type(grades) is not float:
#Handles non-int exception (NOT WORKING)
raise TypeError("Only Numbers please!")
x += 1 # keeps the loop repeating until it is no longer true
average = grades/numOfGrades # Takes the total of grades and divides it
# by numOfGrades to calculate average
rounded_average = round(average, 1) #Rounds the total to two one decimal
print("\n\nYour Grade Average is: " + str(rounded_average))
#If statements based on result scores
if average > 70:
print("\n You are passing but should study harder :|\n\n")
elif average > 80:
print("\n Good Job! you're getting there! :)\n\n")
elif average > 90:
print("\n Awesome Job! You are Acing this! XD\n\n")
else:
print("\n You need to go back and study! :(\n\n")
elif response in ["n","N"]: #If user answers "no", ends the program
print("\n\nGood Luck!\n\n")
else:
print("\n\nIncorrect Entry\n\n")
GradeAverager()
print("\n\n*****Welcome to the Grade Averager******") #Prints the title
GradeAverager() #Calls the function
You just have an extra "not" in the line:
if not type(grades) is not float:
Change it to:
if not (type(grades) is float):
But in general it's better to do it like this:
if isinstance(grades, float):
but if you dig deeper, you'll realize that grades will always be of type float, only if the value from the input is correct. You need to check this. Review this and decide how best to check if the input value is a valid representation of a number.
UPD:
And as rightly noted in the comments, almost the same with the numOfGrades variable
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I'm putting together a small program for a friend that requires an input from the user, and depending on the input it does a certain function
Heres my code:
value = input ("Enter Number")
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")
However, even entering 1 or 2, it always prints "hmmm".
I've tried everything including making a new function and passing the input into it and still it doesn't take. Any advice?
That's because you are taking input as a string not an integer.
Because of it your value is string and when it is compared with integer 1 or 2 it's coming false and the else condition gets satisfied.
Correct code:
value = int(input ("Enter Number"))
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")
This question already has answers here:
Python - User input data type
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am very new to programming and Python. To get started I'm working on a little game that will ask the user for some input and then do "something" with it. My problem is I've seem to account for if the user types in an int lower or high than my parameters BUT i can't seem to find a way to re-prompt the user if they type in anything but an int.
With my limited knowledge I thought that when using an if/elif/else statement if you didn't define what the if/elif is looking for than the else statement was there for everything else that you didn't account for?
Looking for some more insight on how to master this fundamental concept
Thank you in advance!
prompt = True
while prompt == True:
user_input = input("Please give me a number that is greater than 0 but less than 10 \n >")
if user_input > 0 and user_input <= 10:
print("Good job " + str(user_input) + " is a great number")
break
elif (user_input > 10):
print("Hey dummy " + str(user_input) + " is greater than 10")
elif (user_input <= 0):
print("Hey dummy " + str(user_input) + " is less than 0")
else:
print("I have no idea what you typed, try again!")
How about something like this?
a = -1
while a < 0 or a > 10:
try:
a = int(input("Enter a number between 0 and 10: "))
except ValueError:
continue
This will only allow the user to enter an int from 0 to 10, this will also remove the need to print those messages if the number is outside of this range, if you would like to keep those messages I could make adjustments and show you how to handle that as well
This question already has answers here:
convert txt file with mixed spaces/tabs to tabs only (where possible) [closed]
(7 answers)
Closed 4 years ago.
This is a small game I made. Simple rules, the player must determine the number in my mind. I will later import random module though.
print('Hello!, What is your name?')
userName = input()
print(myName + 'Welcome to Guess it! Ralph')
print('You must guess the number that I have in my mind(from 1 to 10) within 5 chances')
myNumber = 3
print('Give your prediction')
for no_of_chances in range(5, 0, -1):
usersPrediction = input()
I get this error when I run in pycharm:
if usersPrediction < myNumber:
^
IndentationError: unexpected indent
if usersPrediction < myNumber:
print('It is lower than required,try a higher value')
elif usersPrediction > myNumber:
print('It is higher than required,try a lower value')
elif usersPrediction == myNumber:
print('yahoo!, you did it')
print('You always have a next chance, try it again')
Indent print('yahoo!, you did it')
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!