My first program - python

I've been doing a lot lessons on Code Academy, but I get frustrated since some of the compilers reject answers that return the same results. So, I decided to breakaway for a bit and create my own program with the tools that I have learned which is a calculator. It doesn't run correctly. When it is at the menu the if/elif/else statements do not work. The program seems to ignore the input . So, here is my first program code...
import math
user_choice=(">>")
def add():
print "What two numbers would you like to add?"
a= int(raw_input(user_choice))
b= int(raw_input(user_choice))
c= a + b
print c
def sub():
print "What two numbers would you like to subtract?"
a=int(raw_input(user_choice))
b=int(raw_input(user_choice))
c=a-b
print c
def mult():
print "What two numbers would you like to multiply?"
a=int(raw_input(user_choice))
b=int(raw_input(user_choice))
c= a*b
print c
def div():
print "What two numbers would you like to divide?"
a=int(raw_input(user_choice))
b=int(raw_input(user_choice))
c=a/b
print c
def exp():
print "What number would you like to power?"
a=int(raw_input(user_choice))
print "By what number would you like it to be powered to?"
b=int(raw_input(user_choice))
c= math.pow(a,b)
print c
def square():
print "What number would you like to square root?"
a=int(raw_input(user_choice))
b=math.sqrt(a)
print b
print "+---------------------------+"
print "| Welcome to my basic |"
print "| calculator! |"
print "| |"
print "|What would you like to do? |"
print "| |"
print "|1: Addition |"
print "|2: Subtraction |"
print "|3: Multiplication |"
print "|4: Division |"
print "|5: Exponents |"
print "|6: Square Root |"
print "|7: Quit |"
print "| |"
print "+---------------------------+"
if int(raw_input(user_choice)) == "1":
add()
elif int(raw_input(user_choice)) == "2":
sub()
elif int(raw_input(user_choice)) == "3":
mult()
elif int(raw_input(user_choice)) == "4":
div()
elif int(raw_input(user_choice)) == "5":
exp()
elif int(raw_input(user_choice)) == "6":
square()
elif int(raw_input(user_choice)) == "7":
exit()
else:
print "Sorry, I didn't understand your entry.Try entering a value 1-7"
there is no "if error" code yet, but I am just adamant about getting it to work. All of the functions work. Just can't get the options to work.

int(rawinput()) will return an integer, which will not be == to a string like "1". Remove the int() from them and it should work.

Change
if int(raw_input(user_choice)) == "1":
To
if int(raw_input(user_choice)) == 1:
Number should not be quoted, only literal string should.
A suggestion, you can get the input just once, and then do the if/elif/else conditional test, for example:
option = int(raw_input(user_choice))
print "You choose %d" % option
if option == 1:
add()
elif option == 2:
sub()
......

Besides the things others have pointed out, I will leave here how I personally would implement it. This surely isn't the best way, but I hope it might give you some idea (which you either will adopt or reject) and some points where you can investigate further in order to broaden your python skills:
class Operation:
def __init__(self, f, argc):
#f is the function to use, argc the number of arguments it takes
self.f = f
self.argc = argc
def __call__(self):
#read in the args
args = [int(input('>> ')) for _ in range (self.argc)]
#print out the result of the function passed in the ctor
print(self.f(*args))
#your operations keyed to the options of your menu
operations = {'1': Operation(lambda a, b: a + b, 2),
'2': Operation(lambda a, b: a - b, 2),
'3': Operation(lambda a, b: a * b, 2),
'4': Operation(lambda a, b: a / b, 2),
'5': Operation(lambda a, b: a ** b, 2),
'6': Operation(lambda a: a ** .5, 1)}
while True:
print('''
1: Addition
2: Subtraction
3: Multiplication
4: Division
5: Exponentiation
6: Square root
7: Quit''')
choice = input('Your choice: ') #raw_input for py2
if choice == '7': break
try: operations[choice]()
#KeyError means choice is not in the dict
except KeyError: print('Unkown option')
#Something else went wrong, division by zero, etc
except Exception as e: print('Something went horribly wrong: {}'.format(e))

Related

don't matter what the input is it won't get to the "else if" statement [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
my output is the menu() function prints only all over again and again, don't matter what the input is it won't get to the "else if" statement #Python...........................................................................
def menu():
#print what options you have
print ("Welcome to calculator.py")
print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) exposion")
print ("6) Quit calculator.py")
print (" ")
return input ("Choose your option: ")
# this adds two numbers given
def add(a,b):
print (a, "+", b, "=", a + b)
# this subtracts two numbers given
def sub(a,b):
print (b, "-", a, "=", b - a)
# this multiplies two numbers given
def mul(a,b):
print (a, "*", b, "=", a * b)
# this divides two numbers given
def div(a,b):
print (a, "/", b, "=", a / b)
# HERE IS MY CODE
def dinami(base, exponent):
if y == 1:
print (base, "*" ,power,"(",base,",", exponent," - 1) = ",base)
if y != 1:
print (base, "*" ,power,"(",base,",", exponent," - 1) = ",base * power(base, exponent - 1))
# NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
loop = 1
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add this: "),input("to this: "))
print ("hi")
elif choice == 2:
sub(input("Subtract this: "),input("from this: "))
elif choice == 3:
mul(input("Multiply this: "),input("by this: "))
elif choice == 4:
div(input("Divide this: "),input("by this: "))
elif choice == 5:
dinami(input("expone this: "),input("to this: "))
elif choice == 6:
loop = 0
print ("Thankyou for using calculator.py!")
input() returns a string, so if you're comparing int with string i.e '1' == 1, which always returns False
https://docs.python.org/3/library/functions.html#input

IndentationError: unindent does not match any outer indentation levels

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))

what's this indentationError?

print("Welcome to calculator.py")
print ("your options are :")
print ("")
print ("1) Addition")
print ("2)Subtraction")
print ("3) Multiplication")
print ("4)Division")
print ("Choose your option")
#this adds 2 numbers given
def add (a,b):
print(a, "+" ,b, "=" ,a+b)
#this subtracts 2 numbers given
def sub (a,b):
print(a, "-" ,b, "=" ,b-a)
#this multiplies 2 numbers given
def mul(a,b):
print(a, "*" ,b, "=" ,a*b)
#this divides 2 numbers given
def div(a,b):
def div(a, "/" ,b, "=" ,a/b)
#NOW THE PROGRAM REALLY STARTS ,AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add (input("Add this: "),input ("to this: "))
elif choice == 2:
sub(input("Subtract this: "),input ("from this: "))
elif choice == 3:
mul (input("Multiply this: "),input ("by this: "))
elif choice == 4:
div(input("Divide this: "),input ("by this: "))
elif choice ==5:
loop = 0
print ("Thank you for using calculator.py")
this is my code and the error is:
print(a, "+" ,b, "=" ,a+b)
^
IndentationError: expected an indented block
Process finished with exit code 1
and many others can anyone help me find all the errors???
can anyone help me???
In python, there are identation rules to know how the program should execute commands. This is the way python recognize when a function, a conditional statement or for, while statements start and end. In your case, for example, the elif statement should be at the same "level" as your initial if statement start:
print("Welcome to calculator.py")
print ("your options are :")
print ("")
print ("1) Addition")
print ("2)Subtraction")
print ("3) Multiplication")
print ("4)Division")
print ("Choose your option")
#this adds 2 numbers given
def add (a,b):
print(a, "+" ,b, "=" ,a+b)
#this subtracts 2 numbers given
def sub (a,b):
print(a, "-" ,b, "=" ,b-a)
#this multiplies 2 numbers given
def mul(a,b):
print(a, "*" ,b, "=" ,a*b)
#this divides 2 numbers given
def div(a,b):
def div(a, "/" ,b, "=" ,a/b)
#NOW THE PROGRAM REALLY STARTS ,AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add (input("Add this: "),input ("to this: "))
elif choice == 2:
sub(input("Subtract this: "),input ("from this: "))
elif choice == 3:
mul (input("Multiply this: "),input ("by this: "))
elif choice == 4:
div(input("Divide this: "),input ("by this: "))
elif choice ==5:
loop = 0
In python blocks are defined by indentation. After defining function you should have a indentation(tab).
Pretty much all of the indentation is wrong, not just that one place:
print("Welcome to calculator.py")
print("your options are :")
print("")
print("1) Addition")
print("2)Subtraction")
print("3) Multiplication")
print("4)Division")
print("Choose your option")
#this adds 2 numbers given
def add(a,b):
print(a, "+", b, "=" , a+b)
#this subtracts 2 numbers given
def sub(a,b):
print(a, "-", b, "=" , b-a)
#this multiplies 2 numbers given
def mul(a,b):
print(a, "*", b, "=" , a*b)
#this divides 2 numbers given
def div(a,b):
print(a, "/", b, "=", a/b)
#NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add this: "), input("to this: "))
elif choice == 2:
sub(input("Subtract this: "), input("from this: "))
elif choice == 3:
mul(input("Multiply this: "), input("by this: "))
elif choice == 4:
div(input("Divide this: "), input("by this: "))
elif choice ==5:
loop = 0
print ("Thank you for using calculator.py")

