This progam was working fine before i used data validation(the while loops) but now i get the following error -
average_grade = (grade1 + grade2) / 2
NameError: name 'grade2' is not defined
This error was not happening before , I have just started programming so i am quite confused
valid = False
while valid==False:
grade1 = float( input("Enter the grade1: ") )
if grade1 <0 or grade1 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
valid = True
while valid==False:
grade2 = float(input("Enter the grade2: "))
if grade2 < 0 or grade2 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
valid = True
while valid == False:
absences = int(input("Enter the number of absences: "))
if type(absences)!=int:
print("Number of absences can only be an integer value")
continue
else:
valid = True
while valid == False:
total_classes = int(input("Enter the total number of classes: "))
if type(total_classes)!=int:
print("Total number of classes can only be an integer value")
continue
else:
valid = True
average_grade = (grade1 + grade2) / 2
attendance = ((total_classes - absences) / total_classes)*100
print(average_grade)
print("Your attendance is :", attendance , "%")
if(average_grade>=6):
if(attendance>=0.8):
print("YOU HAVE PASSED")
else:
print("You have failed as your attendance is less than 80%")
elif(attendance>=0.8):
print("You have failed due to average grade being lower than 6")
else:
print("You have failed due to average grade being lower than 6 and attendance lower than 80%")
The problem is that you're never resetting the value of valid, so once you set valid = True in the first while loop, none of the other loops will execute (because the loop condition will be false).
You don't need the valid variable in any case; instead of having a
conditional loop expression with a flag, just break out of the loop
when you receive a valid value:
while True:
grade1 = float( input("Enter the grade1: ") )
if grade1 <0 or grade1 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
break
while True:
grade2 = float(input("Enter the grade2: "))
if grade2 < 0 or grade2 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
break
while True:
absences = int(input("Enter the number of absences: "))
if type(absences)!=int:
print("Number of absences can only be an integer value")
continue
else:
break
while True:
total_classes = int(input("Enter the total number of classes: "))
if type(total_classes)!=int:
print("Total number of classes can only be an integer value")
continue
else:
break
Unrelated to your question, but when you have a boolean variable you
don't need to compare it explicitly to False (or True); you can
use the value of the variable itself as the condition:
while somevar == False:
You can just write:
while not somevar:
Related
The question is to check the guess entered as the input to the random number generator,
Here is my code for that,
import random
int1 = 1
int2 = 50
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break
The loop breaks after one cycle,
This solves the problem:
import random
int1 = 1
int2 = 50
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break #break used inside elif to loop while correct is not provided
Your booleans seem backward to me. When if a > correctNumber: the the guess is "HIGH" not "LOW".
With that, instead of breaking. You could make your while loop condition based on whether the guess is correct.
import random
int1 = 1
int2 = 50
correctNumber = random.randint(int1, int2)
a = int(input("Please enter your number: "))
while a != correctNumber:
if a < correctNumber:
print("LOW")
elif a > correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
print("YOU GOT IT RIGHT")
If you are using a recent version of python, you can simplify it even further by assigning in the while loop with the := (walrus) operator:
import random
int1 = 1
int2 = 50
correctNumber = random.randint(int1, int2)
while (a := int(input("Please enter your number: "))) != correctNumber:
print("LOW" if a < correctNumber else "HIGH")
print("YOU GOT IT RIGHT")
Indent the break statement from the final line.
The break keyword is used to break out of the while loop. At its current state, the loop is terminating after 1 cycle because it hits the break keyword.
If you indent the break statement, it will be part of the elif block of code, and will only execute after a == correctNumber.
This code would work:
import random
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break
Learn more about break here
def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue
I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))
I want to make the loop continue and catch errors like entering "bob" as an input or integers less than 1 and greater than 4.
salesNum = input("How many sales persons to process? ")
for num in salesNum:
salesName = input("Enter Salesperson Name: ")
salesLevel = 0
while salesLevel == 0:
try:
salesLevel = int(input("Enter Salesperson Level: "))
if salesLevel < 1 or salesLevel > 4:
print("error, try again.")
salesLevel = int(input("Enter Salesperson Level: "))
except ValueError:
print("error, try again")
continue
hoursWorked = float(input("Enter Hours Worked: "))
salesAmount = float(input("Enter Number of Sales: "))
print("Clear")
It works fine if I make one error, but multiple errors don't get caught and the program moves on to the next questions.
I have tried breaking the if statement up, but that doesn't solve the issue.
The error won't be ValueError, so you either change it to TypeError:
except TypeError:
Or to any error:
except:
salesNum = input("How many sales persons to process? ")
for num in salesNum:
salesName = input("Enter Salesperson Name: ")
salesLevel = 0
while salesLevel == 0:
try:
salesLevel = int(input("Enter Salesperson Level: "))
if salesLevel < 1 or salesLevel > 4:
print("error, try again.")
salesLevel = int(input("Enter Salesperson Level: "))
except Exception:
print("error, try again")
continue
hoursWorked = float(input("Enter Hours Worked: "))
salesAmount = float(input("Enter Number of Sales: "))
print("Clear")
try change ValueError to Exception this will catch every abnormality
I first asked the user to enter a number and then ran a try/except block. I now want to check to see if the number is in a range between 1-9.
If not I want it to check if int and then check if it is in range.
Here is what I have so far:
def getInt(low, high):
start = 0
while start == 0:
try:
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
start = 1
asdf = 0
while asdf == 0:
if num > 9 or num < 0:
print("Error: Please only enter numbers between 1-9")
else:
asdf = +1
return num
except:
print("Error: Please only enter numbers")
# main
TOTAL_NUMBERS = 2
LOW_NUMBER = 1
HIGH_NUMBER = 9
num1 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num1)
num2 = getInt(LOW_NUMBER, HIGH_NUMBER )
print(num2)
Maybe you need this:
def getInt(low, high):
while True:
try:
num = int(input("Enter a number for your calculation in range of 1- 9: "))
except ValueError:
print("Error: Please only enter numbers")
continue
if num not in range(1, 10):
print("Error: Please only enter numbers between 1-9")
else:
return num
You could replace
print("Error: Please only enter numbers between 1-9")
with
num = input("Error: Please only enter numbers between 1-9: ")
or move
num = input("Enter a number for your calculation in range of 1- 9: ")
num = int(num)
into the while loop so it gets called again if the user inputs a number outside the range
def getInt(low, high):
while True: # Keep asking until we get a valid number
try:
numStr = raw_input("Enter a number for your calculation in range of {0} - {1}: ".format(low, high) )
if numStr.isdigit():
num = int(numStr)
if num <= high and num >= low:
return num
except: # Field left empty
pass
getInt(1, 9)