IndentationError: unindent does not match any outer indentation levels - python

File "first.py", line 37
elif(operation == "quadratic formula")
IndentationError: unindent does not match any outer indentation level
I really don't know what the problem is with my code. Can someone please help?
def add(var1, var2):
return var1 + var2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def mul(num1,num2):
return num1*num2
def equation1():
import math
a = int(raw_input("please enter your a in the equation: "))
b = int(raw_input("please enter your b in the equation: "))
c = int(raw_input("please enter your c in the equation: "))
d = b**2-4*a*c
if(d < 0):
print "This equation has no real solution"
elif(d == 0):
x = (-b+math.sqrt(b**2-4*a*c))/(2*a)
print "This equation has one solutions: ", x
else:
x1 = (-b+math.sqrt(b**2-4*a*c))/(2*a)
x2 = (-b-math.sqrt(b**2-4*a*c))/(2*a)
print "This equation has two solutions"
print "The first soluition: ", x1
print "And the second solution", x2
def main():
operation = raw_input("what do you want to do (+,-,/,*) or quadratic
formula? ")
if(operation != '+' and operation != '-' and operation != '/' and operation != '*' and operation != 'quadratic formula'):
print 'You must put a valid operation'
elif( operation == "quadratic formula" ):
equation1()
else:
var1 = int(raw_input("enter the first number: " ))
var2 = int(raw_input("enter the second number: "))
if(operation == '+'):
print (add(var1, var2))
elif(operation == '/'):
print (div(var1, var2))
elif(operation == '-'):
print (sub(var1, var2))

The following shows your code in my text editor with tabs and space characters made visible and shown in the color red. As you can see, it indicates that you're using a mixture of them in it—and that's confusing the Python interpreter. Best to stick with one or the other, although I think 4 spaces are the best (and most portable).
You may be able to configure you editor to automatically convert tabs into the right number of spaces for you.
Update:
Since you still seem to be having problems, here's a version of your code in which I have removed the tab characters so now its indentation is comprised exclusively of 4 space characters for each level. See if you have better luck with it.
def add(var1, var2):
return var1 + var2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def mul(num1,num2):
return num1*num2
def equation1():
import math
a = int(raw_input("please enter your a in the equation: "))
b = int(raw_input("please enter your b in the equation: "))
c = int(raw_input("please enter your c in the equation: "))
d = b**2-4*a*c
if(d < 0):
print "This equation has no real solution"
elif(d == 0):
x = (-b+math.sqrt(b**2-4*a*c))/(2*a)
print "This equation has one solutions: ", x
else:
x1 = (-b+math.sqrt(b**2-4*a*c))/(2*a)
x2 = (-b-math.sqrt(b**2-4*a*c))/(2*a)
print "This equation has two solutions"
print "The first soluition: ", x1
print "And the second solution", x2
def main():
operation = raw_input("what do you want to do (+,-,/,*) or quadratic formula? ")
if(operation != '+' and operation != '-' and operation != '/' and operation != '*' and operation != 'quadratic formula'):
print 'You must put a valid operation'
elif( operation == "quadratic formula" ):
equation1()
else:
var1 = int(raw_input("enter the first number: " ))
var2 = int(raw_input("enter the second number: "))
if(operation == '+'):
print (add(var1, var2))
elif(operation == '/'):
print (div(var1, var2))
elif(operation == '-'):
print (sub(var1, var2))

Related

Python Functions not being called. Only able to print the questions in my print statements

history = []
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
def main():
def summation():
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
first_num = str(input(":ype the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
print("The Previous result is: " + str(history()))
def exits():
print("Exiting...")
while True:
x = str(input("Type your option: "))
if x == "1" or x == "2" or x == "3" or x == "4":
break
if x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
else:
exits()
main()
The indentation of your while is wrong. It should be inside of your main function.
Try removing the main function and just let your script run the while loop.
Also break only during the input that you want to exit the loop. If nothing is after the loop, it exits the script; with your current logic, the while loop exits for every option, nothing is printed beyond your first line and your input prompt, then the main function gets ran, but nothing runs because the main function is actually empty (only defines other functions)
history = []
def summation():
global history
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
global history
first_num = str(input("Type the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
global history
print("The Previous result is: " + str(history))
def exits():
print("Exiting...")
while True:
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
x = str(input("Type your option: "))
if x == "4":
exits()
break
elif x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
Note: input() always returns a str type, so there's no reason to cast it

My program not showing question or taking inputs in Python

I made this simple Python Maths Quiz Program for some reason sometimes when it is supposed to ask a question it doesn't display the question or allow any input and just says it is incorrect. The problem doesn't happen every time I run the program just sometimes.
import random
def RandomNum():
import random
ran= random.randint(1,10)
return (ran)
def RanOperation():
import random
operation = ['+','-','x']
RanOp = random.choice(operation)
return (RanOp)
stop = False
while stop == False:
Name= input("Hello, what is your name?").title()
print("Hello,", Name, "Welcome to ARITHMETIC QUIZ")
score=0
for i in range(1, 11):
print(str(i)+".")
num1 = RandomNum()
num2 = RandomNum()
operation = RanOperation()
if operation == "+":
ans = num1+num2
elif operation == "-":
if num1 > num2:
ans = num1-num2
elif num2>num1:
ans = num2-num1
elif operation == "x":
ans = num1*num2
if num1 > num2:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num1+operation+num2+"=")))
elif num2 > num1:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num2+operation+num1+"=")))
if Answer == ans:
print("Correct!")
score += 1
elif Answer != ans:
print("The correct answer is", ans)
print("Sorry this is incorrect!")
length = int(len(Name))
print("You got", score, "correct out of 10,", Name)
File1 = open('Class_Scores.txt','a')
File1.write("\n %-20s %10d" %(Name , score))
File1.close()
Ask = input("Do you want to continue? Y/N").upper()
if Ask == "N":
stop = True
elif Ask == "Y":
stop = False
Your input() line only runs in two situations:
if num1 > num2:
and
elif num2 > num1:
What happens when num1 and num2 are the same? You won't enter the if block, because num1 > num2 is False; And you won't enter the elif block, because num2 > num1 is also False.
That means the input() won't run at all;
Your code's problem is that you do not always call the input:
if num1 > num2:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num1+operation+num2+"=")))
elif num2 > num1:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num2+operation+num1+"=")))
if num1 == num no input is done and the one from before is used (again).
You can solve it by changing one of them to >= or use an additional else: ....
You can shorten/improve your code a lot if you
do not import random multiple times
use a dictionary to decide which function to call (reduces if .. elif .. else
use input validation to avoid crashing on bad input
use string.format() or even better f-strings instead of python 2.7 % formatting
use with open(...) for file operations
structure the code with some more functions
import random
def RanOperation():
return random.choice(['+','-','x'])
def plus():
# get both numbers with one random call
a,b = random.choices(range(1,11),k=2)
return (a,b,a+b)
def minus():
# only operation where a > b matters to not get negative results
# sorting (low to high) and choosing b,a ensures a is at least b or more
# the other operations are cummutative so its better to leave then unsorted
# to train 8x4 as as well as 4x8
b,a = sorted(random.choices(range(1,11),k=2) ) # a > b
return (a,b,a-b)
def mult():
a,b = random.choices(range(1,11),k=2)
return (a,b,a*b)
def get_answer(a,operation,b):
while True:
try:
k = int(input( "{} {} {} = ".format(a,operation,b)))
return k
except Exception:
print("Input a valid number.")
Usage:
# call which function for what ops?
# using mapper["+"]() --> calls the plus() function - this reduces if/else's
mapper = {"-": minus, "+":plus, "x":mult}
while True:
Name= input("Hello, what is your name?").title()
print("Hello,", Name, "Welcome to ARITHMETIC QUIZ")
score=0
for i in range(10):
print(str(i+1)+".")
operation = RanOperation()
a,b,ans = mapper[operation]()
answer = get_answer(a,operation,b)
if answer == ans:
print("Correct!")
score += 1
else:
print("The correct answer is {:>10d}".format(ans))
print("Sorry this is incorrect!")
length = int(len(Name))
print("You got", score, "correct out of 10,", Name)
with open('Class_Scores.txt','a') as File1:
File1.write("\n -{:20s} {:10d}".format(Name , score))
Ask = input("Do you want to continue? Y/N").upper()
if Ask == "N":
break
Output:
Hello, what is your name?Enya
Hello, Enya Welcome to ARITHMETIC QUIZ
1.
10 - 5 = 5
Correct!
2.
8 - 6 = 9
The correct answer is 2
Sorry this is incorrect!
3.
10 - 2 = 8
Correct!
# ...snipp 4-9...
10.
4 - 4 = 0
Correct!
You got 9 correct out of 10, Enya
Do you want to continue? Y/Nn

stuck with a simple python program "elif"

Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

Python : IndentationError: expected an indented block

#Returns the sum of num1 and num2
while True:
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
#*, -, /, +
#remember brackets work like normal
def main ():
operation = input("What type of calculation would you like to make? +,-,/,*")
if(operation != '+' and operation != '-' and operation != '/' and operation != '*'):
#operation invalid
print("To continue enter a vaild operation")
else:
var1 = int(input("Enter num1:"))
var2 = int(input("Enter num1:"))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '*'):
print(mul(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
#Restarts the calculator
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ("Invalid input.")
if answer == "y":
continue
else:
print ('Goodbye')
break
main(add)
Hi, beginner here. I am getting IndentationError: unindent does not match any outer indentation level. Any help would be nice. If I put the continue down any further, I get IndentationError: expected an indented block. Not sure what to do.
I got it on
File "", line 24
continue
^
IndentationError: expected an indented block
Your function should be like the below
def main ():
operation = input("What type of calculation would you like to make? +,-,/,*")
if(operation != '+' and operation != '-' and operation != '/' and operation != '*'):
#operation invalid
print("To continue enter a vaild operation")
else:
var1 = int(input("Enter num1:"))
var2 = int(input("Enter num1:"))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '*'):
print(mul(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
#Restarts the calculator
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ("Invalid input.")
if answer == "y":
continue
else:
print ('Goodbye')
break
There were numerous misaligned chunks of code that I corrected for you. Also corrected other errors as well. Try to avoid while True: loops altogether as your program can easily get stuck in one and cause unintended consequences.
# Returns the sum of num1 and num2
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
# *, -, /, +
# remember brackets work like normal
def main():
operation = raw_input("What type of calculation would you like to make? +,-,/,*")
if (operation != '+' and operation != '-' and operation != '/' and operation != '*'):
# operation invalid
print("To continue enter a vaild operation")
else:
var1 = int(raw_input("Enter num1:"))
var2 = int(raw_input("Enter num1:"))
if (operation == '+'):
print(add(var1, var2))
elif (operation == '/'):
print(div(var1, var2))
elif (operation == '*'):
print(mul(var1, var2))
elif (operation == '-'):
print(sub(var1, var2))
# Restarts the calculator
main()
answer = raw_input('Run again? (y/n): ')
while answer == "y":
main()
answer = raw_input('Run again? (y/n): ')
The error occurs due to bad indentation. In Python, bad indentation means odd number of spaces. For example, 0, 1 or 3 spaces is bad indentation.
For example
def main():
pass
Is valid indentation, as the statement pass under main function is having 4 spaces; instead if the statement pass is having 0, 1 or 3 spaces under main. Valid indentation includes even number of spaces 2, 4 etc.
Well, in short, indentation in Python should be 2 or 4 spaces.

Python - looping

I am trying to build a simple calculator. I just want the user to enter two numbers and an operation, then for the calculation to be shown, then to loop back to entering two numbers again. If the user enters an operation that is not recognized I want to loop back to 'enter operation'.
Why is this not working:
def add (a,b):
return a + b
def minus (a,b):
return a - b
def multi (a,b):
return a * b
def div (a,b):
return a / b
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
def opPic():
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic ()
print ("Hello User")
numPic()
opPic()
You have a few bugs. First, num1 and num2 are local to numPic--not
global. So you need to return them to the caller, and the caller has to pass
them to opPic():
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic (num1, num2)
num1, num2 = numPic()
opPic (num1, num2)
To make it loop-based, you could do something like:
def opPic(num1, num2):
while True:
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
continue
break
Hopefully, you can figure out the other bit on your own, as this looks like a school assignment.
The num1 and num2 you define in numPic are local to that function. You need to return them and pass them to the opPic function for them to be used.
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
#the same code as before
#except changing opPic() to opPic(num1, num2)
print ("Hello User")
num1, num2 = numPic()
opPic(num1, num2)
There are better ways of doing what you seem to be aiming for though. You haven't actually used a loop and have used recursion instead.

Categories