Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python function
#5
You can use default arguments, str concatenation and format-strings.

def hydrocarbon(carbon, hydrogen=None, oxygen=None):
    result = f"C{carbon}"

    if hydrogen:
        result += f"H{hydrogen}"
    if oxygen:
        result += f"O{oxygen}"

    return result
This does only generate the str and does not check, if anything is valid.
In the function specification, you can see that hydrogen and oxygen are assigned to None.
Checking a None of truthiness returns False.
So if you don't set hydrogen or oxygen, those branches are not executed, because they are None.

The += is an inline addition. This works also with str.

greeting = "Hello"
greeting += " "
greeting += "World"
The f in front of the quotes marks the str literal as format string.

name = "all"

# name is replaced by the str content of name
greeting = f"Hello {name}"
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
python function - by Ali_ - Mar-10-2022, 10:25 AM
RE: python function - by Gribouillis - Mar-10-2022, 10:44 AM
RE: python function - by DeaD_EyE - Mar-10-2022, 10:50 AM
RE: python function - by Ali_ - Mar-10-2022, 12:25 PM
RE: python function - by DeaD_EyE - Mar-10-2022, 12:40 PM
RE: python function - by deanhystad - Mar-11-2022, 07:16 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020