Making selections linked to definitions in python

So how this was thought to work was: Start script, make a selectable menu so the user can select what to do (add, divide, multiply and so forth). But I can't seem to figure out how to do it.
Something like this:
Press 1 for add
Press 2 for multiply
and so forth. I have just made the add definition as of now, but I plan on using the same template when doing multiply and divide etc.
# Calculations
def add(a, b):
print "Write the numbers to add"
adda = int(raw_input("First number: "))
addb = int(raw_input("Second number: "))
print "Adding %d and %d together" % (a, b)
print "%d + %d="
return a + b
# Choose what to do
print "Write what you want do do: add, subtract, multiply or divide"
EDITED TO:
# Calculations
def math(command):
print "Write the numbers to %s" % command
a = int(raw_input("First number: "))
b = int(raw_input("Second number: "))
if command == 'add':
return a + b
elif command == 'subtract':
return a - b
elif command == 'multiply':
return a * b
elif command == 'divide':
return a / b
else:
return 'not a valid command'
# Choose what to do
print "Write what you want to do.. add, subtract, multiply or divide"
command = raw_input("Do you want to add, multiply, divide or subtract: ")
Problem here is that it won't print out the value for return a + b for example, I don't have any link to the def math(), so I don't think it will run.. any way to solve this?
You should use raw_input to find out what the user wants to do, similar to how you get the numbers in the add() function.
# Choose what to do
choice = raw_input("Write what you want do do: add, subtract, multiply or divide")
if choice == 'add':
add()
However because in add() you ask for the numbers the user wants to add, you do not want to call add() with parameters, so change
def add(a, b):
to
def add():
Later, when you have the other functions implemented as well you can do something like
# Choose what to do
choice = raw_input("Write what you want do do: add, subtract, multiply or divide")
if choice == 'add':
add()
elif choice == 'subtract'
subtract()
elif choice == 'multiply'
multiply()
elif choice == 'divide'
divide()
else:
print 'not a valid choice'
i plan on using the same template when doing multiply and divide etc.
In that case you could do something like this
def dostuff(command):
print "Write the numbers to %s" (command)
a = int(raw_input("First number: "))
b = int(raw_input("Second number: "))
if command == 'add':
return a + b
elif command == 'subtract':
return a - b
elif command == 'multiply':
return a * b
elif command == 'divide':
return a / b
else:
return 'not a valid command'
# Choose what to do
command = raw_input("Write what you want do do: add, subtract, multiply or divide")
print dostuff(command)

How to move out of function

i am novice to python and i have stuck at one point, though its a simple program
I have used 'Return False' to move out of the function but i want to move out of my function completely. How it can be done.
Also if i want to run this script from python shell, how it can be done.
def menu():
print "calculator using functions"
print "Choose your option:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
return input ("Choose your option: ")
def add(a,b):
print a, "+", b, "=", a + b
print " Do you want to continue: "
decide=raw_input("yes or no: ")
if decide== "no" or decide== 'n':
print(" You have exited ")
return False
elif decide=='yes' or decide== 'y':
menu()
else:
print "wrong choice!!!"
return False
# this subtracts two numbers given
def sub(a,b):
print b, "-", a, "=", b - a
# this multiplies two numbers given
def mul(a,b):
print a, "*", b, "=", a * b
# this divides two numbers given
def div(a,b):
print a, "/", b, "=", a / b
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add first No: "),input("Add second No: "))
elif choice == 2:
sub(input("Add first No: "),input("Add second No: "))
elif choice == 3:
mul(input("Add first No: "),input("Add second No: "))
elif choice == 4:
div(input("Add first No: "),input("Add second No: "))
elif choice == 5:
loop = 0
print "End of program!"
You want to use exit. It exits from the program.
import sys
def spam():
.
.
.
if some_condition:
sys.exit(0) # exits from the program
.
.
.
You don't have to explicitly return anything to exit a function. When the interpreter reaches the end of the function block, the function exits.
On the command line type:
python myprogram.py
to run the program from prompt, if you want to use a specific python shell (other than bash or cmd) then you need to look to the documentation of that specific shell (e.g http://www.dreampie.org/).
To exit from a function use:
return
To exit from a program use:
import sys
sys.exit(0)

Categories