I attempted to write a program in python that calculates (likely horribly inefficiently, but I digress) using several different operations. However, there was an error I can't figure out when running it. I think it requires defining the type of a variable. The program:
import math
print('Select a number.')
y = input()
print('Select another number.')
x = input()
print('Select what operation you wish to perform. (e for exponentiation, d for division, m for multiplication, a for addition, s for subtraction, mo for modulo, l for log (the base is the first number you entered), r for root)')
z = input()
if z == 'e' or z == 'E':
print('The answer is ' + y**x)
elif z == 'd' or z == 'D':
print('The answer is ' + y/z)
elif z == 'm' or z == 'M':
print('The answer is ' + y*x)
elif z == 'a' or z == 'A':
print('The answer is ' + y+x)
elif z == 's' or z == 'S':
print('The answer is ' + y-x)
elif z == 'mo' or z == 'Mo':
print('The answer is ' + y%x)
elif z == 'l' or z == 'L':
print('The answer is ' + math.log(x,y))
elif z == 'r' or z == 'R':
print('The answer is ' + y**(1/x))
The error that showed up in the shell:
Traceback (most recent call last):
File "C:/Users/UserNameOmitted/Downloads/Desktop/Python/Calculator.py", line 7, in <module>
z = input()
File "<string>", line 1, in <module>
NameError: name 'd' is not defined
3 Answers 3
You have several problems here:
zshould be inputted withraw_input, notinput.- In the division case, you're dividing
y/zinstead ofy/x.
1 Comment
input gives an intYou have to do
z = raw_input()
Also input returns as int in python2.x.So use raw_input to read as str Then everywhere like print('The answer is ' + y**x) into print('The answer is ' + str(y**x))
4 Comments
from __future__ import division at top of your fileprint('a string ' + str(num_expr)) or print 'a string', num_expr?Your code has errors
- use raw_input() to take string input instead of input()
- use int(raw_input()) to take integer input, its not an error but it is good practice.
- you tried to divide int with string.
- You tried to concatenate string and integer.
Your code should be something like this.
import math
print('Select a number.')
y = int(raw_input())
print('Select another number.')
x = int(raw_input())
print('Select what operation you wish to perform. (e for exponentiation, d for division, m for multiplication, a for addition, s for subtraction, mo for modulo, l for log (the base is the first number you entered), r for root)')
z = raw_input()
if z == 'e' or z == 'E':
print('The answer is %d' %(y**x))
elif z == 'd' or z == 'D':
print('The answer is %d' %(y/x))
elif z == 'm' or z == 'M':
print('The answer is %d' %(y*x))
elif z == 'a' or z == 'A':
print('The answer is %d' %(y+x))
elif z == 's' or z == 'S':
print('The answer is %d' %(y-x))
elif z == 'mo' or z == 'Mo':
print('The answer is %d' %(y%x))
elif z == 'l' or z == 'L':
print('The answer is %d' %(math.log(x,y)))
elif z == 'r' or z == 'R':
print('The answer is %d' %(y**(1/x)))
raw_inputinstead ofinput.