to display the outputs of following arithmetic operations on two numbers - python

Write a python program to display the outputs of following arithmetic operations on two numbers,which is accepted from user side ? a)Addition b)Subtraction c)Multiplication d)Division//
i wrote this code but it is not working
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ko= input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ko == '+':
result = a + b
elif ko == '-':
result = a - b
elif ko == '*':
result = a * b
elif ko == '/':
result = a / b
else:
print("Error")
print(num1, ko , num2, ":", result)
can anybody please tell me what i did wrong or post the correct code

Firstly, the first line of your program isn't indented properly - You need to remove the indentation before the first line.
Here's a guide to proper indentation in python: https://docs.python.org/2.0/ref/indentation.html
Secondly, the variables that you call in the final print function do not exist. "num1" and "num2" aren't defined - you need to use "a" and "b", because that's what you name the return values of the input functions you call in the beginning of the program. So you can either change "num1" and "num2" to "a" and "b", or vice versa.
The final code would look something like this:
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ko = input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ko == '+':
result = a + b
elif ko == '-':
result = a - b
elif ko == '*':
result = a * b
elif ko == '/':
result = a / b
else:
print("Error")
print(a, ko, b, ":", result)
Also, while programming in any language, it's advised to use descriptive names for variables - It might take some extra typing, but it will save a lot of hassle in bigger and more complex programs, and also it's a good practice.
Finally, this program (even though it gets the job done), isn't the most efficient or beginner-friendly solution for a calculator program. Here are some resources to help you understand it:
"Building a Basic Calculator | Python ": https://www.youtube.com/watch?v=HBbrSDGGOkw
or, if you prefer reading:
https://www.digitalocean.com/community/tutorials/how-to-make-a-calculator-program-in-python-3
I'd also like to tell you that reading the error messages you get in the console would've helped you understand the problem better, and maybe even come up with a solution, but we're here to help you :)

The error was in your last print statement...num1 and num2 should replace as a and b.
So the last line should be:
print(a, ko , b, ":", result)

Related

making calculator in python, is this approach sensible?

I trying to learn to write in Python and am attempting to making a calculator. For this I am using an input to choose which type of calculation and then inputs for the numbers to be calculated.
print ("1. add ; 2. subtract ; 3. multiply ; 4. divide " )
print ("wat is your choise")
choise = input()
if choise == 1 :
num_1_1 = input()
num_2_1 = input()
anwsr_add = (num_1_1 + num_2_1)
print (anwsr_add)
and repetition for the rest of the options.
This however returns that anwsr_add can't be printed because it is not defined. It leads me to believe the second inputs are not valid, giving nothing equal to anwsr_add.
Is there a extra code for these input functions within an if stream or am I completely of track with this approach?
This depends on what version of python you are using.
If you are using python 3, then input() is returns a type of 'str', which leads to your error. To test this theory, try print(type(choice)) and see what type it returns. If it returns str, then there is your culprit. If not, get back to us so we can continue to debug. I've posted my approach to your problem below in python 3 just so you have a reference in case I am unable to reply. Please feel free to ignore it if you would like to write it all on your own.
choice = int(input('Enter 1 to add, 2 to subtract, 3 to multiply, 4 to divide\n'))
if 1 <= choice <= 4:
num1 = int(input('What is the first number? '))
num2 = int(input('What is the second number? '))
if choice == 1:
answer = num1 + num2
elif choice == 2:
answer = num1 - num2
elif choice == 3:
answer = num1 * num2
elif choice == 4:
# In python 3, the answer here would be a float.
# In python2, it would be a truncated integer.
answer = num1 / num2
else:
print('This is not a valid operation, goodbye')
print('Your answer is: ', answer)
The main issue I found is you are comparing a char data type to an int data type. When you ask for input from the user, it is stored as a character string by default. Character strings cannot be compared to integers, which is what you are trying to do with your if block. If you wrap the input in an int() call it will convert the char to an int data type, and can then be properly compared with your == 1 statement. Additionally, within your if statement you call input() twice, and it will also give you a character string. This means if you input 1 and 1, you will get 11 out (like a + b = ab). To fix this, also wrap those input() statements with int() calls. I fixed these problems in the code below:
choice = int(input())
if choice == 1:
num_1_1 = int(input())
num_2_1 = int(input())
anwsr_add = (num_1_1 + num_2_1)
print(anwsr_add)
Hey Dalek I've copied your code and got this result:
1. add ; 2. subtract ; 3. multiply ; 4. divide
What's your choise?
1
Traceback (most recent call last):
File "C:\Users\timur\AppData\Local\Programs\Python\Python36-32\Game.py", line 10, in <module>
print (anwsr_add)
NameError: name 'anwsr_add' is not defined
The NameError occurs because the programm trys to call anwsr_add while it executes the code below if choise == ...
You can use this code. It works. The reason why your code doesn't works is that you call anwr_add not in the if choise == ... method:
choise = input("1. add ; 2. subtract ; 3. multiply ; 4. divide. What's your choise?")
if str(choise) == '1':
print('First_num:')
num_1_1 = input()
print('Second_num:')
num_2_1 = input()
anwsr_add = (int(num_1_1) + int(num_2_1))
print (anwsr_add)

