In this session, we will delve into the foundational concepts of variables and data types in Python. This session is crucial for establishing a strong understanding of how Python handles data, which is fundamental for writing efficient and error-free code. We will explore how variables are used to store data, the types of data that can be stored, and how to convert between different types of data. Additionally, we will learn how to document code using comments to enhance readability and maintainability.

Meta Data

  • Lecture Title: Variables and Data Types
  • Session Number: 2
  • Duration: 60 minutes
  • Target Audience: Beginners to Intermediate Python learners
  • Prerequisites: Basic understanding of Python syntax and familiarity with basic programming concepts
  • Learning Objectives:
    • Understand the concept of variables and their usage in Python
    • Learn about fundamental data types in Python
    • Gain skills in type conversion and type inference
    • Learn to use comments effectively in Python code
    • Apply knowledge through practical exercises and example projects

Table of Contents

  1. Introduction to Variables
  2. Naming Conventions
  3. Fundamental Data Types
  4. Type Conversion and Type Inference
  5. Comments in Python
  6. Exercises
  7. Example Projects
  8. Conclusion

Introduction to Variables in Python

Objective: Understand what variables are, how they work in Python, and how to use them effectively.

What is a Variable?

Think of a variable as a container that holds information. You can give this container a name so you can easily access the information it contains. For example, if you have a container labeled “age,” you might store the number 25 in it. Later, you can use this label to refer to the number 25, update it, or perform operations with it.

Variables in Python

Python is a programming language that makes working with variables easy and flexible. Here’s a breakdown of how variables work in Python:

  1. Dynamic Typing:
    • Python automatically determines the type of a variable based on the value assigned to it. You don’t need to specify the type explicitly. This makes Python simpler to use, as you can change the type of a variable by assigning a new value of a different type.

Example:

age = 25  # 'age' is an integer
age = "Twenty-Five"  # Now, 'age' is a string
  1. Creating Variables:
    • To create a variable, you use the = operator to assign a value to a name.

Syntax:

variable_name = value

Examples:

temperature = 23.5  # 'temperature' holds a float value of 23.5
name = "Alice"      # 'name' holds a string value "Alice"
  1. Case Sensitivity:
    • Variable names in Python are case-sensitive. This means that age, Age, and AGE are considered different variables.

Example:

age = 25
Age = 30
  1. Naming Rules:
    • Variable names should start with a letter or an underscore and can include letters, digits, and underscores. They cannot start with a digit or be a reserved keyword in Python.

Examples of Valid Names:

  • user_age
  • total_price
  • _count

Examples of Invalid Names:

  • 25_age (Starts with a digit)
  • user age (Contains a space)
  • for (Reserved keyword)

Example Code

Here’s a simple program demonstrating the use of variables:

# Declaring variables
name = "Alice"
age = 30
height = 1.65
is_student = True

# Using variables
print(f"Name: {name}")          # Outputs: Name: Alice
print(f"Age: {age}")            # Outputs: Age: 30
print(f"Height: {height}m")     # Outputs: Height: 1.65m
print(f"Is a student: {is_student}")  # Outputs: Is a student: True

In this code:

  • name, age, height, and is_student are variables that store different types of data.
  • The print statements use these variables to display their values.

Naming Conventions in Python

Objective: Understand the best practices for naming variables, functions, and other identifiers in Python to enhance code readability and maintainability.

Why Naming Conventions Matter

Naming conventions are important because they help make your code more readable and maintainable. When you use consistent and descriptive names, it’s easier for you and others to understand what your code does. Good naming practices also reduce errors and make code easier to debug and extend.

General Naming Guidelines

  1. Be Descriptive:
    • Use names that clearly describe the purpose or meaning of the variable or function. Avoid ambiguous names.

Example:

# Good
user_age = 30

# Bad
ua = 30
  1. Be Consistent:
    • Stick to a consistent naming style throughout your codebase. This consistency helps others understand your code quickly.
  2. Avoid Single-Character Names:
    • Single-character names (except for counters or iterators) are generally discouraged because they don’t convey any meaning.

Example:

# Good
number_of_students = 25

# Bad
n = 25
  1. Use Meaningful Names:
    • Choose names that convey the role of the variable or function.

Example:

# Good
total_price = 100.0

# Bad
tp = 100.0
  1. Avoid Reserved Keywords:
    • Don’t use Python reserved keywords (e.g., if, for, class) as variable or function names.

Naming Conventions in Python

Python follows several conventions for naming variables, functions, classes, and modules. Adhering to these conventions helps keep your code clean and consistent with the Python community’s practices.

  1. Variable and Function Names:
    • Style: Use lowercase letters and separate words with underscores (snake_case).
    • Examples:
