What would be the output of this ? I see the output but not able to understand why that happens.
def multiple(x,y):
mul = x*y
return mul
x=int(raw_input("Enter value 1 ")),
y=int(raw_input("Enter value 2 "))
print multiple(x,y)
In your code, the ,
at the end of the first raw_input
means x
is actually a tuple
containing the user input. When you call the function, what you are actually doing is multiplying the tuple by an integer, which just multiplies the tuple ( x
) y
times.
For example:
>>> x = 2,
>>> x * 5
(2, 2, 2, 2, 2)
>>> x = 2
>>> x * 5
10
The comma makes x
equal to a tuple of size 1 (containing the int).
Simple test:
>>> a = 1,
>>> print a
(1,)
A large error with this is that if x and y are not numbers (aka a string), the function would be messed up. This can be fixed by saying: try: mul = float(x) * float(y)
then, to catch the case when x or y are not numbers, except TypeError: print('Please do not give a string...')
In this case, you want to show that mul is not valid, so you say, mul = None
Now you can return mul
in line with the try and except statements.
This ensures that the inputs are decimal point numbers, not characters.
First of all, you define a function called multiple
and it multiplies x
and y
(parameters of multiple
), then returns that value. Then it takes input for two different variables, x
and y
(not the same as the parameters above), multiplies (by calling multiple
), and print
s them out, which is what you see as output.
The comma however, simply defines x
as a tuple.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.