python calculator program [closed] - python

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I wrote a simple calculator program by using functions, I don't know what exactly wrong with this code, its showing error. I did possible steps to debug this, but I couldn't.
#!/usr/bin/python
def add():
print "Enter the two numbers to Add"
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
c = A + B
def sub():
print "Enter the two numbers to Subtract"
A=int(raw_input("Enter A:"))
B=int(raw_input("Enter B:"))
c = A - B
def Mul():
print "Enter the two numbers to Multiply"
A=int(raw_input("Enter A:"))
B=int(raw_input("Enter B:"))
c = A * B
def Div():
print "Enter the two number to Divide"
A=float(raw_input("Enter A:"))
B=float(raw_input("Enter B:"))
c = A / B
print "1: ADDITION"
print "2: SUBTRACTION"
print "3: MULTIPLICATION"
print "4: DIVITION"
print "0: QUIT"
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
add(c):
elif CHOICE == "2":
print 'SUBTRACTING TWO NUMBERS:'
sub(c):
elif CHOICE == "3":
print 'MULTIPLYING TWO NUMBERS:'
Mul(c):
elif CHOICE == "4":
print "DIVIDEING TWO NUMBERS"
Div(c):
elif CHOICE == "0":
return 0:
else
Print "The value Enter value from 1-4"
Error:
File "cal_fun.py", line 44
if CHOICE == "1":
^
SyntaxError: invalid syntax

I've have tried to cover all of the problems with your code, of which there are numerous.
Starting with syntax errors:
# true needed a captial T
while True:
# Brackets were mismatched
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
# Calling a function shouldn't have trailing :
add(c)
elif CHOICE == "2":
print 'SUBTRACTING TWO NUMBERS'
# Calling a function shouldn't have trailing :
sub(c)
elif CHOICE == "3":
print 'MULTIPLYING TWO NUMBERS'
# Calling a function shouldn't have trailing :
Mul(c)
elif CHOICE == "4":
print "DIVIDEING TWO NUMBERS"
# Calling a function shouldn't have trailing :
Div(c)
elif CHOICE == "0":
# can only return from a function use exit here instead
exit()
# else needs a trailing :
else:
# No capital P for print
print "The value Enter value from 1-4"
The code now has no syntax errors but still has many problems.
You pass c to your function, c is never initialized, what is c?
Your function doesn't take arguments def add(): (even though pass the mysterious c value).
Your function doesn't print or return the result it just computes.
You store CHOICE as an int are do comparisons with strings so the else case is always executed and there is no way to exit the loop (infinite looping).
Fixed code:
#!/usr/bin/python
def add():
print "Enter the two numbers to Add"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A + B
def sub():
print "Enter the two numbers to Subtract"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A - B
def mul():
print "Enter the two numbers to Multiply"
A=int(raw_input("Enter A: "))
B=int(raw_input("Enter B: "))
return A * B
def div():
print "Enter the two number to Divide"
A=float(raw_input("Enter A: "))
B=float(raw_input("Enter B: "))
return A / B
print "1: ADDITION"
print "2: SUBTRACTION"
print "3: MULTIPLICATION"
print "4: DIVITION"
print "0: QUIT"
while True:
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION "))
if CHOICE == 1:
print 'ADDING TWO NUMBERS:'
print add()
elif CHOICE == 2:
print 'SUBTRACTING TWO NUMBERS'
print sub()
elif CHOICE == 3:
print 'MULTIPLYING TWO NUMBERS'
print mul()
elif CHOICE == 4:
print "DIVIDEING TWO NUMBERS"
print div()
elif CHOICE == 0:
exit()
else:
print "The value Enter value from 1-4"
The code is now functional.
Output:
1: ADDITION
2: SUBTRACTION
3: MULTIPLICATION
4: DIVITION
0: QUIT
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 1
ADDING TWO NUMBERS:
Enter the two numbers to Add
Enter A: 2
Enter B: 5
7
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 2
SUBTRACTING TWO NUMBERS
Enter the two numbers to Subtract
Enter A: 2
Enter B: 5
-3
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 3
MULTIPLYING TWO NUMBERS
Enter the two numbers to Multiply
Enter A: 2
Enter B: 5
10
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 4
DIVIDEING TWO NUMBERS
Enter the two number to Divide
Enter A: 2
Enter B: 5
0.4
ENTER THE CORRESPONDING NUMBER FOR CALCULATION 0
Functional but not perfect, for instance no error handling for erroneous input.

You're missing an end parenthesis on the previous line (a common cause of mysterious syntax errors), change:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
to
CHOICE = int(raw_input("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
This is not the only syntax error in the program- you end many lines with : when you shouldn't, like:
add(c):
sub(c):
Mul(c):
Div(c):
You also
have no : for an else statement (it's required)
capitalize Print when it should be print
have a return statement outside of any function
There are also errors that are not syntax errors:
misspell True as true
compare CHOICE, an int, to a string like "1" or "2"
are passing a non-existent variable c to a function that takes no arguments

You are passing a variable c to your functions add() sub() etc. but they are defined to take no arguments.

on top of the syntax errors already mentioned what I think you actually want is for each function to return values to the main programme loop, which will then display them:
def add():
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
return A + B
...
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
answer = add()
print answer
...
or alternatively make the programme shorter by inputting A and B in the main loop then passing those as parameters to the calculating functions:
def add():
return A + B
...
while true:
CHOICE = int(raw_input(("ENTER THE CORRESPONDING NUMBER FOR CALCULATION"))
A=int(raw_input("Enter A:"))
B=int(raw_input("ENter B:"))
if CHOICE == "1":
print 'ADDING TWO NUMBERS:'
answer = add(A, B)
print answer
...

Related

Python If Statements - Display numeric Results

I am writing a python code that returns me the larger of two inputs.
def bigger_num(a, b):
if a < b:
print ("First number is smaller than the second number.")
elif a > b:
print ("First number is greater than the second number.")
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
print(bigger_num(a, b))
Result:
Enter first number: 19
Enter second number : 9
First number is greater than the second number.
None
How do I display the numeric result (a/b) in the print?
Ideal solution example: First number, 19 is greater than the second number
Also, is there a way to remove none from the print result?
You can use the format() method or simply concatenate the number to display it. To remove the None, just call the function without the wrapping it with a print() because you print the output inside the function
def bigger_num(a, b):
if a < b:
print ("First number, {0} is smaller than the second number.".format(a))
elif a > b:
print ("First number, {0} is greater than the second number.".format(a))
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
bigger_num(a, b)

Incorrect if-else statements

I've been trying to write a function that will ask for a number between 1-11 and will randomly choose a number and will compare between them.
I can't figure out why no matter what number I type in (equals or smaller or bigger) it will always type the "Your number is less" message.
def loto():
_number = int(input("Enter any number between 1-10: "))
import random
for x in range(1):
print ("Python chose: " + str(random.randint(1,11)))
if ("_number" == "random"):
print ("You Won! :)")
if ("_number" < "random"):
print ("Your number is less")
if ("_number" > "random"):
print ("Your number is more")
else:
print ("You Lost :(")
loto()
I'm using Python 3.
Thanks:)
Your first problem is that you're comparing the strings "_number" and "random". ASCIIbetically (or, rather, Unicoderifically), "_number" < "random", because the _ character is #95 and the r character is #114.
If you want to compare two variables, you just refer to the variables, not strings that happen to be the same as the names of those variables.
Your second problem is that random isn't your random number, it's the module you used to create that number. And, more seriously, you aren't storing that number anywhere—you're just converting it to a string to print it out and then throwing it away.
Your third problem is that you need to change those ifs to elifs. Otherwise, the You Lost message gets printed whenever _number > random is not true, instead of only whenever all of the three comparisons are not true.
Putting that all together:
choice = random.randint(1,11)
for x in range(1):
print ("Python chose: " + str(choice))
if (_number == choice):
print ("You Won! :)")
elif (_number < choice):
print ("Your number is less")
elif (_number > choice):
print ("Your number is more")
else:
print ("You Lost :(")
Of course there's no way to actually lose your game—one of the three conditions is always going to be true. (If you were using complex numbers, or floats including NaN, you could input a number that wasn't comparable in any way to the selected one, but you're not.)
While we're at it:
There's no reason to name your variable _number instead of number.
That for x in range(1): loop doesn't do anything useful—it loops exactly once, setting x to 0, which you never use.
You don't need parentheses around your conditions.
You shouldn't import modules in the middle of a function like that except in special cases where you need unusual things like lazy loading.
You should follow PEP 8 style, or at least pick a consistent style to follow.
It's simpler to just pass multiple arguments to print, or to use string formatting, than to manually convert things to strings and concatenate them.
So:
import random
def loto():
number = int(input("Enter any number between 1-10: "))
choice = random.randint(1, 11)
print("Python chose:", choice)
if number == choice:
print("You Won! :)")
elif number < choice:
print("Your number is less")
elif number > choice:
print("Your number is more")
else:
print("You Lost :(")
loto()
You were comparing strings not variables, you need to remove quotes, and you not saved random number into a variable. The for loop is making one repetition only, you can remove it.
Update your cod like this:
import random
def loto():
_number = int(input("Enter any number between 1-10: "))
rand_number = random.randint(1,11) # can't had the same name as random
if (_number == rand_number):
print ("You Won! :)")
elif (_number < rand_number):
print ("Your number is less")
elif (_number > rand_number):
print ("Your number is more")
else:
print ("You Lost :(")
loto()

Looking for a more efficient way to write my python program

In my Trigonometry class, we were assigned to find the discriminant and conic section of an equation..
I wrote a function that calculates the discriminant, and then based on the value of the discriminant, prints the conic section...
I'm just curious if there is a better, more effective way to write this:
def disc():
a_disc = raw_input("Please enter the value of A: ")
b_disc = raw_input("Please enter the value of B: ")
c_disc = raw_input("Please enter the value of C: ")
disc = b_disc**2-4*(a_disc)*(c_disc)
print ("The discriminant is: %s") % (disc)
if disc < 0:
if a_disc != c_disc:
print ("The conic is an Ellipse!")
elif a_disc == c_disc:
print ("The conic is a Circle!")
elif disc > 0:
print ("The conic is a Hyperbola!")
elif disc == 0:
print ("The conic is a Parabola!")
else:
print ("Something went wrong...")
disc()
I don't fully understand using arguments inside of functions, but I feel like doing something like:
def disc(a,b,c):
would be the more clean approach I guess.
I would really appreciate any feedback anyone has to offer. Thanks in advance!
Yeah you could move disc into a function that just calculates the value, and then have all of the input and output logic as separate code. Some of your if statements are redundant too. Here's a slightly simpler version:
def disc(a, b, c):
return b ** 2 - 4 * a * c
a = raw_input("Please enter the value of A: ")
b = raw_input("Please enter the value of B: ")
c = raw_input("Please enter the value of C: ")
val = disc(int(a), int(b), int(c))
print ("The discriminant is: %s") % (val)
if val == 0:
print ("The conic is a Parabola!")
elif val > 0:
print ("The conic is a Hyperbola!")
elif a != c:
print ("The conic is an Ellipse!")
else:
print ("The conic is a Circle!")

Why is my code returning my else: statement?

When i run through my calculator, it gives the following results;
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
Enter first number: 1
Enter second number: 5
Invalid! Input
Can anyone explain to me why it is responding with my else if statement, i'v checked the code many times, plus i have copied paste the code directly, as is, after much frustration, yet it yields the same result?
# A simple calculator that can add, subtract, multiply and divide.
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# Take input from the user
print ("Select operation.")
print ("1.Add")
print ("2.Subtract")
print ("3.Multiply")
print ("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num,"+",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")
You're using Python 2, where input() evaluates what is entered; so when you enter 2, for instance, choice contains the int 2. Try entering '2' into your current code (including the quotes). It'll act as you expect entering 2 to act.
You should use raw_input() on Python 2 and input() on Python 3. If you want your code to be compatible with both, you can use the following code, after which you can always just use input():
try:
input = raw_input # Python 2
except NameError: # We're on Python 3
pass # Do nothing
You can also use the six package, which does this and many other Python 2/3 compatibility things.
In Python 3 input() does what raw_input() does in Python 2, and Python 2's input() is gone.

Returning value from function

I am new to Python (and programming) and was just experimenting by making a program to convert decimals. I have defined a function as I wish to reuse it later in the program, but I am having a problem carrying the result of the function to the rest of the program.
print "For decimal to binary press B"
print "For decimal to octal press O"
print "For decimal to hexadecimal press H"
def checker(n):
choice = n
while choice not in ("B", "O", "H"):
print "That is not a choice."
choice = str.upper(raw_input("Try again: "))
else:
return choice
firstgo = str.upper(raw_input("Enter your choice: "))
checker(firstgo)
if choice == 'B':
n = int(raw_input("Enter the number to be converted to binary: "))
f = bin(n)
print n, "in binary is", f[2:]
elif choice == 'O':
n = int(raw_input("Enter the number to be converted to octal: "))
f = oct(n)
print n, "in octal is", f[1:]
elif choice == 'H':
n = int(raw_input("Enter the number to be converted to hexadecimal: "))
f = hex(n)
print n, "in hexadecimal is", f[2:]
You need to save the returned value from the function.
Do something like this:
choice = checker(firstgo)
Then you save the result coming back from your function.
Every variable you declare, is only available at the scope of the function you declare it,
so when you use choice outside of the function checker, your program does not know what choice is, and that's why it won't work.
Instead of:
checker(firstgo)
You need:
choice = checker(firstgo)
As you have it, the value returned by checker is lost. The choice variable defined by checker is not the same variable as the one defined outside it. You can use the same names for different variables defined within different scopes. This way you don't have to worry that the same name may be already used somewhere else in the program.

Categories

Resources