Reputation: 151
def myfun(x,y):
z=x+y
Print("my x is", x)
Print("my y is", y)
Print("my z is", z)
myfun(1,2)
myfun(3,4)
myfun(5,6)
myfun(x,y)
This is an idea of what I want to do. The first the 3 calls of the function are predetermined, and in the 4th one, I want to promt for user input, is there anyway I can do this with 1 function(without changing the formatting) because the final format needs to be..
my x is 1
my y is 2
my z is 3
my x is 3
my y is 4
my z is 5
my x is 5
my y is 6
my z is 7
my x is (userinput)
my y is (userinput)
my z is ...
Anyone way I can do this correctly with one function?
Upvotes: 2
Views: 491
Reputation: 943
In one line:
#myfun(x,y)
myfun(input("What is value of x? "),input("What is value of y? "))
Upvotes: 0
Reputation: 1505
def myfun(x=0, y=0):
z = x + y
Print("My x is", x)
Print("My y is", y)
Print("My z is", z)
myfun(1,2)
myfun(3,4)
myfun(5,6)
# here you can make a input for x and y and then you type cast the string in int
x = int(raw_input('Input x: '))
y = int(raw_input('Input y: '))
myfun(x,y)
If you use Python 3.x, take input() instead of raw_input()
x = int(input('Input x: '))
y = int(input('Input y: '))
myfun(x,y)
Upvotes: 2
Reputation:
You can't achieve this with ordinary values as parameters, referencing a local variable never does anything extra. You can, however, accept functions which supply a value. Then instead of passing some integer, you pass a function which returns an integer, and instead of changing myfun
to do I/O, you just pass a function which does the I/O.
myfun(lambda: 5, lambda: 6)
# I'm gonna assume Python 3
myfun(input, input)
You need to write the function a bit differently though, because you want the input to happen at a precise point in time. Something like this:
def myfun(x_fun, y_fun):
print("my x is", end=" ")
x = x_fun()
print("my y is", end=" ")
y = y_fun()
z=x+y
print("my z is", z)
Upvotes: 1