Python calculator concatenates instead of preforming operations - python

I'm new to Python and I'm attempting to program a calculator. The problem is I can't find a way to make the variables num1 and num2 do the operation I have listed for them. All they do is concatenate the two numbers instead of performing the operation, any suggestions? Thanks.
letter = ()
class Calc():
print raw_input("What operation do you want to do?\n\tA) Addition\n\tB) Subtraction\n\ ")
num1 = raw_input("Please enter your first number: ")
num2 = raw_input("Please enter your second number: ")
if letter == 'A' or 'a':
print "The sum of", num1, "plus", num2, "equals"
print num1 + num2
elif letter == 'B' or 'b':
print "The difference of", num1, "minus", num2, "equals"
print num1 - num2

raw_input returns a string, so your two inputs are concatenated. You need to convert that input to a number before using it with numeric operators.
num1 = int(raw_input("Please enter your first number: "))
You can use either float or int to convert the input string to a number.
You also need to change
if letter == 'A' or 'a':
to
if letter == 'A' or letter == 'a':

You are using
raw_input()
which converts the input to strings.
If you want to add them together, you would like to use
num1 = float(num1)
before adding.

This is because you are doing string operations. raw_input returns a string, so you must manually convert it to an int or float using: float() or int().
Do this:
print int(num1) + int(num2) in order to print the numbers in their addition form.

I think this will do what you ask:
letter = raw_input("What operation do you want to do?\n\tA)
Addition\n\tB)Subtraction\n")
num1 = input("Please enter your first number: ")
num2 = input("Please enter your second number: ")
if letter == 'A' or 'a':
print "The sum of", num1, "plus", num2, "equals"
print num1 + num2
elif letter == 'B' or 'b':
print "The difference of", num1, "minus", num2, "equals"
print num1 - num2

Related

how do i turn an input into a variable so i can add or use in equations in python

if I have a code like this?
num1= input (" number goes here")
num2= input ("number goes here")
how can I make a simple equation work such as.
num3=num2+num1
print ("num3")
and when I do that it outputs
num2num3
I have tried things such as
int=(num1)
You need to convert num1 and num2 into int type because input gives you a str type.
num1 = int(input(" number goes here"))
num2 = int(input("number goes here"))
num3 = num1 + num2
print(num3)

How to pass string input as integer arguments? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I wanted to do the following simple calculation by passing values for the parameters num1 and num2 from input() methods.
I tried following code:
def add(num1, num2):
return num1 * num2
num1 = input('Enter number1: ')
num2 = input('Enter number2: ')
print(add(num1, num2))
But it is showing the following error when it is run (After input num1 and num2):
TypeError: can't multiply sequence by non-int of type 'str'
Can somebody please explain where did I go wrong and how to convert an input string to the integer type?
input() will returns a string, you have to convert the string to a int or float, you can test if the input is a valid number.
isnumeric() will return true if all chars in the string are numeric ones and the string is not empty.
Note: i renamed the function to multiply because this is not adding ...
def multiply(num1,num2):
return num1*num2
inp1=input('Enter number1: ')
inp2=input('Enter number2: ')
if inp1.isnumeric() and inp2.isnumeric():
num1 = int(inp1)
num2 = int(inp2)
print(multiply(num1,num2))
else:
print("Atleast one input is not numeric")
You can try this:
def add(num1, num2):
return num1 * num2
num1 = int(input('Enter number1: '))
num2 = int(input('Enter number2: '))
print(add(num1, num2))
The input function stores the input as a string and so what is happening in your code is that you are entering two integers but they are being stored as strings. You cannot multiply two strings. All you need to do is convert the input strings to integers by using the [int()][2] function. If you want to multiply floats, you can use the [float()][3] function in place of the int() function. You can also convert the strings to integers or floats once you have passed them into the function. Something like this:
def add(num1, num2):
return int(num1) * int(num2)
num1 = input('Enter number1: ')
num2 = input('Enter number2: ')
print(add(num1, num2))
input (in Python 3) returns a str which is seen as text and not a number. If you want to multiply (or add) numbers, you must first parse the strings as numbers.
Sometimes this will fail as well. If you're assuming the input is always going to be a valid number, you can convert a string using:
float("3.1415926")
You can use this in your code with:
def add(num1,num2):
return num1*num2
num1=float(input('Enter number1: '))
num2=float(input('Enter number2: '))
print(add(num1,num2))
To avoid floating point errors, you can print/display the float using an f-string (added in Python 3.6).
def add(num1,num2):
return num1*num2
num1=float(input('Enter number1: '))
num2=float(input('Enter number2: '))
print(f"{add(num1,num2):.2f}")
def mul(num1,num2):
return(num1*num2)
inp1 = input('Enter number1:')
inp2 = input('Enter number2:')
num1 = int(inp1)
num2 = int(inp2)
print(mul(num1,num2))

Trying to make a pow() calculator, without the pow, ERROR message "'int' object has no attribute 'count'"

