2

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.

4
  • The if block after the for is unreachable. The first return hands over control to the caller. What exactly are you up to? Commented Feb 25, 2017 at 11:39
  • Your indentation (or lackof) is incorrect, maybe that's the issue. Commented Feb 25, 2017 at 11:40
  • Thanks for the reply ILI, but the indentation is correct in the original code. Commented Feb 25, 2017 at 11:41
  • Thanks for the reply Moses, but how can I fix it ? Commented Feb 25, 2017 at 11:42

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.