I dont kow why I keep getting this issue of "Name Error: Name 'a' is not defined"
def addition():
a = input("Enter your first number: ")
b = input("Enter secondary number: ")
c = int(a) + int (b)
print(a," + ",b," = ",c," . ")
I don't know how you've indented it, but I've got it to work like this...
def addition():
a = int(input("Enter your first number: "))
b = int(input("Enter secondary number: "))
c = a + b
print(a," + ",b," = ",c," . ")
addition()
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 11 months ago.
I'm trying to use list in this one but I had the bug in the last line stumarks[CourseID] = [(StuID,marks)]
Here is my code :
courselist = []
class course:
def __init__(self,id,name):
self.id = id
self.name = name
#classmethod
def CourseInfo(cls):
return cls(
input("Enter the course ID : "),
input("Enter the course name : ")
)
def cif():
for i in range(getNumOfCourses()):
cse = course.CourseInfo()
courselist.append(cse)
stumarks = []
def MarkInput():
CourseID = input("Enter the course's ID : ")
if CourseID not in [CourseInfo.id for CourseInfo in courselist]:
print(" The course's id isn't founded! Please try again!")
else:
nm = int(input("Number of student that you want to enter marks: "))
for i in range(nm):
while True:
StuID = input("Enter a student's ID : ")
if StuID not in [StudentInfo.id for StudentInfo in studentlist]:
print("The student's ID isn't founded! Please try again! ")
continue
break
marks = float(input("Enter the mark: "))
if CourseID in stumarks:
stumarks[CourseID].append((StuID,marks))
else:
stumarks[CourseID] = [(StuID,marks)]
Could anyone help me with this one? Thank you!
The problem is that CourseId is not cast to an integer and is hence treated as a string. Try changing:
CourseID = input("Enter the course's ID : ")
to
CourseID = int(input("Enter the course's ID : "))
print("Welcome to The pyCalc")
print("For Addition press 1")
print("For Multiplication press 2")
print("For Subtraction press 3")
print("For Division press 4")
flag = 'y'
while flag == 'y':
x = float(input("Enter your Choice(1-4): "))
if x == 1:
a = float(input("Enter 1st Value: "))
b = float(input("enter 2nd Value: "))
c = a+b
print("Sum: ", int(c))
elif x == 2:
a = float(input("Enter 1st Value: "))
b = float(input("Enter 2nd Value: "))
c = a*b
print("Product: ", int(c))
elif x == 3:
a = float(input("Enter the 1st value: "))
b = float(input("Enter the 2nd value: "))
c = a - b
print("Difference: ", int(c))
elif x == 4:
a = float(input("Enter the 1st value: "))
b = float(input("Enter the 2nd value: "))
c = a // b
print("Quotient: ", c)
else:
print("error !")
flag = print(input("Do you want to calculate more(y/n)? : ", y))
if flag == y:
continue
Hi, I'm actually new to Python so not really familiar with even basic concepts. so in this calculator program, after the first run, i want the code to rerun when the user gives an input of y. According to my knowledge, this is possible using a while loop in which we put the main code in its body and give a condition using if statement and the secondly by using the continue statement. Can somebody explain whats wrong here.
p.s. indentation may be wrong in some cases.
I have re-written your code because there were two issues:
There's no such thing as print(input(""))
flag = input("Do you want to calculate more(y/n)? : ") should be outside else
print("Welcome to The pyCalc")
print("For Addition press 1")
print("For Multiplication press 2")
print("For Subtraction press 3")
print("For Division press 4")
flag = 'y'
while flag == 'y':
x = float(input("Enter your Choice(1-4): "))
if x == 1:
a = float(input("Enter 1st Value: "))
b = float(input("enter 2nd Value: "))
c = a+b
print("Sum: ", int(c))
elif x == 2:
a = float(input("Enter 1st Value: "))
b = float(input("Enter 2nd Value: "))
c = a*b
print("Product: ", int(c))
elif x == 3:
a = float(input("Enter the 1st value: "))
b = float(input("Enter the 2nd value: "))
c = a - b
print("Difference: ", int(c))
elif x == 4:
a = float(input("Enter the 1st value: "))
b = float(input("Enter the 2nd value: "))
c = a // b
print("Quotient: ", c)
else:
print("error !")
flag = input("Do you want to calculate more(y/n)? : ")
if flag.lower() == "y":
continue
I keep getting syntax error highlighted on "m" in second row on the variable "mark2".
This is the code I have:
print("Please enter your 5 marks below")
mark1 = float(input("enter mark1: ")
mark2 = float(input("enter mark2: ")
mark3 = float(input("enter mark3: ")
mark4 = float(input("enter mark4: ")
mark5 = float(input("enter mark5: ")
marksList = [mark1, mark2, mark3, mark4, mark5]
print(marksList)
sumofMarks = mark1 + mark2 + mark3 + mark4 + mark5
averageOfMarks = sumofMarks/5
print("The sum of your mark is: "+str(sumofMarks))
print("The sum of your mark is: "+str(averageOfMarks))
mark1 = float(input("enter mark1: "))
^ you missed this
In the next 4 lines as well. It is better to use an IDE (Eg: PyCharm) to catch these errors.
This program prints 'Select a Valid function!' even if the input is correct, why is that? And how can I tell the program that I'm talking about individual elements in a list and not the entire list?
sign = input ("Enter the sign: ")
if sign != ["+","-","*","/"]:
print ("Select a Valid function!")
else:
print ("Let's Begin")
if sign =="+":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)+int(no2))
elif sign =="-":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)-int(no2))
elif sign =="*":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)*int(no2))
elif sign =="/":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)/int(no2))
if sign != ["+","-","*","/"]:
That will always be true, because sign is not a list, so it will never be equal to a list.
You want to use the in operator instead:
if sign not in ["+","-","*","/"]:
As others have pointed out, you're not using the correct operator to check if something is in a list.
But you don't even need that check. Just add an else: statement after all the if/elif.
sign = input ("Enter the sign: ")
if sign =="+":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)+int(no2))
elif sign =="-":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)-int(no2))
elif sign =="*":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)*int(no2))
elif sign =="/":
no1 = input("Enter the first number: ")
no2 = input("Enter the second number: ")
print (int(no1)/int(no2))
else:
print ("Select a Valid function!")
This way you don't need to keep the list consistent with the list of signs that you implement.
As others have said change:
if sign != ["+","-","*","/"]:
to
if sign not in ["+","-","*","/"]:
to test for non-membership of a list.
You can also cut down on a lot of duplication in your code and avoid the if...elif statements by using a dictionary of operators like this:
import operator
ops = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
sign = input ("Enter the sign: ")
if sign not in ops:
print ("Select a Valid function!")
else:
print ("Let's Begin")
no1 = int(input("Enter the first number: "))
no2 = int(input("Enter the second number: "))
ans = ops[sign](no1, no2)
print(ans)
Python reads function input() as string.
Before passing it to my function for division, variables are typecasted into int using int().
If one variable is non-int (eg "a") then how to catch it?
def divideNums(x,y):
try:
divResult = x/y
except ValueError:
print ("Please provide only Integers...")
print (str(x) + " divided by " + str(y) + " equals " + str(divResult))
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
divideNums (int(firstVal), int(secondVal))
if __name__ == "__main__":
main()
How to handle typecast of firstVal / secondVal ?
You can use isdigit function to check if the input values are integer or not
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
if firstVal.isdigit() and secondVal.isdigit():
divideNums (int(firstVal), int(secondVal))
else:
print ("Please provide only Integers...")
You are right about using a try/except ValueError block, but in the wrong
place. The try block needs to be around where the variables are converted to
integers. Eg.
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
try:
firstVal = int(firstVal)
secondVal = int(secondVal)
except ValueError:
# print the error message and return early
print("Please provide only Integers...")
return
divideNums (firstVal, secondVal)