The idea is, that the calculator is supposed to detect the numbers of num1 in the calculation and add more until it is equal to the num2, as it is supposed to be num1 raised to the power of num2.
But I keep receiving this message "'int' object has no attribute 'count'". I know the count is for lists, so I was wondering, what the appropriate command would be for int (or float).
Furthermore, how would I go about adding the numbers of "num1" to the equation?
Here is the whole code
num1 = int(input("Enter a number"))
operator = input("Now enter an operator")
num2 = int(input("Enter a new number"))
Pow = (num1*num1)
if operator == "^":
print(Pow)
while Pow.count(num1) < num2 += 1:
Pow = num1 * num1
num1 = int(input("Enter a number: "))
operator = input("Now enter an operator: ")
num2 = int(input("Enter a new number: "))
goal = num1 ** num2
#print("goal: " + str(goal))
count = 1
if operator == '^':
while num1 < goal:
#print(num1)
num1 += num1
count += 1
#print(num1)
print ("It took %(count)d loops to get to %(num)d!" % {'count': count, 'num': goal})
Your question is vague, but I believe this is what you are looking for?
Edited code above and included example below
You have an Invalid Syntax here which is while Pow.count(num1) < num2 += 1:
Have a look at this edited code:
num1 = int(input("Enter a number"))
operator = input("Now enter an operator")
num2 = int(input("Enter a new number"))
Pow = (num1*num1)
if operator == "^":
print(Pow)
while num1 < num2:
Pow = num1 * num1
num2 += 1

adding python loop best practices

I am new to python and trying to learn the best way to learn to code. I am practicing with some simple code that asks for 2 numbers and multiples them and I want to add a a function to ask if you are done or if you want to multiply some more numbers. Below is the code I started with. I want to know what is the best way to have it loop back to asking for 2 more numbers with a yes or no question?
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
You can set a reminder like when the user is finish then make you can make the reminder is False to make it finish or take a input and check if user want to exit then just simply break the loop.
# set reminder for while loop
done = False
while not done:
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
ask = input('Do you want to try again y/n: ')
if ask == 'n':
done = True # set the reminder is true or break the loop
# break
While loop is the most used one:
repeat = 'yes'
while repeat.lower() == 'yes':
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
print('If you want to continue type yes or no')
repeat = input()
You can do that by wrapping the whole code in a while True loop with a break statement to exit. Essentially, we will want to repeat the process forever, until the user types n or N. The check condition can be refined as desired.
while True:
# Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
# Convert input to interger
num1 = int(num1)
num2 = int(num2)
# Multiply the numbers
results = num1 * num2
# Print the results
print("Your answer is: " + str(results))
# Ask to continue or not
res = input("\nWould you like to continue? (y/n) ").strip()
if res.lower() == 'n':
break
Just simple use while loop and declare a variable named choice and ask the user to enter his choice.
while(True):
choice = input("Would you like to continue? (y/n) ")
if(choice.lower=='y'):
num1 = int(input("\nEnter the first number you want to multiply: "))
num2 = int(input("\nEnter the second number you want to multiply: "))
results = num1 * num2
print("Your answer is: ",results)
else:
break
def termination():
_noexit=str(raw_input())
if _noexit.lower() == 'y':
return True
else:
return False
#Cal the termination condition
while termination:
num1 = input("\nEnter the first number you want to multiply: ")
num2 = input("\nEnter the second number you want to multiply: ")
num1 = int(num1)
num2 = int(num2)
results = num1 * num2
print results
#Checking termination
termination()

If statement error. Comparison of numbers to output max

I'm writing a simple code on python, but have come across an unusual error. The statements are to compare thre numbers and return the max value. Most of the time the program executes fine, however, if for example num3 is a 3-digit number and others are not, I get a comparison error. Any ideas?
def maxNum(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num3 and num2 >= num1:
print (num2)
return num2
else:
print (num3)
return num3
num1 = input("Please enter first number: ")
num2 = input("Please enter second number: ")
num3 = input("Please enter third number: ")
print ("Max number is:", maxNum(num1, num2, num3))
Please click on image link. I have changed the code as advised but still get error. It seems any integer that I input that is more than or equal to 100 creates this error:
enter image description here
1 def max_num(num1, num2, num3):
2 biggest = max([int(num1),int(num2), int(num3)])
3 return biggest
4
5 num1 = input("Enter First Number: ")
6 num2 = input("Enter Second Number: ")
7 num3 = input("Enter Third Number: ")
8
9
10 print(max_num(num1, num2, num3))
Are you just trying to work the function comparisons, or are you open to other methods?
This will accomplish the same task with less steps.
Although I am by no means fluent in Python, I believe the approach to distinguish all cases that can occur is hard to understand. Instead, I suggest iterating the input values as follows. The approach uses an additional varaiable to store the potential result.
def maxNum(num1, num2, num3):
result = num1
if (num2 > result)
result = num2
if (num3 > result)
result = num3
print(result)
return result

Categories