Skip to content

Instantly share code, notes, and snippets.

@nax3t
Last active February 28, 2024 20:29
Show Gist options
  • Save nax3t/cd85c3422786b1dc3dd7016d20861363 to your computer and use it in GitHub Desktop.
Save nax3t/cd85c3422786b1dc3dd7016d20861363 to your computer and use it in GitHub Desktop.
Python Basics Lesson for Web Development FUNdamentals Episode 3.

Python Basics

Welcome to the exciting world of Python programming!

Python's simplicity and power make it a top choice for software engineering, data analysis, and beyond. With Python, you can automate tasks, analyze data, build web applications, and even create AI. Today, we'll delve into the basics, setting the stage for your exploration of Python's endless possibilities. Let's dive in and unlock the potential of Python together!

Objectives

By the end of this lecture, you will:

  1. Understand essential programming concepts in Python.
  2. Become familiar with variables and data types.
  3. Understand assignment and comparison operators.
  4. Grasp control flow mechanisms like conditional statements and looping.
  5. Learn how to define and use simple functions in Python.

Python Basics

Variables and Data Types

In Python, variables are like containers for storing data values. Unlike some languages, you don't need to declare a variable's type explicitly—Python is dynamically typed, meaning the variable assumes the type of the data that is assigned to it.

# Examples of variables
name = "Alice"  # String
age = 30        # Integer
height = 5.5    # Float
is_student = True  # Boolean

Variables are essentially names attached to particular objects in Python. To write clean and maintainable code, following the naming conventions and rules is crucial. Here are key points to keep in mind:

  • Names can include letters, digits, and underscores (_). However, they cannot start with a digit.
  • Case matters: Car and car are treated as distinct variables.
  • Avoid using Python's built-in function names (like list, str) to avoid name clashes and potential bugs.
  • Use meaningful names: Choosing descriptive and meaningful names makes your code much more readable and maintainable. For example, user_age is better than just a.
  • Follow a convention: The Python community typically uses snake_case for variable names (all lowercase letters with underscores between words).

Python offers a variety of data types, some of the primary ones include:

  1. Integers (int): Whole numbers, positive or negative, without decimals. Example: 5, -3.
  2. Floating-point (float): Numbers with a decimal point or in exponential (E) form. Example: 3.14, -0.001, 2e2.
  3. Strings (str): A sequence of characters enclosed in quotes. Example: "Hello", 'Python3'.
  4. Booleans (bool): Holds True or False values, typically resulting from comparisons or conditions.
  5. Lists (list): Ordered, mutable collections of items (which can be of mixed types). Example: [1, "two", 3.0].
  6. Tuples (tuple): Ordered, immutable collections of items. Example: (1, "two", 3.0).
  7. Dictionaries (dict): Ordered collections of key-value pairs. Example: {"name": "Alice", "age": 30}.
  8. Sets (set): Ordered collections of unique items. Example: {1, 2, 3}.
  9. NoneType (None): Represents the absence of a value or a null value.

Assignment and Comparison Operators

Assignment Operators

Assignment operators are used to assign values to variables. The most common one is the equals (=) sign.

x = 10  # x is now 10
x += 5  # Equivalent to x = x + 5, x is now 15

Other assignment operators include -= (subtract and assign), *= (multiply and assign), /= (divide and assign), etc., used in a similar manner.

Comparison Operators

Comparison operators compare values and return a boolean result (True or False). Here are the primary comparison operators:

  • Equal to (==): Checks if the values on either side are equal.
  • Not equal to (!=): Checks if two values are not equal.
  • Greater than (>), Less than (<): Compare two values.
  • Greater than or equal to (>=), Less than or equal to (<=): Compare two values with inclusivity.
a = 5
b = 10
print(a == b)  # False
print(a != b)  # True
print(a < b)   # True

Control Flow: Conditional Statements

Control flow allows you to execute certain parts of your code based on conditions. The if, elif, and else statements are the main players here.

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

Looping

Looping in Python enables you to execute a block of code multiple times. for loops are great for iterating over items of a collection (like a list). while loops keep running as long as a condition is True.

# For loop example
for i in range(5):  # Will print numbers 0 to 4
    print(i)

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

Basic Functions

Functions allow you to encapsulate code for reuse and clarity. In Python, functions are defined using the def keyword, followed by the function's name and a set of parentheses. These parentheses may contain optional (comma separated) parameters, which specify the input (arguments) expected by the function when it is called (invoked/run/executed). The area of the function where we write all of our logic is called the body of the function. It is denoted by an indentation of our code. Once we de-indent our code to be in line with the def keyword, we are no longer inside of the function body. By convention, code that follows a function definition is usually preceded by two empty lines.

Let's examine an example:

def greet(name):
    # This function takes a name as input and returns a greeting message.
    return "Hello, " + name + "!"

In this function named greet, name is a required argument. Within the function, we access the name parameter and concatenate it (glue it together) with a greeting message. Finally, we return the resulting string back out to the program where the function was first called. In the example below, the function call is wrapped in a print function, which prints the result to the terminal.

To call this function and greet someone named "Alice," we simply write:

print(greet("Alice"))

This will output:

Hello, Alice!

Conclusion and Review

Congratulations! You've just taken your first steps into Python programming. Today, we learned:

  • Variables in Python are used to store data of various types such as strings, integers, and floating-point numbers, without explicitly declaring their type.
  • Various operation characters such as the equal sign are used for things like variable assignment and comparison.
  • Conditional statements (if, elif, else) guide the flow of your program based on conditions.
  • Looping (for and while loops) enables repetitive execution of code blocks.
  • Functions allow for code reuse and structure by encapsulating blocks of code.

This knowledge sets the stage for you to dive deeper into more complex programming concepts, explore libraries, and start building your own Python projects. I urge you to practice what we've covered today by writing simple programs or scripts. Remember, the path to mastery in programming is paved with consistent practice and curiosity. See below for an exercise to get you started!

Code Exercise, FizzBuzz

"""
Functionality of FizzBuzz
- loops over numbers from 1 to 100
- For each number a check is performed
- if a number is divisible by both 3 and 5 then "FizzBuzz" is printed
- if a number is divisible by only 3, then "Fizz" is printed
- if a number is divisible by only 5, then "Buzz" is printed
- if a number is not divisible by 3 or 5 then the number itself is printed
"""
def fizz_buzz():
    pass # replace this line with your own code


fizz_buzz()

View full solution here

Glossary of Python Terms

Below is a glossary of terms used in our Python Basics lesson, each with a brief description and links to more detailed explanations. This glossary will help reinforce your understanding and serve as a handy reference. There's a lot here. By no means do you need to understand it all right away, simply refer back to it as needed while making your way through the material.

Variables

  • Variables: Named locations used to store data in memory. In Python, variables do not need to be declared with any specific type, and can even change type after they have been set.

Data Types

  • Integers (int): Whole numbers, positive or negative, without decimals.
  • Floating-point Numbers (float): Numbers with a decimal point or in exponential form.
  • Strings (str): A sequence of Unicode characters surrounded by single or double quotes.
  • Booleans (bool): Represents True or False.
  • Lists (list): Ordered collection of items.
  • Tuples (tuple): Immutable ordered collection of items.
  • Dictionaries (dict): Unordered collections of key-value pairs.
  • Sets (set): Unordered collection of unique items.
  • None Type (None): Represents the absence of a value.

Operators

Control Flow

Functions

  • Functions: A block of organized, reusable code used to perform a single, related action.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment