making calculator in python, is this approach sensible? - python

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)

Related

Why this WHILE loop does not end? [Python] [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
im trying to create a multiple values calculator in Python, using While, For/In sentences with lists
numbers = []
out = 0
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == 1:
out == 1
#In theory if out == 1 the while loop should end and go to:
for add in numbers:
add = numbers
print(add)
I tried using While Not sentence, but i get an obvius mistake. I suppose this is a pretty dumb error of comprehention i have, but i can't really get what am i doing wrong. I'll be very glad if u help me with this.
First of all, variable assignment should be done with = not ==. Your problem is that in the second input() (where you let user choose will he/she stay or exit), you need to convert the input to int from string first, OR check by the string representation of the number (fail-safe):
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == '1':
out = 1
However, best way to break out a loop is to use break:
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == '1':
break
Apart from the errors pointed out in the other 2 answers, you are getting input from the user as a str and not converting it to an int.
So it never hits the if condition and therefore your program doesn't end.
Please try this
numbers = []
out = 0
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
print(type(out2))
if int(out2) == 1: # Convert the out2 to an int here
print(f" Inside if condition")
out = 1 # Use an assignment operator here

If statement where a variable is equal to a special character [Python] [duplicate]

This question already has answers here:
Python input error
(4 answers)
Closed 6 years ago.
I've made a simple calculator where you can enter unlimited numbers in one operator(i.e. addition) but every time I run it, it gives an error:
"Traceback (most recent call last):
File "C:\Users\My own\Desktop\1.py", line 68, in <module>
choose_operation()
File "C:\Users\My own\Desktop\1.py", line 9, in choose_operation
addition()
File "C:\Users\My own\Desktop\1.py", line 26, in addition
c = input("Number:")
File "<string>", line 1
+
^
SyntaxError: unexpected EOF while parsing"
I only included two functions here which are the function for selecting the operation to be used and the addition function so it would remain short as possible. The problem is: Whenever I tried to put "c == '+'" in the second to the last line, I get the error mentioned above. What I'd like to happen is that when a user inputs '+', it calls the function 'choose_operation' so I could get back to choosing an operation. What went wrong? Here's my code.
def choose_operation():
print "choose operator"
print "1. Addition"
print "2. Subtraction"
print "3. Multiplication"
print "4. Division"
choice = input("choice = ")
if choice == 1:
addition()
elif choice == 2:
subtraction()
elif choice == 3:
multiplication()
elif choice == 4:
division()
else:
print "Select numbers from 1 to 4"
choose_operation()
def addition():
a = input("Number:")
b = input("Number:")
sum = a + b
print sum
while True: #I put this here so it can keep on adding numbers
c = input("Number:")
sum = sum + c
print sum
if c == '+':
choose_operation()
Since you're using python 2, using input tries to evaluate the entered string.
It may seem convenient when you enter numbers because you can do:
a = input("enter number")
and a is a float, int, whatever you entered.
But when you want to enter a string, (ex: +), the pyhton engine evaluates your expression as +, hence the error you're experiencing.
So, drop input() for python 2 since it has security issues: you can run system commands and delete files, etc...
Python 2:
you can use raw_input() to get the strings (like +)
enter numbers like this: a = float(raw_input("enter a float"))
Python 3:
same thing, but use input instead of raw_input (input as we know it with the nasty evaluation has been removed and raw_input is now input)

python - inputting numbers that start with 0

I'm making a program in python. It is suppose to take in a GTIN number and put in a list and then check if it's valid. The program works, but as soon as I enter a GTIN number that starts with a 0, I get a "invalid token (, line 1)" error. I really need a solution because some products have their GTIN numbers starting with a 0.
when I input a number for example:
96080832
The program works great.
When i put in a number like:
00256986
I get an error:
invalid token (<string>, line 1)
pointing to this line:
inputtedInt = int(input("Enter the gtin number: "))
Whole def:
def chooseOption(inputInt):
while(inputInt > 0 and inputInt < 4):
if(inputInt == 1):
print("you picked option number 1")
showOptions()
break
elif(inputInt == 2):
print(" ")
inputtedInt = int(input("Enter the gtin number: "))
gtin = map(int,str(inputtedInt))
checkValidity(gtin, 2)
print(" ")
showOptions()
break
elif(inputInt == 3):
print("you picked option number 3")
showOptions()
break
else:
option = int(input("Error - enter a number from 1 to 3. : "))
chooseOption(option)
Thanks in advance.
You seem to be using Python 2. In Python 2, input tries to evaluate the input string as a Python expression, and a leading 0 on a numeric literal in Python 2 syntax means that the number is in octal, or base 8. Since 8 and 9 are not valid digits in base 8, this input constitutes a syntax error.
If you were supposed to be using Python 3, get on Python 3. If you're supposed to be on Python 2, use raw_input instead of input.
Additionally, if you care about preserving things like leading zeros, you should keep the input as a string and only call int on it when you want to do math on it as an integer.
Error is raised because you are mapping str ant/to int in line:
gtin = map(int,str(inputtedInt))
for example if you ty to run:
a = 005
You will get following error:
File "<stdin>", line 1
a = 005
^
SyntaxError: invalid token
Sollution -> you should use stringsfor GTIN number :)

How to add and subtract in python

So I am making a statcalc and everything is working except adding. When I select the option to add it just skips it and says select an option. I was wondering what's wrong with it?
numberstoadd = input("What is the first number you want to add? ")
numbertoadd = input("What do you want to add to it? ")
sum = numbertoadd + numberstoadd
print sum
You need to turn your input strings into ints. Like this:
number_1 = int(raw_input("What is the first number you want to add? "))
number_2 = int(raw_input("What do you want to add to it? "))
sum = number_1 + number_2
print sum
In Python 2, input would eval the typed text and return an integer, whereas under Python 3 input just returns a string containing the typed text (equivalent to raw_input in Python 2).
See this link for other changes between Python version 2.x & 3.x
http://docs.python.org/dev/whatsnew/3.0.html
print("Welcome to fizz buzz")
num1=input("Choose a number from 1 to 100")
if num1 is >= 50:
print("hello")
else:
print("good bye")
Sample Input 0
2
1 3
10 100
Sample Output 0
-2
-90
Given a two integers print the difference of two integers.
*Hint: Try to implement without using '-' operator.

Python: Display and count divisors of two integers

Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :

Categories

Resources