user_name = "Alice"
calculate_total_price()
  1. Constants:
    • Style: Use uppercase letters and separate words with underscores.
    • Examples:
MAX_LIMIT = 100
DEFAULT_TIMEOUT = 30
  1. Class Names:
    • Style: Use CapitalizedWords (PascalCase) for class names.
    • Examples:
class StudentRecord:
    pass

class UserProfile:
    pass
  1. Module and Package Names:
    • Style: Use lowercase letters and separate words with underscores (snake_case) for module names. For packages, use lowercase letters and avoid underscores.
    • Examples:
# Module name
data_processing.py

# Package name
utilities
  1. Private Members:
    • Style: Use a single underscore prefix for variables and methods intended to be private to a module or class.
    • Examples:
class Example:
    def __init__(self):
        self._private_variable = 42

    def _private_method(self):
        pass
  1. Special Methods:
    • Style: Use double underscores (dunder) before and after special methods (e.g., __init__, __str__).
    • Examples:
class Example:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"Example with value {self.value}"

Example Code

Here’s a simple Python script illustrating proper naming conventions:

# Constants
MAX_ATTEMPTS = 5
DEFAULT_USERNAME = "guest"

# Function
def calculate_area(radius):
    """Calculate the area of a circle given its radius."""
    PI = 3.14159
    return PI * (radius ** 2)

# Class
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        """Return the area of the circle."""
        return calculate_area(self.radius)

In this code:

  • MAX_ATTEMPTS and DEFAULT_USERNAME follow the convention for constants.
  • calculate_area and area use snake_case for functions.
  • Circle uses PascalCase for class names.

Data Types in Python: Integers, Floats, Strings, and Booleans

Objective: Understand the fundamental data types in Python: integers, floats, strings, and booleans. Learn how to use these types effectively in your code.’

1. Integers (int)

Definition: Integers are whole numbers without a fractional component. They can be positive, negative, or zero.

Characteristics:

  • No Decimal Points: Integers do not include decimal points.
  • Arbitrary Size: Python’s integers can be of any size, limited only by available memory.

Examples:

age = 25          # Positive integer
temperature = -5  # Negative integer
zero = 0          # Zero

Operations:

  • You can perform arithmetic operations such as addition, subtraction, multiplication, and division with integers.

Example:

a = 10
b = 3
sum = a + b          # sum is 13
difference = a - b   # difference is 7
product = a * b      # product is 30
quotient = a // b    # quotient is 3 (integer division)

2. Floats (float)

Definition: Floats are numbers that contain a fractional part, represented with decimal points.

Characteristics:

  • Decimal Points: Floats can represent numbers with decimal values.
  • Precision: Floats are approximate representations of real numbers and may have precision limitations.

Examples:

height = 1.75         # Positive float
temperature = -0.5    # Negative float
pi = 3.14159          # Float representing Pi

Operations:

  • Floats support arithmetic operations, including addition, subtraction, multiplication, and division.

Example:

x = 5.5
y = 2.0
sum = x + y           # sum is 7.5
difference = x - y    # difference is 3.5
product = x * y       # product is 11.0
quotient = x / y      # quotient is 2.75

3. Strings (str)

Definition: Strings are sequences of characters used to represent text. They are enclosed in single quotes (') or double quotes (").

Characteristics:

  • Immutable: Strings cannot be changed after they are created. Operations on strings return new strings.
  • Support for Various Operations: Strings support concatenation, repetition, and slicing.

Examples:

name = "Alice"             # String with double quotes
greeting = 'Hello, World!' # String with single quotes
multi_line_string = """This is a
multi-line string."""     # Multi-line string

Operations:

  • Concatenation: Joining strings together using the + operator.
  • Repetition: Repeating strings using the * operator.
  • Slicing: Extracting substrings using indexing and slicing.

Example:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name  # Concatenation, full_name is "John Doe"

repeated = "Hello! " * 3  # Repetition, repeated is "Hello! Hello! Hello! "

substring = full_name[0:4]  # Slicing, substring is "John"

4. Booleans (bool)

Definition: Booleans represent truth values and can be either True or False. They are used for conditional statements and logical operations.

Characteristics:

  • Binary Values: Booleans are binary in nature, representing the two states: true or false.
  • Commonly Used in Conditions: Used in control flow statements to determine the execution of code blocks.

Examples:

is_active = True   # Boolean representing true
is_logged_in = False  # Boolean representing false

Operations:

  • Logical Operations: Booleans can be combined using logical operators like and, or, and not.

Example:

a = True
b = False
result_and = a and b    # result_and is False
result_or = a or b      # result_or is True
result_not = not a      # result_not is False