This question already has an answer here:
What is the difference between printing two variables using "+" and "," in Python?
(1 answer)
Closed 2 years ago.
I'm new to python and I just want to know the difference between , and + in python. example:
a = 4
b = "string"
print(a, b)or is it print(a + b)?
The first option you have print(a,b) will print i.e output the contents of what is stored within variable a and variable b respectively (in that order). The output would be: 4, 'string'
Whereas the 2nd option, print(a+b), you will try and add the contents but it won't be possible too as there is a type-casting difference between a and b. The error you would see is this: TypeError: unsupported operand type(s) for +: 'int' and 'str.
And If you really want to concatenate those two variables, you can type-cast the variable a like this: a = str(a) and then go on with adding it to b like so: print(a+b) would output: 4string.
Printing (a, b) will print the integer, then the string followed by it:
4 string
Printing(a + b) will raise an error, because the + sign concatenates two strings, but it is unable to convert the integer to type string.
EXPLANATION:
(a, b) treats the two items as separate elements in a tuple, whereas (a + b) tries to concatenate the two items.
print(a, b)
will print a then b
print(a + b)
is doing a + b and then print it
in your case since the addition of an integer and a string is not defined it raise an error.
Related
This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Convert a string of numbers to a list of integers. Python
(1 answer)
Closed 3 years ago.
In Python I have a string that looks like this:
str = '1,2,3,4'
I have a method that takes four arguments:
def i_take_four_arguments(a, b, c, d):
return a + b + c + d
What do I have to do to string to allow it to be sent to the method?
If you want to perform arithmetic operation, following is one way. The idea is to convert your split string values to integers and then pass them to the function. The * here unpacks the generator into 4 values which are taken by a, b, c and d respectively.
A word of caution: Don't use in-built function names as variables. In your case, it means don't use str
string = '1,2,3,4'
def i_take_four_arguments(a, b, c, d):
return a + b + c + d
i_take_four_arguments(*map(int, string.split(',')))
# 10
str = '1,2,3,4'
list_ints = [int(x) for x in str.split(',')]
This will give you a list of integers, which can be added, pass them to your function
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4
This question already has answers here:
Cannot concatenate 'str' and 'float' objects? [duplicate]
(3 answers)
Closed 8 years ago.
I have been working on a pythagorus theorem calculator on python
Here is my code so far:
a = int(raw_input("what is length a?"))
b = int(raw_input("what is length b?"))
a2 = a*a
b2 = b*b
c2 = a2+b2
c = c2**0.5
print "the length of c is " + c
It will not work on the last line. It throws the following error:
cannot concatenate 'str' and 'float' objects
Does anyone know what's wrong with it?
Just what it says: c is a float, but "the length of c is " is a string. As a quick fix you can do this: "the length of c is " + str(c), but you will want to learn about string formatting.
c is an int, "the length of c is " is a string
You would have to say
print "the length of c is ", str(c)
Try print "the length of c is %.3f" % (c,)
Concatenation is combining strings together, and Python doesn't automatically convert non-strings to strings (unlike Java).
How can I remove ' from the string '/' and use it for division in Python?
For example:
a='/'
b=6
c=3
bac
The answer should be 2.
You can get the built-in operators as functions from the operator module:
import operator
a = operator.div
b = 6
c = 3
print a(b, c)
If you want to get the correct operator by the symbol, build a dict out of them:
ops = {
"/": operator.div,
"*": operator.mul,
# et cetera
}
a = ops["/"]
Python has an eval() function that can do this:
a = "/"
b = "6"
c = "3"
print eval(b + a + c)
However, please note that if you're getting input from a remote source (like over a network), then passing such code to eval() is potentially very dangerous. It would allow network users to execute arbitrary code on your server.
There are no single quotes in the variable a. Python just uses these to denote a represents a string. b and c represent ints and don't have the single quotes. If you ensure all of these variables are strings, you can join() them together:
>>> a='/'
>>> b=6
>>> c=3
>>> bac = ''.join(str(x) for x in (b, a, c))
>>> bac
'6/3'
See how there are single quotes at the beginning and end of the string.
You could then use eval() (with caution) to perform the division:
>>> eval(bac)
2
Related: Is using eval in Python a bad practice?
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4