A Friendly Beginner's Guide to Learn Python by reading and tried out code and see how and why it works. Let's embark on a journey into the world of programming.

Python Practice - Part One

Whether you aspire to become a web developer, data scientist, or simply want to automate everyday tasks, learning Python is the skill to have. In this article, we'll provide you with some code examples to kickstart your Python journey and lay a solid foundation for your programming endeavors.

Spoiler Alert! The following piece or block of code are from my experience learning with the CS50-Python program provided by the Harvard University (find CS50 course here). It is a free Python course that takes you from Zero to a really, really good understanding of programming in general. Also note that my code is not a "stand alone-way to go, or the best way to do it", it is just my personal approach.

Let's get started!

I am going to start by talking about FUNCTION! I know a lot of developer and coder out there will disagree with me. Some will tell you that a beginner should not start learning what a function is, that a beginner should start by learning the basics like for example, playing with variables, and type to understand them etc... It's up to you to blieve them or not. No More Comment!

What is function?

In many programming language out there, a function is a block of reusable code that performs a specific task or set of tasks. In Python programming functions are fundamental building blocks, allowing you to organize code into logical units, improve code readability, and promote code reusability. Functions in Python follow a specific syntax and can accept inputs (arguments) and return outputs (the results).

When learning a programming language the best thing you have to do to get started is to learn about the basic syntax of this programming language. Here's the basic syntax of a function in Python:

def function_name(parameters):
    """
    Docstring: Optional documentation for the function
    """
    # Function body: Code that defines what the function does
    # Perform tasks using parameters and/or other variables
    # Return a result if necessary
    return result

Let's break down the components of a function:

  1. def keyword: Functions in Python are defined using the def keyword, followed by the name of the function.

  2. function_name: This is the identifier for the function. Choose a descriptive name that reflects the purpose of the function.

  3. parameters: Parameters (also known as arguments) are optional values that you can pass to the function. They allow you to provide input data for the function to work with. Parameters are enclosed in parentheses and separated by commas.

  4. Docstring: The docstring is an optional string literal that provides documentation for the function. It describes the purpose of the function, its parameters, and its return value. Docstrings are enclosed in triple quotes (""" """) and are typically placed immediately after the function definition.

  5. Function body: The function body contains the code that defines what the function does. It consists of one or more statements that perform specific tasks. These statements are indented to indicate that they belong to the function.

  6. return statement: The return statement is used to specify the value that the function should return after completing its tasks. It is optional, and a function may have multiple return statements or none at all. If the function does not include a return statement, it implicitly returns None.

Calling a function in Python involves invoking it by its name and providing any required arguments within parentheses. Here's a breakdown of how to call a function:

  1. Function Name: Write the name of the function you want to call.

  2. Arguments: If the function requires any arguments (parameters), provide them within parentheses. These arguments are passed to the function and used within its body to perform tasks.

The following function calculates and "Expression" from the user. Assumint the user want to know the result for 5 * 25, or 19876 / 184, or 45 - 9, or even return an error message if the user fail to do what the program was expected.

We can end up with a small function like this:

# Define the function
def calculator():
    expression = input("Expression: ")
    left_num, mid_num, right_num = expression.split()

    if mid_num == '+':
        print(float(left_num) + float(right_num))
    elif mid_num == '-':
        print(float(left_num) - float(right_num))
    elif mid_num == '*':
        print(float(left_num) * float(right_num))
    elif mid_num == '/':
        print(float(left_num) / float(right_num))
    elif mid_num == '%':
        print(float(left_num) % float(right_num))
    else:
        print("you can only use the following operator: +, -, *, /, % ")

# Calling the function
calculator()

In this smal function we are using if, elif and else statement.

In Python, the if, elif (short for "else if"), and else statements are used for conditional execution, allowing you to control the flow of your code based on certain conditions. These statements help you make decisions and execute specific blocks of code depending on whether conditions are true or false.

  • The if statement is used to execute a block of code only if a specified condition evaluates to True. 
  • Also in some cases you may have an if statement stand alone "itself" without any other elif and/or else statements.
  • The elif statement allows you to check additional conditions if the preceding if or elif conditions are False. You can have multiple elif statements, and they are evaluated sequentially until one of the conditions is True or until there are no more conditions left to check.
  • The elif statement is optional and can appear zero or more times after the initial if statement.
  • If the condition associated with an elif statement evaluates to True, the corresponding block of code is executed, and subsequent elif and else statements are skipped.
  • If no elif conditions are true and there is an else clause, the block of code following the else statement is executed.
  • The else statement is used to define a block of code that will execute when the preceding if and elif conditions are False. It is optional and appears after all if and elif statements.
  • The else statement is paired with an if statement and is used to provide an alternative action if the if condition evaluates to False.
  • The else statement cannot exist without an if statement.
  • And finally, the else statement must be the last part of the conditional statement.

Now let's talk about the following line of code: expression = input("Expression: "), specially the input keyword:

This line of code is prompting the user to enter an expression and storing the input in the variable named expression. Let's break it down:

  • input("Expression: "): This function call displays the string "Expression: " as a prompt to the user in the terminal or console. The user is expected to input a value after this prompt.

  • The input() function then waits for the user to input some text and press Enter.

  • Whatever the user enters is treated as a string and returned by the input() function.

  • Finally, the value returned by input() is assigned to the variable expression, which allows you to access and manipulate the user's input in subsequent code.

What about the following line of code: left_num, mid_num, right_num = expression.split()

Note that the line of code:

left_num, mid_num, right_num = expression.split()

is the same as doing the following:

left_num = input("First number: ")
mid_num = input("Operator: ")
right_num = input("Last number: ")

Here's an example of how it would work:

expression = "10 + 20"
left_num, mid_num, right_num = expression.split()
print(left_num)   # Output: "10"
print(mid_num)    # Output: "+"
print(right_num)  # Output: "20"

You can already have an idea about what the split() is doing in this case. In this example, the string "10 + 20" is split into three parts: "10", "+", and "20", which are assigned to the variables left_num, mid_num, and right_num, respectively.

The resulting list contains substrings extracted from the original string, separated by whitespace.  This line: left_num, mid_num, right_num = expression.split() uses Python's multiple assignment feature, also known as Unpacking, to assign the substrings from the list returned by split() to the variables left_num, mid_num, and right_num.

In the following example we are going to prompt the user with the following message: What time is it?, and display the result base on the time of the day.

def main():
    day_time = input("What time is it? (HH:MM) ")
    convert(day_time)

def convert(time):
    hours, minutes = time.split(":")  # print(type(hours)) is str

    hours = int(hours)  # print(type(hours)) is converted to int
    minutes = int(minutes)

    # Converting time to decimal format
    decimal_time = hours + minutes / 60  # print(decimal_time) is now in decimal format

    if 7 <= decimal_time < 12:
        print("Breakfast time")
    elif 12 <= decimal_time < 18:
        print("Lunch time")
    elif decimal_time >= 18:
        print("Dinner time")

    return decimal_time


if __name__ == "__main__":
    main()

If you test the code you can have some results as the following:

The following code implement a program that prompts the user to insert a coin, one at a time, each time informing the user of the amount due. Once the user has inputted at least 50 cents, output how many cents in change the user is owed. Assume that the user will only input integers, and ignore any integer that isn’t an accepted denomination. only accepts coins in these denominations: 25 cents, 10 cents, and 5 cents.

coke_price = 50
amounts = [25, 10, 5]
coin = 0

while True:
    print(f"Amount Due: {coke_price}")
    coin = int(input("Insert Coin (25, 10, or 5): "))

    if coin not in amounts:
        continue  # Go back to the start of the loop

    if coke_price <= coin:
        coin -= coke_price
        print(f"Change Owed: {coin}")
        break

    coke_price -= coin

The above code is not a function but only introducing a while loop befor use it inside our next function.

Let's breat it down the code step-by-step:

  1. coke_price = 50: This line assigns the value 50 to the variable coke_price, representing the price of a coke in cents.

  2. amounts = [25, 10, 5]: This line creates a list named amounts containing the values [25, 10, 5], representing the valid coin denominations that can be inserted (in cents).

  3. coin = 0: This line initializes the variable coin to 0. This variable will store the value of the coin inserted by the user.

  4. while True:: This line starts an infinite loop. The loop will continue indefinitely until a break statement is encountered.

  5. print(f"Amount Due: {coke_price}"): This line prints the current amount due for the coke, using f-string formatting to insert the value of coke_price.

  6. coin = int(input("Insert Coin (25, 10, or 5): ")): This line prompts the user to insert a coin and stores the input as an integer in the variable coin.

  7. if coin not in amounts:: This line checks if the value of coin is not present in the list amounts (i.e., if the inserted coin is not valid). If it's not valid, it continues to the next iteration of the loop using the continue statement.

  8. if coke_price <= coin:: This line checks if the current coke_price is less than or equal to the value of coin inserted by the user. If it's true, it means the inserted coin is sufficient to cover the cost of the coke.

    • If true, it subtracts the coke_price from the inserted coin to calculate the change owed (coin -= coke_price), prints the change owed, and exits the loop using the break statement.
  9. coke_price -= coin: This line subtracts the value of coin from coke_price, effectively reducing the amount due by the value of the coin inserted.

If you test the code on your own you may end up with something like this:

In the following function we are going to implement a program that prompts the user for items, one per line, until the user inputs control-d (Ctrl+D), then output the user’s grocery list in all uppercase, sorted alphabetically by item, prefixing each line with the number of times the user inputted that item. No need to pluralize the items. Treat the user’s input case-insensitively. 

Side note: If you are using Visual Studio Code on Windows you will have to use control-z (Ctrl+Z) instead of Ctrl+D.

def my_list():
    item_list = []
    item_dict = {}

    while True:
        try:
            user_input = input().strip().upper()
            item_list.append(user_input)
        except EOFError:
            # iterate through the item_list (list:[]) and add the items in the item_dict (dictionary: {})
            for item in item_list:
                if item in item_dict:
                    item_dict[item] += 1
                else:
                    item_dict[item] = 1
                # print(item_dict)

            # iterate through the item_dict (dictionary: {}) by sorting the keys alphabetically
            for key in sorted(item_dict.keys()):
                # get the value in the count variable
                count = item_dict[key]
                print(f"{count} {key}")
            break
        except KeyError:
            break
        except ValueError:
            break


my_list()

 

An example of the result:

Valid Plate function example

In the following function we will implement a program that prompts the user for a vanity plate and then output Valid if the plate meets all of the requirements or Invalid if it does not. Assume that any letters in the user’s input will be uppercase.

Actually here is the challenge from CS50 with details:
In Massachusetts, home to Harvard University, it's possible to request a vanity license plate for your car, with your choice of letters and numbers instead of random ones. Among the requirements, though, are:
"All vanity plates must start with at least two letters."
"… vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters."
"Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable. Vanity plate; AAA22A would not be acceptable. The first number used cannot be a '0'."
"No periods, spaces, or punctuation marks are allowed."

def main():
    plate = input("Plate: ").strip()
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):
    punctuation = ['.', ' ', '-', '?', '/', ';', ':', ',', "'"]

    if 2 <= len(s) <= 6:  # len(s) >= 2 and len(s) <= 6
        # Extract digits from the string
        digits = ''.join(filter(str.isdigit, s))
        # print(s)

        # Check if the first digit is '0'
        if digits and digits[0] == '0':
            return False

        # Check if the last character is a letter
        if digits and s[-1].isalpha():
            return False

        # checks if the current character is an alphabet (a letter)
        is_alpha = False
        is_digit = False

        for char in s:
            if char.isalpha():
                is_alpha = True
                if is_digit:
                    return False
            elif char.isdigit():
                is_digit = True

            # If any character is in the punctuation list, the plate is invalid
            if char in punctuation:
                return False

        if is_digit:
            return is_alpha and is_digit  # If all checks pass, the plate is valid
            # return is_alpha + is_digit  # this line will prevent the test to pass
            # now I use and instead of + sign
        return is_alpha

    return False  # If length is not within the specified range


if __name__ == "__main__":
    main()

If you test the code you may have results like the following:

Note that I have presented simple functions to you, but you can also write more complex functions according to your needs.
I hope this article has made you want to learn a little more about Python and programming in general.

Yardley Estiverne
Yardley Estiverne
AI MVP & Software Developer | AI Tech Entrepreneur

AI MVP Developer - Blazor, C# .NET Developer with good crafted hands-on experience in developing and deploying robust web solutions. Proficient in .NET programming and its associated libraries, with understanding of SQL practices. I also create backend application using Django Rest Framework.

LinkedIn:Yardley

No comments