PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

[FIXED] Why does this simple code line not work even though it should based on the output?

 August 17, 2022     output, python, python-decorators     No comments   

Issue

When function square(x) gets a var it returns var*var. When the function doesn't get a var it returns a list of all the vars that were used.

def square_or_list(func):
    def wrapper(*arg):
        if not arg:
            return last
        else:
            last.append(arg[0])
            func(arg[0])

    last = []
    return wrapper

@square_or_list
def square(x):
    print(x)
    return x**2

print(square(3))
print(square(4))
print(square())

This is the output:

3
None
4
None
[3, 4]

As you can see the program prints the correct x values but doesn't multiply them.


Solution

You need to return in your else block as well:

 def wrapper(*arg):
    if not arg:
        return last
    else:
        last.append(arg[0])
        # you need to return for the for a correct recursive call
        return func(arg[0])


Answered By - Jarvis
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing