Programming Fundamentals/Strings/Python3

From Wikiversity
Jump to navigation Jump to search

strings.py[edit]

# This program splits a given comma-separated name into first and last name
# components and then displays the name.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Python_Programming

def get_name():
    while True:
        print("Enter name (last, first):")
        name = input()
        index = name.find(",")
        if index >= 0:
            break
    return name

def get_last(name):
    index = name.find(",")
    if index < 0:
        last = ""
    else:
        last = name[0:index]
    return last

def get_first(name):
    index = name.find(",")
    if index < 0:
        first = ""
    else:
        first = name[index + 1:]
        first = first.strip()
    return first

def display_name(first, last):
    print(f"Hello {first} {last}!")

def main():
    name = get_name()
    last = get_last(name)
    first = get_first(name)
    display_name(first, last)
    
main()

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.

See Also[edit]