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)
Related
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))
I am trying to find of biggest of 3 numbers using python3.6. But its returning wrong value.
#!/usr/bin/python3
a=input("Enter first number: ")
b=input("Enter second number: ")
c=input("Enter Third number: ")
if (a >= b) and (a >= c):
largest=a
elif (b >= a) and (b >= c):
largest=b
else:
largest=c
print(largest, "is the greatest of all")
If I provide, a=15; b=10 and c=9
Expected output should be 15.
But I am getting actual output as 9.
input() returns strings. You need to convert the strings to class int to compare their numeric value:
a = int(input("Enter the first number: "))
In string comparisons, 9 is greater than 1. You can try in the REPL:
>>> '9' > '111111111111111111'
True
You can use the max() builtin function of python:
https://www.freecodecamp.org/forum/t/python-max-function/19205
Like the comment of khelwood mentioned it You are comparing strings, not numbers. – khelwood. You should first cast the input values to integers (or float) and then compare them.
More about casting in python can be found here
As khelwood pointed out in comment those inputs are used as strings.
try inserting this after input and its fixed:
a = int(a)
b = int(b)
c = int(c)
This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 4 years ago.
Very new to programming and decided to get into Python. Sorry in advance if this question is very simple. Experimenting with functions. Got this to run with no errors, but doesn't always work.
I'm pretty sure I'm doing the string replacement wrong? Any explanation or advice would be great.
Noticed it wasn't working when I was comparing a single digit number to a multi digit.
def bigger(a, b):
if a > b:
print ("%s is bigger" % a)
elif a == b:
print ("They are both equal!")
else:
print ("%s is bigger" % b)
a = input("Pick a number: ")
b = input("Pick another number: ")
bigger(a, b)
input by default return String. You need to convert it to numbers. Change the int into float or double, if dealing with decimal numbers
def bigger(a, b):
if int(a) > int(b):
print ("%s is bigger" % a)
elif a == b:
print ("They are both equal!")
else:
print ("%s is bigger" % b)
a = input("Pick a number: ")
b = input("Pick another number: ")
bigger(a, b)
a = input("Pick a number: ")
b = input("Pick another number: ")
input() is always represented as a string and not an integer so in order to run comparisons like if a > b you must first convert it to an integer, like this:
a = int(input("Pick a number: "))
b = int(input("Pick another number: "))
The reason your program works is because Python is comparing the individual sizes of your strings. So "32" starts with a 3 while "122" starts with a 1 so 32 is larger.
>>> '122'<'32'
True
>>> '44'>'1333333'
True
There is a similar question on this website but I found the answers were only for string outputs. e.g dramatically different things. Imagine if I have this python program:
#!/usr/bin/env python
def printAndReturnNothing():
x = "hello"
print(x)
def printAndReturn():
x = "hello"
print(x)
return x
def main():`enter code here`
ret = printAndReturn()
other = printAndReturnNothing()
print("ret is: %s" % ret)
print("other is: %s" % other)
if __name__ == "__main__":
main()
What do you expect to be the output?
hello
hello
ret is : hello
other is: None
However, the question is to define a function called avg4. It asks the user for four numbers and returns the average of four numbers. The second question asks to define a function called avg. It asks the user for three numbers and prints the average.
Wouldn't these be the same output?
This is my code for avg4:
def avg4(a,b,c,d):
a=int(input(ënter a number")
b
c
d
avg=a+b+c+d/4
return
When I call it it prompts the user to enter four numbers, but doesn't return anything. While the second one, avg will print the average.
You need to return something using a return statement at the end of your def. There's also some other changes you needed to make. Your new code would be this:
def avg4(): # You don't need parameters for this function; they're overwritten by your input
a=int(input("Enter a number")) # Added missing quote and bracket
b=int(input("Enter a second number")) # Filled in inputs for b, c and d
c=int(input("Enter a third number"))
d=int(input("Enter a fourth number"))
avg=(a+b+c+d)/4 # Changed to suit BODMAS
return avg # Returns the variable avg
Now you can do this because avg returns something:
result = avg()
Your avg4 function have several issues. Try to use
def avg4():
a=int(raw_input("Enter a number").strip())
b=int(raw_input("Enter a second number").strip())
c=int(raw_input("Enter a third number").strip())
d=int(raw_input("Enter a fourth number").strip())
avg=float(a+b+c+d)/4.0 # avg must be float, not int
return avg
...
print avg4()
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.