DEV Community

Cover image for Python: From Beginners to Pro in 30 Mins (Part 2)
Scofield Idehen
Scofield Idehen

Posted on

Python: From Beginners to Pro in 30 Mins (Part 2)

Continuation from Here

What to Focus on as a Python Beginner

As a Python beginner, it's crucial to build a strong foundation. too many YouTube videos without context can overwhelm you. Stick to the basics. Make sure you build a simple application after each session.

Impress only yourself; you are the most important person on your journey, and why you are on your path, you need to understand the fundamentals of Python syntax. This includes:

  • Variables and data types:
    name = "Alex"  # String
    age = 15       # Integer
    height = 5.7   # Float
    is_student = True  # Boolean
Enter fullscreen mode Exit fullscreen mode

In Python, a variable is like a container that holds a value. We use variables to store and manage data in our programs.

In this example, we have four variables: name, age, height, and is_student.

Assignment

  • The = sign is used to assign a value to a variable.
  • For example, name = "Alex" means we're storing the value "Alex" in the variable called name.

    name = "Alex"

  • Strings are used for text data.

  • They are enclosed in quotes (either single ' or double ").

Integer (int)

age = 15
Enter fullscreen mode Exit fullscreen mode
  • Integers are whole numbers without decimal points.

Float

height = 5.7
Enter fullscreen mode Exit fullscreen mode
  • Floats are numbers with decimal points.

Boolean (bool)

is_student = True
Enter fullscreen mode Exit fullscreen mode
  • Booleans represent True or False values.
  • They are often used for conditions and logic in programming.

Comments

  • The # ''' ``''' symbol is used to write comments in Python.
  • Comments are notes for humans and are ignored by Python when running the code.

Variable Naming

  • Variable names in Python should be descriptive and follow certain rules:
  • They can contain letters, numbers, and underscores.
  • They must start with a letter or underscore.
  • They are case-sensitive (e.g., name and Name are different variables).

  • Basic operations:



    x = 5 + 3  # Addition
    y = 10 - 2  # Subtraction
    z = 4 * 3  # Multiplication
    w = 15 / 3  # Division


Enter fullscreen mode Exit fullscreen mode
  • Print statements and string formatting:


    print("Hello, World!")
    print("Hello i am a boy and i am", 5+7 ,"years old")
    name = "scofield"
    age = 29
    print(f"My name is {name} and I'm {age} years old.")


Enter fullscreen mode Exit fullscreen mode

Basic Print Statement

`print("Hello, World!")`
Enter fullscreen mode Exit fullscreen mode
  • The print() function is used to output text to the console.
  • Text inside quotes is a string, which will be printed without changing it.
  • This line will output: Hello, World!

Print with Multiple Arguments



    print("Hello i am a boy and i am", 5+7 ,"years old")


Enter fullscreen mode Exit fullscreen mode
  • You can pass multiple items to print(), separated by commas.
  • Python will automatically add spaces between these items.

5+7 is an expression that Python will evaluate (to 12) before printing.

This line will output: Hello, i am a boy and i am 12 years old

*****Variables in Print Statements*



    name = "scofield"
    age = 29


Enter fullscreen mode Exit fullscreen mode
  • Here, we're defining two variables: name and age.
  • These variables can be used in our print statements.

F-Strings (Formatted String Literals)



    print(f"My name is {name} and I'm {age} years old.")


Enter fullscreen mode Exit fullscreen mode

F-strings provide an easy way to embed expressions inside string literals. once we start the string with f before the opening quotation mark, variables or expressions in curly braces {} will be replaced with their values.

This line will output: My name is scofield and I'm 29 years old.

Key Points:

  • The print() function is used to display output in Python.
  • You can print strings, numbers, variables, and even the results of expressions.
  • Commas in print() separate multiple items and add spaces between them.
  • F-strings (starting with f) allow you to easily include variable values in strings.
  • Curly braces {} in f-strings are placeholders for variables or expressions.

Control Flow: Learn how to control the flow of your program

  • If statements

we use if statements to control which parts of our code run based on whether certain conditions are true or false. For example, imagine you are contemplating between two choices or more than two choices, and you then say if this choice does not work, the other will or the third choice will.

If statement is a probability based on your options.

Let's break down the example:



    if age >= 18:
        print("You're an adult.")
    elif age >= 13:
        print("You're a teenager.")
    else:
        print("You're a child.")


Enter fullscreen mode Exit fullscreen mode

First, we have the if statement. It starts with the keyword if, followed by a condition. In this case, the condition is age >= 18. This is asking, "Is the age 18 or greater?" If this condition is true, the code indented under this line will run. So if someone is 18 or older, they'll see "You're an adult." printed.



    if age >= 18:
        print("You're an adult.")


Enter fullscreen mode Exit fullscreen mode

But what if they're not 18 or older? That's where the 'elif' comes in. 'elif' is short for "else if". It's like saying, "If the first condition wasn't true, let's check this one instead." Here, we're checking if 'age >= 13'. So if someone is 13 or older (but not 18 or older because the first condition would have caught that), they'll see “You're a teenager." printed.



    elif age >= 13:
        print("You're a teenager.")


Enter fullscreen mode Exit fullscreen mode

Finally, we have the else statement. This is like a catch-all. If none of the above conditions were true, this code will run. So if someone is neither 18 or older, nor 13 or older, they must be younger than 13, and they'll see "You're a child." printed.



    else:
        print("You're a child.")


Enter fullscreen mode Exit fullscreen mode

It's important to note the indentation in Python. The code that should run if a condition is true must be indented under that condition. This is how Python knows which code belongs to which part of the if-elif-else structure.

NOTE: Indentation is very important and can ruin your code if you do not learn it properly; I had a lot of issues with indention at the beginning until I came up with a personal cheat sheet where I have everywhere indentation can be used and mastered the list.

After a colon (:) Indentation is required after any line that ends with a colon. This includes:

  • If statements
  • Elif and else clauses
  • For and while loops
  • Function definitions
  • Class definitions
  • With statements
  • Try/except blocks

  • Continuation of long lines When a line of code is too long, and you need to split it across multiple lines, the continuation lines are often indented.

  • Nested structures: When you have structures inside other structures (like a loop inside an if statement), each level needs its indentation.

Let us return to our if statement and master it properly. Imagine you're creating a simple age-based recommendation system for a movie streaming service. Here's how you might use an if statement:



    age = int(input("Please enter your age: "))

    if age >= 18:
        print("You can watch all movies, including R-rated ones.")
    elif age >= 13:
        print("You can watch PG-13 movies and below.")
    else:
        print("You can only watch G and PG rated movies.")


Enter fullscreen mode Exit fullscreen mode

This script asks the user for their age and then uses an if-elif-else structure to provide a recommendation based on that age.

A quick quiz to check your understanding

Let's say you run this code and input the age 15. What message will be printed, and why?

Take a moment to think about it. Remember to consider the order of the conditions. When ready, explain your answer in the comment below.

Loops in Python



    # For loop
    for i in range(5):
        print(i)

    # While loop
    count = 0
    while count < 5:
        print(count)
        count += 1


Enter fullscreen mode Exit fullscreen mode

Loops are used to repeat a block of code multiple times. They're incredibly useful when you want to perform the same action over and over, or when you need to process each item in a collection. Let's look at the two main types of loops in Python:

For Loops
A for loop iterates over a sequence (like a list, tuple, or string) or other iterable objects. It's particularly useful when you know in advance how many times you want to execute a block of code.



    for item in each sequence:
        # Code to be repeated


Enter fullscreen mode Exit fullscreen mode

Example:


python
    # For loop
    for i in range(5):
        print(i)


Enter fullscreen mode Exit fullscreen mode

In this example:

  • range(5) creates a sequence of numbers from 0 to 4.
  • The loop variable i takes on each value in this sequence.
  • The indented code block (print(i)) is executed for each value of i.

Output:

0
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

When to use: Use a for loop to iterate over a known sequence of items or a specific number of times.

While Loops
A while loop repeats a block of code as long as a given condition is true. It's useful when you don't know in advance how many times you need to repeat the code.

Basic Syntax:

while condition:
    # Code to be repeated
Enter fullscreen mode Exit fullscreen mode

Example:



    # While loop
    count = 0
    while count < 5:
        print(count)
        count += 1


Enter fullscreen mode Exit fullscreen mode

In this example:

  • We start with count = 0.
  • The loop continues as long as count < 5 is true.
  • Inside the loop, we print the current value of count and then increase it by 1.
  • This process repeats until count reaches 5, at which point the condition becomes false and the loop ends.

What if we remove count += 1? We have an endless loop because count would keep printing out the first iteration of 0 as it does not know if it has counted the first item.

This situation perfectly illustrates why it's crucial in while loops to have a way to update the condition. Without count += 1, we've removed the loop's ability to progress and eventually terminate.

But when we include the count += 1 we can check if we have iterated over each item and move on to the next.

Output:

0
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

When to use: Use a while loop when you must repeat an action until a certain condition is met, especially when you don't know how many iterations will be needed.

Key Points for Beginners

  1. Indentation: Remember that the code block to be repeated must be indented. This is crucial in Python.
  2. Infinite Loops: Be careful with while loops. If the condition never becomes false, you'll create an infinite loop. Always ensure there's a way for the loop condition to become false.
  3. Loop Variables: In for loops, the loop variable (like i in our example) is automatically updated each iteration. In while loops, you typically need to update the variable yourself.
  4. Range Function: range(n) creates a sequence from 0 to n-1. It's commonly used with for loops.
  5. Incrementing: count += 1 is a shorthand for count = count + 1. This is often used in while loops to update the counter.

Practice Exercise
Try writing a loop that prints out the even numbers from 0 to 10. You can use either a for loop or a while loop. Think about which might be more appropriate and why.

Remember, the key to understanding loops is practice. Try modifying the examples, experiment with different conditions and sequences, and see what happens. Don't be afraid to make mistakes.

Top comments (0)