简体   繁体   中英

how to use if statement for function with pre-defined argument

This is my code:

def characters(a=''):
    if a:
        for c in Characters:
            b=c
            print(b)
    else:
        for char in Characters:
            yield char

What I want is, whenever function is called without argument it should print the keys inside dictionary "Characters" and when argument is given it should return the keys instead of printing them. The else statement does it's job but if statement doesn't work.

The if is the wrong way around – the empty string is falsy in Python's eyes.

However, maybe instead of "without argument" you might want an argument default value with some semantics?

def characters(mode='print'):
    if mode == 'print':
        for c in Characters:
            print(c)
    elif mode == 'yield':
        for char in Characters:
            yield char
    else:
        raise ValueError('invalid mode')

This way characters() defaults to printing, characters('print') does the same, and characters('yield') does the other thing (and other values cause an exception).

You could try something like this:

def characters(a=""):
    character_keys = list(Characters.keys())
    if a:
        return character_keys
    else:
        print(character_keys)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM