I'm getting confused with functions as i have just tried to employ the if and else
functions and i can't get them working...
def instructions():
print ("Hello, and welcome to the programme")
def getInput(b):
b=int(input("Enter how many bags of Java coffe you have purchased: "))
if b <= 25:
bonus = b + 0:
if b >= 25:
else:
b <= 49:
bonus = b * 0.05:
if b <= 50:
else:
b >= 99:
bonus = b * 0.1:
if b >= 100:
bonus = b * 0.2:
...
instructions()
...
print("")
...
getInput()
the else on the second line is coming up as an error and so to id the b near the top.
Any help would be greatly appreciated.
Thanks.
Let me help you out a bit
if b <= 25:
bonus = b + 0:
elif b >= 25 and b <= 49:
bonus = b * 0.05:
elif b >= 50 and b <= 99:
bonus = b * 0.1:
else:
bonus = b * 0.2:
Should give you more of what you expect.
Also you will have issues with your get input it is expecting an argument when it should be returning one it should look more like this:
def getInput():
return int(input("Enter how many bags of Java coffe you have purchased: "))
You'll probably want to indent all of the bonus code into a function of its own and pass the return from getInput into it
Your code indentation is incorrect - this is important in python; it is part of the syntax.
The logic could do with a bit of cleaning up too;
def instructions():
print ("Hello, and welcome to the programme")
def getInput(b):
b=int(input("Enter how many bags of Java coffe you have purchased: "))
bonus = 0:
if 25 < b <= 50:
bonus = b * 0.05
elif b <= 99:
bonus = b * 0.1
elif b >= 100:
bonus = b * 0.2:
return b, bonus
...
instructions()
...
bagsBought, bonus = getInput()
print "You bought %i, and got %i bonus bags!" % (bagsBounght, bonus)
Related
Please help understand what is wrong with the code below. The code works fine if I pass values up to 34. Once I pass 35 or higher, the output is incorrect.
tuk=0
if tuk <= 24:
print ('The text is very easy to read.')
elif tuk >= 25 & tuk <= 34:
print('The text is easy to read.')
elif tuk >= 35 & tuk <= 44:
print('The text is moderately difficult to read.')
elif tuk >= 45 & tuk <= 54:
print('The text is difficult to read')
elif tuk >= 55:
print('The text is very difficult to read')
else:
print('This is beyond')
Your code is correct, but changing the "&" to "and" because "&" is a bitwise logical operator, not a logical one.
For example:
z = 0 := 0b000
a = 1 := 0b001
b = 2 := 0b010
c = 3 := 0b011
d = 4 := 0b100
now the result of the expression (a & c) is 0b001 or 1
but in logical expression (a and c) the result will be true, which I suppose you are interested in.
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")
def MultiplicationTable():
on = True
while on:
print("\nType 101 to exit application.")
number = int(input("What table is to be printed out (1-10)? "))
if 0 < number < 11:
print("Multiplication table of: ", number)
for mul in range(1, 11):
print("{0} * {1} = {2}".format(number, mul, (number * mul)))
elif number < 0:
print("Your Input is a negative number!")
elif number == 0:
print("Your input is zero, any number multiplied to zero is also zero.")
elif number == 101:
print("Quitting application...")
on = False
else:
print("Your Input is greater than 10!")
MultiplicationTable()
I've tried putting yield, but I cannot make it work.
The output should be like this:
What table is to be printed out (1-10)? 1
Multiplication table of: 1
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
Like this? If you have to use yield in this program. But seem no meaning.
def MultiplicationTable():
on = True
while on:
print("\nType 101 to exit application.")
number = int(input("What table is to be printed out (1-10)? "))
if 0 < number < 11:
print("Multiplication table of: ", number)
for line in gen_multi_table(number):
print(line)
elif number < 0:
print("Your Input is a negative number!")
elif number == 0:
print("Your input is zero, any number multiplied to zero is also zero.")
elif number == 101:
print("Quitting application...")
on = False
else:
print("Your Input is greater than 10!")
def gen_multi_table(number):
for mul in range(1, 11):
yield "{0} * {1} = {2}".format(number, mul, (number * mul))
MultiplicationTable()
The yield statement just suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run.
def MultiplicationTable():
on = True
while on:
yield("\nType 101 to exit application.")
number = int(input("What table is to be printed out (1-10)? "))
if 0 < number < 11:
yield "Multiplication table of: "+str(number)
for mul in range(1, 11):
yield("{0} * {1} = {2}".format(number, mul, (number * mul)))
break
elif number < 0:
yield("Your Input is a negative number!")
elif number == 0:
yield("Your input is zero, any number multiplied to zero is also zero.")
elif number == 101:
yield("Quitting application...")
on = False
else:
yield("Your Input is greater than 10!")
for i in MultiplicationTable():
print(i)
for any reference : link
I recently tried to make a love calculator with this code. However, when faced with a name that has over 11 characters in common for either 'love' or 'true' it does not return the proper statement. For example, if I get 711 returned because the 'love' statement is over 9, it just gives me the 'else' option instead of the => 90 statement. I'm not sure what I did wrong. Thank you for any help in advance!
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_names = str(name1.lower()) + str(name2.lower())
t = combined_names.count('t')
r = combined_names.count('r')
u = combined_names.count('u')
e = combined_names.count('e')
l = combined_names.count('l')
o = combined_names.count('o')
v = combined_names.count('v')
e = combined_names.count('e')
Love = l + o + v + e
true = t + r + u + e
truelove = int(str(true) + str(Love))
if truelove <= 10 and truelove >= 90:
print(f"Your score is {truelove}, you go together like coke and mentos")
elif truelove >= 40 and truelove <= 50:
print(f"Your score is {truelove}, you are alright together")
else:
print(f"Your score is {truelove}")
truelove <= 10 and truelove >= 90
Will always give false and not pass this if statement.
To be able to run it you can try.
truelove >= 10 and truelove <= 90
EDIT: I saw that your elif statement will never work because first if statement is wider range. So flipping the if statements will fix it.
if truelove >= 40 and truelove <= 50:
print(f"Your score is {truelove}, you are alright together")
elif truelove >= 10 and truelove >= 90:
print(f"Your score is {truelove}, you go together like coke and mentos")
else:
print(f"Your score is {truelove}")```
I tried to do the first assignment from http://www.cplusplus.com/forum/articles/12974/
g = int(raw_input('Enter the grade you scored: '))
if g >= 90 & g <= 100:
print 'Your grade is: A'
elif g >= 80 & g < 90:
print 'Your grade is: B'
elif g >= 70 & g < 80:
print 'Your grade is: C'
elif g >= 60 & g < 70:
print 'Your grade is: D'
elif g >= 50 & g < 60:
print 'Your grade is: E'
elif g >= 0 & g <= 49:
print 'Your grade is: F'
else:
print 'You can only enter an integer within the range of 0-100.'
The problem is that whenever I run this program, any number I input that is greater than 0 will get:
Your grade is: A
Any help greatly appreciated. Thanks!
Bi Rico's answer is simple and correct. To explain the situation further:
The & operator computes the bitwise AND of two integers. For example, 5 & 3 == 1.
The precedence of & is above the comparison operators (such as < and >=). So a < b & c < d actually means a < (b & c) < d.
Python allows chained comparisons. For example, a < b == c >= d translates into a < b and b == c and c >= d.
Putting these facts together, this is what happens when you run your program:
Assume that g is assigned an integer value between 0 and 100, inclusive.
So the if-test g >= 90 & g <= 100 means (g >= (90 & g)) and ((90 & g) <= 100).
Bitwise AND is always smaller than or equal to both arguments (i.e. (a & b <= a) and (a & b <= b)).
Thus 90 & g <= g is always true. Likewise, 90 & g <= 100 is always true, because 90 <= 100.
Therefore the first if-test is always true, so the body will execute and the elif/else clauses will never execute.
The problem in your code is that you're using & when you want to use and, try this:
if g >= 90 and g <= 100:
print 'Your grade is: A'
...
The code you had their was spot on but syntax is very important in Python. You want to use and where you have & like this:
g = int(raw_input('Enter the grade you scored: '))
if g >= 90 and g <= 100:
print 'Your grade is: A'
elif g >= 80 and g < 90:
print 'Your grade is: B'
elif g >= 70 and g < 80:
print 'Your grade is: C'
elif g >= 60 and g < 70:
print 'Your grade is: D'
elif g >= 50 and g < 60:
print 'Your grade is: E'
elif g >= 0 and g <= 49:
print 'Your grade is: F'
else:
print 'You can only enter an integer within the range of 0-100.'
This will display what you need the correct way.
Using the correct keyword is always important as certain things can cause errors. Use and, not &.