To print strings with math addition numbers in Python, what is the correct way doing something like:
# Read two inputs from users
a = input("Enter your First Number")
b = input("Enter your Second Number")
# perform type conversion
a = int(a)
b = int(b)
print (f"Result: {a}+{b}")
Output:
Enter your First Number10
Enter your Second Number10
Result: 10+10
Desired output: Result: 20
Your current format string Result: {a}+{b} prints out a and b individually as Result: 10+10 and doesn't perform the addition.
To achieve that, you need to change the f-string to f"Result: {a+b}" so that the addition happens within the formatting curly braces and the result gets printed
print (f"Result: {a+b}")
The output will be
Result: 20
a = input("Enter your First Number")
b = input("Enter your Second Number")
# perform type conversion
a = int(a)
b = int(b)
print (f"Result: {a + b}")
You should change
print (f"Result: {a} + {b}")
to
print (f"Result: {a + b}")
# Read two inputs from users
a = int(input("Enter your First Number"))
b = int(input("Enter your Second Number"))
print ("Result: {}".format(a+b))
Related
I've created a basic addition statement, i am aware that input is being read as a string but my code prints out "none" before taking an input (see below). How do i take integer as an input??
# code example
print("This is a calculator")
a = input(print("Enter the first number"))
b = input(print("Enter the second number"))
print("sum =", a + b)
This outputs:
This is a calculator
Enter the first number
None5
Enter the second number
None6
sum = 56
remove print() in the first two lines:
a = input("Enter the first number")
b = input("Enter the second number")
instead of:
a = input(print("Enter the first number"))
b = input(print("Enter the second number"))
None is the return of the print() function so since input() prints what you input to it you are printing the returned None value. Then the print statement will still print the prompt. However you want to let input() print the prompt as described above.
input() prints the prompt for you. You just have to enter a = input("Enter the first number")
I have to make a program using while that:
Will ask for user to put 2 integer numbers
and give back the addition and multiplication
of those 2.
Will check if the numbers are integers.
Will close if the user uses the word stop.
I have made 1 and 2 but am stuck on 3. Here is what I wrote:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.
What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Just a slight change is required (and you can be slightly more structured using else in your try block.
You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).
I am trying to add 2 integers in Python3 using input.
def sum(x,y):
return x+y
a = int(input("Enter first number"))
b = int(input("Enter second number"))
print("The sum of a and b is", sum(a,b))
and get the following error
Traceback (most recent call last):
File "Main.py", line 7, in <module>
a = int(input("Enter first number"))
ValueError: invalid literal for int() with base 10: '1 1'
Another concern is this works normally in my Jupyter notebook,
but for another online practice center it shows this error.
Your code is working, but not for the specific input the practice center is giving. Make this modification:
nums = [int(x) for x in input("Enter numbers: ").split()]
print("The sum of a and b is", sum(nums))
By the way, sum is a built-in function, so you don't have to write it yourself. The only line that really changed is this:
nums = [int(x) for x in input("Enter numbers: ").split()]
nums will be a list of numbers, as the name implies. The next part is the list comprehension. input("Enter numbers: ").split() will take the input and split it on any whitespace. For instance, 'hello world' will be turned into a list with ['hello', 'world']. In this case, '1 1' will be turned into a list with ['1', '1']. Then, with the list comprehension, you are turning each element into an integer (['1', '1'] -> [1, 1]). Then, you pass this list into sum. Also, this does the same thing as the list comprehension:
nums = list(map(int, input("Enter numbers: ").split()))
It doesn't matter which one you choose. If you wanted to get real fancy, you can do the whole thing in one line:
print("The sum of a and b is", sum(map(int, input("Enter numbers: ").split())))
Given that your input are coming with spaces itself, you can use replace command and replace those spaces.
def sum(x,y):
return x+y
a = int(input("Enter first number: ").replace(" ",""))
b = int(input("Enter second number: ").replace(" ",""))
print("The sum of a and b is: ", sum(a,b))
For your specific case, this should work. What I am doing here is that I am converting the input like '8 3 525 5', to '835255', which itself will be easily converted to int later on and will work perfectly.
Removing the duplicate as well mate.
If you want to input all values in the same line as 1 1, then you should use split():
def sum(x,y):
return x+y
a, b = map(int, input("Enter numbers ").strip().split())
print("The sum of a and b is", sum(a,b))
Output:
C:\Users\Desktop>py xxx.py
Enter numbers 1 1
The sum of a and b is 2
If separately values need to be inputted:
def sum(x,y):
return x+y
a = int(input("Enter first number ").strip())
b = int(input("Enter second number ").strip())
print("The sum of a and b is", sum(a,b))
Output:
C:\Users\Desktop>py xxx.py
Enter numbers 1 1
The sum of a and b is 2
It's a very basic doubt in Python in getting user input, does Python takes any input as string and to use it for calculation we have to change it to integer or what? In the following code:
a = raw_input("Enter the first no:")
b = raw_input("Enter the second no:")
c = a + b
d = a - b
p = a * b
print "sum =", c
print "difference = ", d
print "product = ", p
Python gives following error:
Enter the first no:2
Enter the second no:4
Traceback (most recent call last):
File "C:\Python27\CTE Python Practise\SumDiffProduct.py", line 7, in <module>
d=a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Can someone tell please why am I getting this error?
Yes, every input is string. But just try:
a = int(a)
b = int(b)
before your code.
But be aware of the fact, that user can pass any string he likes with raw_input. The safe method is try/except block.
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
So it could be like:
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
From the documentaion:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Yes, you are correct thinking you need to change the input from string to integer.
Replace a = raw_input("Enter the first no: ") with a = int(raw_input("Enter the first no: ")).
Note that this will raise a ValueError if the input given is not an integer. See this for how to handle exceptions like this (or use isnumeric() for checking if a string is a number).
Also, beware that you although you might find that replacing raw_input with input might work, it is a bad and unsafe method because in Python 2.x it evaluates the input (although in Python 3.x raw_input is replaced with input).
Example code could therefore be:
try:
a = int(raw_input("Enter the first no: "))
b = int(raw_input("Enter the second no: "))
except ValueError:
a = default_value1
b = default_value2
print "Invalid input"
c = a+b
d = a-b
p = a*b
print "sum = ", c
print "difference = ", d
print "product = ", p
a = input("Enter integer 1: ")
b = input("Enter integer 2: ")
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
Just use input() and you will get the right results. raw_input take input as String.
And one more i Would Like to Add..
why to use 3 extra variables ?
Just try:
print "Sum =", a + b
print "Difference = ", a - b
print "Product = ", a * b
Don't make the Code complex.
raw_input() stores the inputted string from user as a "string format" after stripping the trailing new line character (when you hit enter). You are using mathematical operations on string format that's why getting these errors, first cast your input string into some int variable by using a = int(a) and b = int(b) then apply these operations.
I've just started studying Python, and I'm an absolute newbie.
I'm starting to learn about functions, and I wrote this simple script:
def add(a,b):
return a + b
print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")
result = add(a, b)
print "The result is: %r." % result
The script runs OK, but the result won't be a sum. I.e: if I enter 5 for 'a', and 6 for 'b', the result will not be '11', but 56. As in:
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: '56'.
Any help would be appreciated.
raw_input returns string, you need to convert it to int
def add(a,b):
return a + b
print "The first number you want to add?"
a = int(raw_input("First no: "))
print "What's the second number you want to add?"
b = int(raw_input("Second no: "))
result = add(a, b)
print "The result is: %r." % result
Output:
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11.
You need to convert the strings to ints to add them, otherwise + will just perform string concatenation since raw_input returns raw input (a string):
result = add(int(a), int(b))
You need to cast a and b to integer.
def add(a, b):
return int(a) + int(b)
This is because raw_input() returns a string and + operator has been overloaded for strings to perform string concatenation. Try.
def add(a,b):
return int(a) + int(b)
print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")
result = add(a, b)
print "The result is: %r." % result
The resultant output is as follows.
>>>
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11
Converting the string inputs to int, uses the + operator to add the results instead of concatenating them.
.
**
**>raw_input always returns string. You need to convert the strings to int/float datatype to add them, otherwise addition will perform string concatenation.
You can check the type of the variables yourself : print(type(a), type(b))
Simply tweak your function**
**
def add(a, b):
return int(a) + int(b)
OR
def add(a, b):
return float(a) + float(b)