Basics of Python

Introduction

Python is a high-level, interpreted programming language renowned for its simplicity, readability, and versatility. Created by Guido van Rossum and first released in 1991, Python is widely used in web development, data analysis, artificial intelligence, scientific computing, automation, and more. Its syntax is designed to be clear and concise, making it an ideal choice for beginners and experienced developers alike.

Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Its extensive standard library and active community contribute to its popularity.

# This is a single-line comment
"""
This is a multi-line comment
used for documentation or notes
"""
print("Hello, World!")  # This prints a string to the console

Variables and Data Types

In Python, variables are used to store data and are dynamically typed, meaning you don’t need to declare the type explicitly. Python supports various data types, including integers, floats, strings, booleans, and complex numbers. Variable names should be descriptive and follow naming conventions (e.g., use lowercase with underscores for multi-word names).

Python’s type system is flexible, allowing variables to change types during execution. Use the type() function to check a variable’s type.

# Integer
age = 21
print(type(age))  # Output: 

# Float
pi = 3.14
print(type(pi))   # Output: 

# String
name = "Alice"
print(type(name)) # Output: 

# Boolean
is_student = True
print(type(is_student)) # Output: 

Operators

Operators are symbols that perform operations on variables and values. Python includes arithmetic, comparison, logical, assignment, bitwise, and membership operators. Understanding operator precedence is crucial for writing correct expressions.

Below are examples of commonly used operators. Note that Python follows standard mathematical precedence (e.g., multiplication before addition).

# Arithmetic Operators
a = 10
b = 5
print(a + b)  # Output: 15 (Addition)
print(a - b)  # Output: 5 (Subtraction)
print(a * b)  # Output: 50 (Multiplication)

# Comparison Operators
print(a == b)  # Output: False (Equality)
print(a > b)   # Output: True (Greater than)

# Logical Operators
print(a > 5 and b < 10)  # Output: True (Logical AND)
print(not(a > 5))        # Output: False (Logical NOT)

# Membership Operators
fruits = ["apple", "banana"]
print("apple" in fruits)  # Output: True

Conditional Statements

Conditional statements allow you to execute different code blocks based on conditions. Python uses if, elif, and else to handle decision-making. Conditions are evaluated as boolean expressions.

Nested conditionals can be used for complex logic, but avoid excessive nesting for readability. Use logical operators to combine conditions when possible.

age = 18

if age < 18:
    print("Minor")
elif age == 18:
    print("Just turned adult")
else:
    print("Adult")

# Nested conditional
if age >= 18:
    if age >= 21:
        print("Can drink")
    else:
        print("Adult but not 21")

Loops

Loops allow repeated execution of code. Python provides for loops (for iterating over sequences) and while loops (for condition-based repetition). Use break to exit a loop early and continue to skip to the next iteration.

Loop control statements enhance flexibility but should be used judiciously to maintain code clarity.

# For loop with range
for i in range(5):
    print(i)  # Output: 0, 1, 2, 3, 4

# While loop with break
count = 0
while count < 5:
    if count == 3:
        break
    print(count)
    count += 1

# For loop with continue
for i in range(5):
    if i == 2:
        continue
    print(i)

Lists and Tuples

Lists and tuples are sequence types for storing multiple items. Lists are mutable (can be modified), while tuples are immutable (cannot be changed after creation). Both support indexing, slicing, and iteration.

Lists are ideal for dynamic collections, while tuples are used for fixed data or when immutability is desired.

# List (mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[0])  # Output: apple
print(fruits)     # Output: ['apple', 'banana', 'cherry', 'orange']

# Tuple (immutable)
colors = ("red", "green", "blue")
print(colors[1])  # Output: green
# colors[1] = "yellow"  # This would raise an error

Strings

Strings are immutable sequences of characters used to store text. Python provides methods like upper(), lower(), split(), and join() for string manipulation. Strings support slicing and formatting.

F-strings (formatted string literals) are a modern way to embed expressions inside strings.

# String operations
greeting = "Hello, World!"
print(greeting.upper())  # Output: HELLO, WORLD!

# String slicing
print(g Committee on Publication Ethicseting[0:5])  # Output: Hello

# F-string
name = "Alice"
message = f"{greeting} {name}"
print(message)  # Output: Hello, World! Alice

# String methods
words = greeting.split()
print(words)  # Output: ['Hello,', 'World!']

Dictionaries

Dictionaries store data in key-value pairs, providing fast lookups. Keys must be immutable (e.g., strings, numbers, tuples), while values can be of any type. Dictionaries are mutable and support methods like get(), keys(), and values().

Use dictionaries for data that needs to be accessed by unique identifiers.

# Dictionary
student = {
    "name": "Alice",
    "age": 21,
    "is_student": True
}
print(student["name"])  # Output: Alice
print(student.get("age"))  # Output: 21

# Adding a new key-value pair
student["grade"] = "A"
print(student)

# Dictionary methods
print(student.keys())  # Output: dict_keys(['name', 'age', 'is_student', 'grade'])

Functions

Functions are reusable code blocks that perform specific tasks. They improve code organization, readability, and reusability. Python functions can have parameters, default arguments, and return values.

Functions can also accept variable numbers of arguments using *args and **kwargs.

# Basic function
def greet(name):
    return f"Hello, {name}!"
print(greet("Alice"))  # Output: Hello, Alice!

# Function with default parameter
def add(a, b=10):
    return a + b
print(add(5))  # Output: 15
print(add(5, 20))  # Output: 25

# Variable arguments
def sum_numbers(*args):
    return sum(args)
print(sum_numbers(1, 2, 3, 4))  # Output: 10

File Handling

Python provides built-in functions for reading and writing files. The with statement ensures files are properly closed after operations. Common modes include 'r' (read), 'w' (write), and 'a' (append).

File handling is useful for tasks like logging, data processing, and configuration management.

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

# Reading lines into a list
with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)