Ashok
Ashok

Reputation: 214

Python function: multiple arguments

I need to define a function T(i) which has the same value (say 10) from i=1 to 1=3, and a different value (say 20) at i=4. I wrote the following code,

def T(i):
for i in range(1, 4):
    y= 10
    return y
if i==4:
    y= 20
    return y

for i in range(1, 5): print(i,T(i))

Values from i=1 to 1=3 are printed correctly, but the value at i=4 is wrong. Seems like the second argument is not assigned correctly. Please help.

Thanks in advance.

Upvotes: 2

Views: 85

Answers (2)

Trelzevir
Trelzevir

Reputation: 765

There is no need for the for loop in the function, as you call T() from a loop anyway, and return will exit the function, so the if statement cannot execute.

An easier way to do this is:

def T(i):
    return 20 if i==4 else 10

However, defining a function is not necessary to accomplish this, you could implement the same condition in a list comprehension:

[20 if i==4 else 10 for i in range(1,5)]

Upvotes: 1

Sarvex
Sarvex

Reputation: 785

You need to have the special case handled first

def T(i):
  if i < 4:
    return 10
  else:
    return 20

for i in range(1, 5): print(i,T(i))

Upvotes: 1

Related Questions