Random Maths Program

thanks for taking time to read this.
I have to create a program that generates 10 random maths questions based around =, - and *. I have the program working but everytime I run it after the main program it prints "none" even though that's not in my program.Any help at all would be much appreciated. Thank you.
import random
print ("Welcome")
name=input("What's your name?")
print("Nice to meet you", name, ",you will be given 10 multiplication, addition and subtraction questions.")
Num1 = random.randint(1,12)
Num2 = random.randint(1,12)
sign = random.randint(1,3)
if sign == 1: # If the random number generated is 1
question = Num1 + Num2
rightanswer1 = Num1 + Num2
answer1=input(print("What is", question ,"?"))
if answer1 == rightanswer1:
print("Well Done!")
if answer1 != rightanswer1:
print("Sorry, that's incorrect, the answer was", rightanswer1)
if sign == 2:
question = Num1 - Num2
rightanswer2 = Num1 - Num2
answer2=input(print("What is", Num1, "-", Num2 ,"?"))
if answer2 == rightanswer2:
print("Well done!")
elif answer2 != rightanswer2:
print("Sorry, that's incorrect, the answer was", rightanswer2)
if sign == 3:
question = Num1 * Num2
rightanswer3 = Num1 * Num2
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
if answer3 == rightanswer3:
print("Well done!")
elif answer3 != rightanswer3:
print("Sorry, that's incorrect, the answer was", rightanswer3)`
> Welcome
> What's your name? John
> Nice to meet you John ,you will be given 10 multiplication, addition and subtraction questions.
> What is 12 x 3 ?
> None 36
> Sorry, that's incorrect, the answer was 36
I think you are using python 3. In python 3 input is like raw_input in python 2. So you get the string as input. So convert it into int
var = int(input("Enter a number: "))
So in your code make it as
print("What is", Num1, "x", Num2 ,"?")
answer3 = input()
answer3 = int(answer3)
See this:
whats-the-difference-between-raw-input-and-input-in-python3-x
I'm reluctant to just give you an answer that just does it for you, so instead i'll provide you with a few hints to improve things. (i.e. this isn't an answer, just too large of a comment - and more like a codereview answer)
First off, you use a structure like this:
if x == 1:
#do something
if x == 2:
#do something else
...
In this case, which it makes no difference, it is easier to read if you use the if syntax as intended:
if <condition>:
#do this if the above test is true.
elif <more conditions>:
#do this only if the first test is false and this one is true
elif <more conditions>:
#same as above, except for the second test must be false too
else:
#do this if all the above tests are false
So you could use this something like:
if sign == 1:
...
elif sign == 2:
...
elif sign == 3:
...
else:
# something weird happened...
Which would make that section of the program easier to follow.
The same thing can be done with the if answer1 == rightanswer1: sections;
if answer1 == rightanswer1:
#correct!
else:
#incorrect.
That would be a clearer was to do it. You seem to have used the if...elif style in a couple of them, but not the first one.
Once you have this, it will be a little clearer.
The next way you could improve things is by removing duplicated code. You don't need separate branches for each sign, you can just roll it all into one:
number1 = randint(1,12)
number2 = randint(1,12)
op = randint(1,3)
question_string = "%d %s %d = ?" % (number1, number2, ["+", "-", "*"][op])
result = None
if op == 1:
result = number1 + number2
elif op == 2:
result = number1 - number2
elif op == 3:
result = number1 * number2
This will do most of the logic for you, and generate the strings you want, without duplicating all of the other code.
Small changes like this can make things much more readable.
It's printing None because the print() function returns None and you're passing that value of None from print() as the prompt to your input() functions. Eg,
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
So print("What is", Num1, "x", Num2 ,"?") prints its stuff, and returns None, which then gets printed as the prompt by input().
A simple way to fix this is to just move your print() function calls out of your input() functions.
Eg,
print("What is", Num1, "x", Num2 ,"?")
answer3=input()
However, there's another major problem with your program: the rightanswer variables are ints, but the inputted answers are strings. To compare them properly they need to be the same type. So you should either convert the inputted answers to int, or alternatively, convert the rightanswers to str.
There are two problems with how you use the input function:
You misuse the prompt argument
You forget to convert the result
First, have a better look at the reference of the input function
The prompt argument
input takes a string as argument that will be displayed ("prompted") to the user to indicate that the program is waiting an input. The print function also displays a string to the user, but it doesn't return anything. It does its job and that's all (and in Python a function that returns nothing, returns None). That's what input gets to display, so it displays None. You should use format instead. It will format and return the formatted string that input can display:
answer1_as_str=input("What is {} ?".format(question))))
or
answer2_as_str=input("What is {:d} - {:d} ?".format(Num1, Num2)))
The return value
input returns the user input as a string contrary to python 2 (i.e. exactly as entered). So you have to convert the input to the desired type if you need it. If you type 10 for example, the input will return "10". If you need an int, you have to convert it yourself.
answer1 = int(answer1_as_str)
It looks like you don't really understand how input() works. You might also want to review the different datatypes and conditional statements. Other than that, it was a very good attempt. Here's my solution:
from random import randint
print("Welcome")
name = input("What's your name?\n")
print("Nice to meet you " + name + ", you will be given 10 multiplication, addition and subtraction questions.")
for i in range(10):
print("\nProblem " + str(i+1))
num1 = randint(1,12)
num2 = randint(1,12)
sign = randint(1,3)
if sign == 1:
question = str(num1) + " + " + str(num2)
answer = num1 + num2
elif sign == 2:
question = str(num1) + " - " + str(num2)
answer = num1 - num2
else:
question = str(num1) + " x " + str(num2)
answer = num1 * num2
user_answer = input("What is " + question + "? ")
if user_answer == str(answer):
print("Well done!")
else:
print("Sorry, that's incorrect, the answer was", answer)

Confusing result from raw_input() in Python

I'm having problems with the "operator" variable. So far I have only tried +. It doesn't seem to register and I can't figure out why. i'm using the online python interpreter on repl.it because I'm having problems with my computer.
EDIT: I should probably add that I just started learning Python (I had some Java experience but it was years ago). I'm trying to create a simple text calculator.
restart=raw_input("to restart calculations enter \'true\'")
#if restart == "true":
#stuff
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
answer=numone+numtwo
print(answer)
print("test")
if operator == "-":
answer=numone-numtwo
print(answer)
else:
print("something went wrong")
#if operator == "*":
Your problem is that you're concatenating two strings, you should cast to int before:
answer = int(numone) + int(numtwo)
Why? Because raw_input reads the input as string.
Give elif to the second statement
since user give '+'
first if statment excutes but in next statement it fails and go to the else so for + you get two result both addition and something wrong
and also you need to convert the operands to integer
one more thing while converting to integer you need check right conditions for integer else it will give error
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
try:
answer=int(numone)+int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
elif operator == "-":
try:
answer=int(numone)-int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
else:
print("something went wrong")

Taking apart strings in Python

So I am making a quick calculator script in Python, and I need to take apart a short string. The program first displays a short welcome message, then a prompt asks What they want to do calculate, and shows them the correct format. The functionality is there to do the calculation but unfortunately, I can not get the string dissecting bit working.
Here's my code
print ("--------------------------------------")
print (" ")
print ("Advanced Quick Calculator")
print ("By Max M, licenced under GPLv3")
print (" ")
print ("--------------------------------------")
statement = raw_input ("Please enter your mathematical statement [3 3 plus minus times divide]: ")
strnum1 = statement[:1]
print ("strnum1 : " + strnum1)
#num1 = int (strnum1)
strnum2 = statement[:4]
print ("strnum2 : " + strnum2)
#num2 = int (strnum2)
operation = statement[5:11]
print ("operation : " + operation)
#if operation == "+":
# ans = num1 + num2
#if operation == "-":
# ans = num1 - num2
#if operation == "*":
# ans = num1 * num2
#if operation == "/":
# ans = num1 / num2
#print ("The answer is : "), ans
This looks like a job for regular expressions:
>>> import re
>>> match = re.search(r'(\d+)\s*([+*/-])\s*(\d+)', '42 + 7')
>>> match.group(1) # <-- num1
'42'
>>> match.group(2) # <-- operation
'+'
>>> match.group(3) # <-- num2
'7'
Slicing the input like you're currently doing is probably not a good idea as it greatly restricts the allowed formats. For instance, what if the user accidentally precedes his input with a couple of spaces? Regular expressions can handle such cases well.
I'm not going to do your homework for you, but I will point you to the answer to your question (hint: it looks like you're trying to split on spaces instead of comma's like in the link, so adjust the code accordingly).
How to read formatted input in python?

Python: altering raw_input?

I'm trying to create a program to create a questionaiire, ultimately giving back info the user inputs. Here's my code:
. Def questionaiire:
>>. Loop = 0
>>
>> While loop != 1:
>> Print "A: name"
>> Print "B: age"
>> Print "B: Favorite color".
>> Zen = raw_input("choose a, b, or c") #my problem line
>> If zen == "a" or "A":
>> A = raw_input("Input your name: ")
>>. Elif zen == "b" or "B":
>>. B = raw_input:("Input your age: ")
>>. Elif zen == "C" or "c":
>> C = raw_input("Input your favorite color")
>> Else:
>> Print A, B, C
>> Break
The ending bit is a little more sophisticated, but essentially thats my function. Help?
I also tried inserting return after the if and elifs, but that made the program stuck(couldnt input) so i took them out
There are a number of syntax errors in your code.
You must not capitalize def, while, print, if, elif, else, break, or any other python keyword, they must be all lower case.
You need to be consistent in the casing of your variable names. Zen and zen are two different variables!
You must put parenthesis after the name of the function, like this: def questionaiire():
The period in this line is a syntax error. Remove it.
print "B: Favorite color".
The colon following raw_input in this line is a syntax error. Remove it.
B = raw_input:("Input your age: ")
I don't know what the >>s at the start of each line is, I presume it's not part of the actual source code. If it is, remove all occurances of > at the start of a line.
This line does not do what you think it does:
if zen == "a" or "A":
It's interpreted like this:
if (zen == "a") or "A":
So it's always true, since "A" evaluates to True. Write it like this instead:
if zen.lower() == "a":
Here's a working example. I've made as few changes as possible to the code, to ease comparison.
def questionaiire():
a = b = c = ""
while True:
print "a: name"
print "b: age"
print "c: favorite color"
zen = raw_input("choose a, b, or c: ")
if zen.lower() == "a":
a = raw_input("input your name: ")
elif zen.lower() == "b":
b = raw_input("input your age: ")
elif zen.lower() == "c":
c = raw_input("input your favorite color: ")
else:
print a, b, c
break
You never used the loop variable, so I've removed it. Since you use break, there's no real need for it in this code example.
The number and variety of mistakes you've made writing this short code indicates that you would really benefit from reading through at least the first few chapters of the python tutorial before programming any more python or asking further python-related questions on this site.

Categories

Resources