### 1.
Running Your First Python Script
To run a Python script, you can click the green play button in the corner of your
IDE or go to the "Run" tab and then select "Run". The output will appear in the
terminal window at the bottom. If the program finishes successfully, it will
display "process finished with exit code zero".
**Code Example:**
```python
# To print a message to the terminal window
print("I love pizza") #
print("It's really good") #
```
### 2. Variables and Data Types
A **variable** is a container for a value and behaves as the value it contains.
Variables are not limited to just numbers; they can store whole words, numbers, and
even booleans.
#### Strings
A **string** is a series of characters. You can create a string using either single
or double quotes in Python.
**Code Example:**
```python
name = "bro" #
print(name) # This will print 'bro'
# If you put the variable name within quotes, it will literally print the word
'name'
print("name") # This will literally print 'name'
# You can combine string variables with other strings (string concatenation)
first_name = "Bro" #
last_name = "Code" # A common naming convention for two-word variables is to
separate with an underscore
full_name = first_name + " " + last_name #
print("Hello " + full_name) # This will print 'Hello Bro Code'
# Check the data type of a variable using the type() function
print(type(full_name)) # This will print <class 'str'>
```
#### Integers (Ints)
The **int** data type stores a whole integer number. When assigning an integer
value, make sure it is not within quotes, as that would technically make it a
string. You cannot normally use strings for mathematical operations.
**Code Example:**
```python
age = 21 #
print(age) # This will print 21
# You can perform mathematical operations
age = age + 1 #
print(age) # This will print 22
# Shorthand way to increment
age += 1 #
print(age) # This will print 23
# Check the data type
print(type(age)) # This will print <class 'int'>
# Example of Type Error when performing math on a string
# age = "21" # If age is a string
# age += 1 # This would cause a TypeError: can only concatenate str to str, not int
```
#### Floats
The **float** data type is a numeric value that can store a number that includes a
decimal portion, unlike an int.
**Code Example:**
```python
height = 250.5 #
print(height) # This will print 250.5
# Check the data type
print(type(height)) # This will print <class 'float'>
# Displaying a float with a string requires type casting
print("Your height is " + str(height) + "cm") # Converts height to string for
concatenation
```
#### Booleans
The **boolean** data type can only store `True` or `False`. Booleans are very
useful with if statements. Ensure they are not within quotes, as that would make
them strings and they behave differently.
**Code Example:**
```python
human = True #
print(human) # This will print True
# Check the data type
print(type(human)) # This will print <class 'bool'>
# Displaying a boolean with a string requires type casting
print("Are you a human? " + str(human)) # Converts human to string for
concatenation
```
### 3. Multiple Assignment
Multiple assignment allows you to assign multiple variables at the same time using
one line of code.
**Code Example:**
```python
# Standard assignment
# name = "Bro"
# age = 21
# attractive = True
# Multiple assignment
name, age, attractive = "Bro", 21, True #
print(name) #
print(age) #
print(attractive) #
# Assigning multiple variables to the same value
spongebob = patrick = sandy = squidward = 30 #
print(spongebob) #
print(patrick) #
print(sandy) #
print(squidward) #
```
### 4. String Methods
Strings have several useful built-in methods.
**Code Example:**
```python
name = "Bro Code" #
# len() - returns the length of the string
print(len(name)) # Prints 8
# .find() - finds the first index of a character
print([Link]("o")) # Prints 2 (index of the first 'o')
# .capitalize() - capitalizes the first letter of the string
print([Link]()) # Prints "Bro code"
# .upper() - converts string to all uppercase
print([Link]()) # Prints "BRO CODE"
# .lower() - converts string to all lowercase
print([Link]()) # Prints "bro code"
# .isdigit() - returns True if string contains only digits
num_string = "123"
print(num_string.isdigit()) # Prints True
print([Link]()) # Prints False
# .isalpha() - returns True if string contains only alphabetical characters (no
spaces)
print([Link]()) # Prints False (due to space)
alpha_name = "BroCode"
print(alpha_name.isalpha()) # Prints True
# .count() - counts how many times a character appears
print([Link]("o")) # Prints 2
# .replace(old, new) - replaces occurrences of a character
print([Link]("o", "a")) # Prints "Bra Cade"
# String multiplication - displays a string multiple times
print(name * 3) # Prints "Bro CodeBro CodeBro Code"
```
### 5. Type Casting
Type casting is the ability to convert the data type of a value to another data
type.
**Code Example:**
```python
x = 1 # int
y = 2.0 # float
z = "3" # string
# Original values
print(x) # 1
print(y) # 2.0
print(z) # 3
# Convert float to int
y_int = int(y)
print(y_int) # 2
# Convert string to int
z_int = int(z)
print(z_int * 3) # 9 (as int multiplication)
# Convert int to float
x_float = float(x)
print(x_float) # 1.0
# Convert int/float to string for concatenation
print("X is " + str(x)) # X is 1
print("Y is " + str(y)) # Y is 2.0
```
### 6. User Input
The `input()` function is used to accept user input in Python. User input is always
of the string data type by default.
**Code Example:**
```python
# Accepting string input
name = input("What is your name? ") #
print("Hello " + name) #
# Accepting numeric input and casting to int
age = int(input("How old are you? ")) # Casts input string to integer
age += 1 # Perform mathematical operation
print("You are " + str(age) + " years old") # Casts integer back to string for
display
# Accepting numeric input and casting to float
height = float(input("How tall are you? ")) # Casts input string to float
print("You are " + str(height) + "cm tall") #
# Example of ValueError if casting non-whole number to int
# age = int(input("Enter your age (whole number): "))
# If user types 21.5, this will raise a ValueError
```
### 7. Useful Number Functions (Math Module)
The `math` module provides various functions related to numbers.
**Code Example:**
```python
import math #
pi = 3.14 #
# round() - Built-in function to round to the nearest whole integer
print(round(pi)) # Prints 3
# [Link]() - Rounds a number up to the nearest whole integer
print([Link](pi)) # Prints 4
# [Link]() - Rounds a number down to the nearest whole integer
print([Link](pi)) # Prints 3
# abs() - Returns the absolute value of a number (distance from zero)
negative_pi = -3.14
print(abs(negative_pi)) # Prints 3.14
# pow(base, exponent) - Raises a base number to a power
print(pow(pi, 2)) # Prints 9.8596
# [Link]() - Returns the square root of a number
print([Link](420)) # Prints 20.4939...
# max() - Finds the largest of a varying amount of values
x = 1
y = 2
z = 3
print(max(x, y, z)) # Prints 3
# min() - Finds the lowest of a varying amount of values
print(min(x, y, z)) # Prints 1
```
### 8. String Slicing
Slicing can be used to create a substring by extracting elements from another
string using the indexing operator (`[]`) or the `slice()` function. It uses a
start index (inclusive), a stopping index (exclusive), and an optional step.
**Code Example:**
```python
name = "Bro Code" #
# Slicing with start and stop index
first_name = name[0:3] # Starts at index 0, stops before index 3
print(first_name) # Prints "Bro"
# Shorthand: leaving start index blank assumes 0
first_name_shorthand = name[:3]
print(first_name_shorthand) # Prints "Bro"
# Slicing with specific start and stop index for 'Code'
last_name = name[4:8] # Index 4 for 'C', stops before index 8
print(last_name) # Prints "Code"
# Shorthand: leaving stop index blank goes to the end
last_name_shorthand = name[4:]
print(last_name_shorthand) # Prints "Code"
# Slicing with step: count every second character
funky_name = name[0:8:2] # Start 0, stop 8, step 2
print(funky_name) # Prints "Bocd"
# Shorthand for step: leaving start and stop empty assumes full string
funky_name_shorthand = name[::2]
print(funky_name_shorthand) # Prints "Bocd"
# Reversing a string with a negative step
reversed_name = name[::-1] # Start empty, stop empty, step -1
print(reversed_name) # Prints "edoC orB"
# Using slice() function to create a reusable slice object
website1 = "[Link] #
website2 = "[Link] #
# Define slice object: start at index 7 (after [Link] stop before -4
(before .com)
slicer = slice(7, -4) #
print(website1[slicer]) # Prints "google"
print(website2[slicer]) # Prints "wikipedia"
```
### 9. If/Elif/Else Statements
An **if statement** is a block of code that will execute only if its condition is
true. Indented code underneath an if statement is the block of code for that
statement. An **else statement** provides an alternative course of action if the
`if` condition is false. An **elif (else if) statement** allows you to check more
than one condition before reaching an `else` statement. The order of these
statements matters.
**Code Example:**
```python
age = int(input("How old are you? ")) #
# Basic if statement
if age >= 18: #
print("You are an adult") #
# If-Else statement
if age >= 18:
print("You are an adult")
else: #
print("You are a child") #
# If-Elif-Else statement
if age < 0: #
print("You haven't been born yet") #
elif age == 100: # Checks if age is exactly 100 (using double equals for
comparison)
print("You are a century old") #
elif age >= 18: #
print("You are an adult") #
else: #
print("You are a child") #
```
### 10. Logical Operators
Logical operators (`and`, `or`, `not`) are used to check if two or more conditional
statements are true.
**Code Example:**
```python
temp = int(input("What is the temperature outside? ")) #
# and logical operator: both conditions must be true
if temp >= 0 and temp <= 30: #
print("The temperature is good today!") #
print("Go outside!") #
elif temp < 0 or temp > 30: # or logical operator: as long as one condition is true
print("The temperature is bad today!") #
print("Stay inside!") #
# not logical operator: flips the boolean value of a condition
# Example using 'not' to reverse the conditions
# (Note: The source swaps the print statements to match the original logic after
applying 'not')
if not (temp >= 0 and temp <= 30): # If it's NOT between 0 and 30 (i.e., less than
0 OR greater than 30)
print("The temperature is bad today!")
print("Stay inside!")
else: # If it IS between 0 and 30
print("The temperature is good today!")
print("Go outside!")
```
### 11. While Loops
A **while loop** is a statement that will execute its block of code as long as its
condition remains true. It's important to have a way to eventually escape the loop
to avoid an **infinite loop**.
**Code Example:**
```python
# Example of an infinite loop (don't run this without a way to stop it!)
# while 1 == 1:
# print("Help! I'm stuck in a loop!")
# Practical example: prompting for user input until a non-empty name is entered
name = "" # Initialize name as empty string
while len(name) == 0: # Loop as long as the length of name is 0
name = input("Enter your name: ") #
print("Hello " + name) #
# Alternative way using 'not' for checking if name is empty (none or empty string)
name = None #
while not name: # Loop as long as name is considered 'falsy' (None, empty string,
0, False)
name = input("Enter your name: ")
print("Hello " + name)
```
### 12. For Loops
A **for loop** is a statement that will execute its block of code a limited amount
of times. It's useful for iterating through a range of numbers or items in a
collection.
**Code Example:**
```python
# Count from 0 to 9 using range()
for i in range(10): #
print(i) # Prints 0 to 9
# Count from 1 to 10 by adjusting output
for i in range(10):
print(i + 1) # Prints 1 to 10
# Count from 50 to 100 (inclusive of 50, exclusive of 101)
for i in range(50, 101): #
print(i) # Prints 50 to 100
# Count with a step: from 50 to 100 by 2
for i in range(50, 101, 2): #
print(i) # Prints 50, 52, 54...100
# Iterate through a string
for i in "Bro Code": #
print(i) # Prints each letter on a new line
# Countdown timer example
import time #
for seconds in range(10, -1, -1): # Start 10, end 0 (exclusive -1), step -1
print(seconds) #
[Link](1) # Pause for 1 second
print("Happy New Year!") #
```
### 13. Nested Loops
A **nested loop** is a general concept of having one loop inside of another loop.
The inner loop will finish all of its iterations before one iteration of the outer
loop is finished.
**Code Example:**
```python
# Drawing a rectangle with nested loops
rows = int(input("How many rows? ")) #
columns = int(input("How many columns? ")) #
symbol = input("Enter a symbol to use: ") #
for i in range(rows): # Outer loop for rows
for j in range(columns): # Inner loop for columns
print(symbol, end="") # Print symbol without new line
print() # Print a new line after each row is complete
```
### 14. Loop Control Statements
Loop control statements are used to change a loop's execution from its normal
sequence.
#### Break
**Break** is used to terminate the loop entirely when it is encountered.
**Code Example:**
```python
# Break example: continually ask for name until non-empty
while True: # Infinite loop
name = input("Enter your name: ") #
if name != "": # If name is not empty
break # Exit the loop
print("Hello " + name)
```
#### Continue
**Continue** skips to the next iteration of the loop.
**Code Example:**
```python
# Continue example: display phone number without dashes
phone_number = "123-456-7890" #
for i in phone_number: # Iterate through each character
if i == "-": # If character is a dash
continue # Skip to next iteration
print(i, end="") # Print character without new line
print() # Print a final new line
```
#### Pass
**Pass** does nothing; it acts as a placeholder.
**Code Example:**
```python
# Pass example: print numbers 1-20, skipping 13
for i in range(1, 21): #
if i == 13: # If number is 13
pass # Do nothing, just pass
else:
print(i) # Print the number
```
### 15. Lists
A **list** is used to store multiple items within a single variable, enclosed in
square brackets `[]`. Each item in a list is referred to as an element and has a
numbered index starting from zero. Lists are mutable (changeable).
**Code Example:**
```python
food = ["pizza", "hamburger", "hotdog", "spaghetti"] #
# Accessing elements by index
print(food) # Prints "pizza" (first element at index 0)
print(food) # Prints "hamburger"
# Updating elements
food = "sushi" # Changes the first element from "pizza" to "sushi"
print(food) # Prints "sushi"
# Displaying all elements using a for loop
for x in food: #
print(x) # Prints each food item on a new line
# List methods
[Link]("ice cream") # Adds "ice cream" to the end
[Link]("hotdog") # Removes "hotdog"
[Link]() # Removes the last element (e.g., "spaghetti" if ice cream was popped
before)
[Link](0, "cake") # Inserts "cake" at index 0
[Link]() # Sorts the list alphabetically
[Link]() # Removes all elements from the list
print(food) # Prints the current state of the list after operations
```
### 16. 2D Lists (Multi-dimensional Lists)
A **2D list** (or multi-dimensional list) is a list of separate lists.
**Code Example:**
```python
# Create separate lists
drinks = ["coffee", "soda", "tea"] #
dinner = ["pizza", "hamburger", "hotdog"] #
dessert = ["cake", "ice cream"] #
# Combine lists into a 2D list
food = [drinks, dinner, dessert] #
print(food) # Prints the 2D list
# Accessing a specific list within the 2D list
print(food) # Prints the 'drinks' list: ['coffee', 'soda', 'tea']
# Accessing a specific element within a nested list
print(food) # Prints 'coffee' (first element of the first list)
print(food) # Prints 'hotdog' (third element of the second list)
```
### 17. Tuples
A **tuple** is a collection which is ordered and unchangeable, defined using
parentheses `()`. They are useful for grouping together related data.
**Code Example:**
```python
student = ("Bro", 21, "male") # Create a tuple
print(student) # Prints the tuple
# Tuple methods
print([Link]("Bro")) # Counts occurrences of "Bro" (Prints 1)
print([Link]("male")) # Finds index of "male" (Prints 2)
# Displaying all contents using a for loop
for x in student: #
print(x) # Prints each element on a new line
# Checking if a value exists within a tuple
if "Bro" in student: #
print("Bro is here!") # Prints "Bro is here!"
```
### 18. Sets
A **set** is a collection which is unordered, unindexed, and does not allow any
duplicate values, defined using curly braces `{}`. Sets are generally faster than
lists for checking if an item is present.
**Code Example:**
```python
utensils = {"fork", "spoon", "knife", "knife"} # Duplicate "knife" will be ignored
# Displaying all elements (order may vary as sets are unordered)
for x in utensils: #
print(x) # Prints fork, spoon, knife (order might be different)
# Set methods
[Link]("napkin") # Adds "napkin" to the set
[Link]("fork") # Removes "fork" from the set
[Link]() # Removes all elements
# Combining sets
utensils = {"fork", "spoon", "knife"}
dishes = {"bowl", "plate", "cup", "knife"} #
[Link](dishes) # Adds all elements from 'dishes' to 'utensils'
print(utensils) # Prints all unique items from both sets
# Joining two sets to create a new set (union)
dinner_table = [Link](dishes) # Creates a new set with all unique elements
print(dinner_table)
# Comparing sets
# .difference() - Returns items in the first set that are not in the second
print([Link](dishes)) # Prints {'spoon', 'fork'} (what utensils has
that dishes doesn't)
print([Link](utensils)) # Prints {'plate', 'cup', 'bowl'} (what dishes
has that utensils doesn't)
# .intersection() - Returns items common to both sets
print([Link](dishes)) # Prints {'knife'}
```
### 19. Dictionaries
A **dictionary** is a changeable, unordered collection of unique key-value pairs,
defined using curly braces `{}` with keys and values separated by colons `:`. They
are fast because they use hashing to quickly access values.
**Code Example:**
```python
capitals = {"USA": "Washington DC",
"India": "New Delhi",
"China": "Beijing",
"Russia": "Moscow"} #
# Accessing values by key
print(capitals["USA"]) # Prints "Washington DC"
# Safer way to access values using .get()
print([Link]("Germany")) # Prints None (if key doesn't exist, avoids
KeyError)
print([Link]("India")) # Prints "New Delhi"
# Dictionary methods
print([Link]()) # Prints all keys: dict_keys(['USA', 'India', 'China',
'Russia'])
print([Link]()) # Prints all values: dict_values(['Washington DC', 'New
Delhi', 'Beijing', 'Moscow'])
print([Link]()) # Prints all key-value pairs: dict_items([...])
# Iterating through key-value pairs using a for loop
for key, value in [Link](): #
print(key, value) # Prints each key and value
# Updating a dictionary
[Link]({"Germany": "Berlin"}) # Adds new key-value pair
[Link]({"USA": "Las Vegas"}) # Updates existing key's value
print(capitals)
# Removing elements
[Link]("China") # Removes the key-value pair for "China"
print(capitals)
[Link]() # Removes all elements
print(capitals)
```
### 20. Index Operator (`[]`)
The **index operator** (`[]`) gives access to a sequence's elements, including
strings, lists, and tuples.
**Code Example:**
```python
name = "bro Code!" #
# Accessing a single element
# Check if the first letter is lowercase and capitalize it
if [Link](): # Accesses the character at index 0
name = [Link]() #
print(name) # Prints "Bro Code!"
# Creating substrings (slicing)
first_name = name[0:3] # From index 0 (inclusive) to 3 (exclusive)
print(first_name.upper()) # Prints "BRO"
# Shorthand for slicing from the beginning
first_name_shorthand = name[:3]
print(first_name_shorthand.upper()) # Prints "BRO"
# Slicing to the end
last_name = name[4:].lower() # From index 4 to the end
print(last_name) # Prints "code!"
# Negative indexing: accessing elements from the end of the sequence
last_character = name[-1] # -1 refers to the last element
print(last_character) # Prints "!"
second_to_last_character = name[-2] # -2 refers to the second to last element
print(second_to_last_character) # Prints "e"
```
### 21. Functions
A **function** is a block of code which is executed only when it is called (or
invoked). Functions are useful for performing specific tasks and avoiding code
repetition.
**Code Example:**
```python
# Defining a function
def hello(): # 'def' keyword, unique name, parentheses, colon
print("Hello") #
print("Have a nice day") #
# Calling a function
hello() # Executes the function's code block
hello() # Can be called multiple times
# Functions with arguments and parameters
def greet(first_name, last_name, age): # Parameters to receive arguments
print("Hello " + first_name + " " + last_name) #
print("You are " + str(age) + " years old") # Type casting for age
print("Have a nice day") #
# Calling the function with arguments
greet("Bro", "Code", 21) # Passing values as arguments
my_first_name = "Dude"
my_last_name = "Bro"
my_age = 30
greet(my_first_name, my_last_name, my_age) # Passing variables as arguments
```
### 22. Return Statement
The **return statement** is used within functions to send Python values or objects
back to the caller. These values or objects are known as the function's **return
value**.
**Code Example:**
```python
# Function that multiplies two numbers and returns the result
def multiply(number1, number2): #
result = number1 * number2 #
return result # Returns the 'result' variable
# Calling the function and printing the returned value
print(multiply(6, 8)) # Prints 48
# Storing the returned value in a variable
x = multiply(6, 8) # 'x' will store 48
print(x) # Prints 48
# Concise way to write the return statement
def multiply_concise(number1, number2):
return number1 * number2 # Directly returns the expression result
print(multiply_concise(6, 8)) # Prints 48
```
### 23. Keyword Arguments
**Keyword arguments** are arguments that are preceded by an identifier when passed
to a function. With keyword arguments, the order of the arguments doesn't matter,
unlike positional arguments.
**Code Example:**
```python
def hello(first_name, middle_name, last_name): #
print("Hello " + first_name + " " + middle_name + " " + last_name) #
# Positional arguments (order matters)
hello("Bro", "Dude", "Code") # Prints "Hello Bro Dude Code"
# Keyword arguments (order does not matter)
hello(last_name="Code", middle_name="Dude", first_name="Bro") # Prints "Hello Bro
Dude Code"
```
### 24. Nested Function Calls
**Nested function calls** are function calls inside of other function calls. This
is possible because certain functions return a value which can immediately be used
as an argument for the next function.
**Code Example:**
```python
# Example: Convert input to float, find absolute value, round, then print
# Original multi-line code
# num = input("Enter a whole positive number: ")
# num = float(num)
# num = abs(num)
# num = round(num)
# print(num)
# Nested function calls (achieves the same in one line)
print(round(abs(float(input("Enter a whole positive number: "))))) #
# Execution starts from innermost function (input) and works outwards
```
### 25. Variable Scope
The **scope** of a variable is the region that a variable is recognized. A variable
is only available from inside the region that it is created.
**Code Example:**
```python
# Global variable
name = "Bro" # Declared outside any function, has global scope
def display_name():
# Local variable
name = "Code" # Declared inside function, has local scope
print(name) # Prints "Code" (local version is prioritized)
display_name() # Call the function
print(name) # Prints "Bro" (global version)
# If no local variable, global variable is used within the function
name_global = "Bro"
def display_name_uses_global():
# No local 'name_global' here
print(name_global) # Will use the global 'name_global'
display_name_uses_global() # Prints "Bro"
```
### 26. `*args` Parameter
The `*args` parameter will pack all arguments into a tuple. It's useful so that a
function can accept a varying amount of arguments. The `args` portion can be named
anything, but the **asterisk** is important.
**Code Example:**
```python
# Function to add numbers with a fixed number of parameters
# def add(num1, num2):
# return num1 + num2
# print(add(1, 2)) # Works
# print(add(1, 2, 3)) # TypeError
# Function to add numbers using *args
def add(*stuff): # 'stuff' will be a tuple containing all passed arguments
sum = 0 #
# You can convert the tuple to a list if you need to modify it
# stuff = list(stuff)
# stuff = 0 # Example modification if 'stuff' was a list
for i in stuff: # Iterate through the tuple
sum += i #
return sum #
print(add(1, 2, 3, 4, 5, 6)) # Prints 21
print(add(10, 20)) # Prints 30
```
### 27. `**kwargs` Parameter
The `**kwargs` parameter will pack all keyword arguments into a dictionary. It's
useful so that a function can accept a varying amount of keyword arguments. The
`kwargs` portion can be named anything, but the **double asterisks** are important.
**Code Example:**
```python
# Function to greet with varying names using **kwargs
def hello(**names): # 'names' will be a dictionary of keyword arguments
print("Hello", end=" ") # Print "Hello " and stay on the same line
for key, value in [Link](): # Iterate through the dictionary items
print(value, end=" ") # Print each name followed by a space
hello(title="Mr.", first="Bro", middle="Dude", last="Code") # Prints "Hello Mr. Bro
Dude Code "
```
### 28. Format Method
The **`.format()` method** is an optional method available to strings that gives
users more control when displaying output. It uses curly braces `{}` as format
fields (placeholders).
**Code Example:**
```python
animal = "cow" #
item = "moon" #
# Using format method with values
print("The {} jumped over the {}".format("cow", "moon")) # Prints "The cow jumped
over the moon"
# Using format method with variables
print("The {} jumped over the {}".format(animal, item)) # Prints "The cow jumped
over the moon"
# Positional arguments: specify index in format fields
print("The {0} jumped over the {1}".format(animal, item)) # Prints "The cow jumped
over the moon"
print("The {1} jumped over the {0}".format(animal, item)) # Prints "The moon jumped
over the cow"
# Keyword arguments: use keyword names in format fields
print("The {animal} jumped over the {item}".format(animal="cow", item="moon")) #
Prints "The cow jumped over the moon"
print("The {item} jumped over the {animal}".format(animal="cow", item="moon")) #
Prints "The moon jumped over the cow"
# Reusing values
print("The {0} jumped over the {0}".format(animal, item)) # Prints "The cow jumped
over the cow"
# Storing format string in a variable
text = "The {} jumped over the {}" #
print([Link](animal, item)) # Prints "The cow jumped over the moon"
# Padding: adding space
name = "Bro" #
print("Hello my name is {:10}".format(name)) # Adds 10 spaces of padding to the
right
print("Hello my name is {:<10}".format(name)) # Left-align (default)
print("Hello my name is {:>10}".format(name)) # Right-align
print("Hello my name is {:^10}".format(name)) # Center-align
# Formatting numbers
number = 3.14159 #
print("The number pi is {:.2f}".format(number)) # Displays 2 digits after decimal,
rounds
large_number = 1000 #
print("The number is {:,}".format(large_number)) # Adds comma at thousands place
print("The number is {:b}".format(large_number)) # Binary representation
print("The number is {:o}".format(large_number)) # Octal representation
print("The number is {:x}".format(large_number)) # Hexadecimal (lowercase)
print("The number is {:X}".format(large_number)) # Hexadecimal (uppercase)
print("The number is {:e}".format(large_number)) # Scientific notation (lowercase
e)
print("The number is {:E}".format(large_number)) # Scientific notation (uppercase
E)
```
### 29. Random Module
The `random` module provides functions for generating pseudorandom numbers.
**Code Example:**
```python
import random #
# [Link](a, b) - generates a random integer between a and b (inclusive)
x = [Link](1, 6) # Simulates rolling a dice
print(x)
# [Link]() - generates a random floating point number between 0 and 1
y = [Link]() #
print(y)
# [Link](sequence) - picks a random element from a list or other sequence
my_list = ["rock", "paper", "scissors"] #
z = [Link](my_list) #
print(z)
# [Link](list) - shuffles a list in-place
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, "J", "Q", "K", "A"] #
print("Original cards:", cards)
[Link](cards) #
print("Shuffled cards:", cards)
```
### 30. Exception Handling
An **exception** is an event detected during execution that interrupts the normal
flow of a program. `try` and `except` blocks are used to handle these exceptions.
**Code Example:**
```python
# Basic try-except block
try: # Code that might cause an exception
numerator = int(input("Enter a numerator: ")) #
denominator = int(input("Enter a denominator: ")) #
result = numerator / denominator #
print(result) #
except Exception: # Catches any exception
print("Something went wrong :(") #
# Handling specific exceptions
try:
numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter a denominator: "))
result = numerator / denominator
print(result)
except ZeroDivisionError: # Catches division by zero specifically
print("You can't divide by zero, idiot!") #
except ValueError: # Catches invalid type conversion (e.g., non-numeric input)
print("Enter only numbers please!") #
except Exception as e: # Catch-all for any other unexpected exceptions, and display
the error
print(e) # Prints the exception message
print("Something went wrong :(")
# Try-Except-Else-Finally blocks
try:
numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter a denominator: "))
result = numerator / denominator
except ZeroDivisionError as e:
print(e)
print("You can't divide by zero, idiot!")
except ValueError as e:
print(e)
print("Enter only numbers please!")
else: # Executes only if no exception occurred in the try block
print(result) #
finally: # Always executes, regardless of whether an exception occurred
print("This will always execute") #
```
### 31. File Detection
The `os` module provides functions for interacting with the operating system,
including file detection.
**Code Example:**
```python
import os #
path = "[Link]" # Path to a file (can be a full path or just filename if in same
directory)
# path = "C:\\Users\\BroCode\\Desktop\\folder" # Example for a folder
# [Link](path) - Checks if a path exists
if [Link](path): #
print("That location exists") #
if [Link](path): # [Link](path) - Checks if path is a file
print("That is a file") #
elif [Link](path): # [Link](path) - Checks if path is a directory
print("That is a directory") #
else:
print("That location doesn't exist") #
```
### 32. Reading Files
You can read the contents of a file using Python. The `with open(...)` statement
ensures the file is automatically closed.
**Code Example:**
```python
try:
# 'with open(filename, mode) as file_object:'
# 'r' mode is for reading (default)
with open('[Link]', 'r') as file: # Assumes '[Link]' is in the same
directory
print([Link]()) # Reads and prints the entire content of the file
print([Link]) # True (file is automatically closed by 'with' statement)
except FileNotFoundError: # Handles the specific exception if the file doesn't
exist
print("That file was not found :(") #
```
### 33. Writing Files
You can write to a file using Python. Using `'w'` mode will overwrite existing
content, while `'a'` mode will append to it.
**Code Example:**
```python
text_to_write = "Yo!\nThis is some text.\nHave a good one!" # \n creates a new line
# 'w' mode for writing (overwrites existing file or creates new)
with open('[Link]', 'w') as file: #
[Link](text_to_write) # Writes the text to the file
print("File '[Link]' written successfully.")
text_to_append = "\nHave a nice day! See ya!" # New content to append
# 'a' mode for appending (adds to the end of the file)
with open('[Link]', 'a') as file: #
[Link](text_to_append) # Appends text to the file
print("File '[Link]' appended successfully.")
```
### 34. Copying Files
The `shutil` module provides high-level file operations, including copying.
**Code Example:**
```python
import shutil #
# Source file path (assume [Link] exists in the project folder)
source_file = "[Link]" #
# Destination file path ([Link] will be created in the project folder)
destination_file = "[Link]" #
# To copy to a different location, provide a full path: "C:\\Users\\BroCode\\
Desktop\\[Link]"
# [Link](source, destination) - Copies contents only
[Link](source_file, destination_file) #
print(f"'{source_file}' copied to '{destination_file}' using copyfile.")
# [Link](source, destination) - Copies contents and permissions
# [Link](source_file, "copy_with_permissions.txt")
# print(f"'{source_file}' copied to 'copy_with_permissions.txt' using copy.")
# shutil.copy2(source, destination) - Copies contents, permissions, and metadata
(creation/modification times)
# shutil.copy2(source_file, "copy_with_metadata.txt")
# print(f"'{source_file}' copied to 'copy_with_metadata.txt' using copy2.")
```
### 35. Moving Files
The `os` module can be used to move files and directories.
**Code Example:**
```python
import os #
# Assume '[Link]' exists in the current project folder
source_path = "[Link]" #
# Example: moving to Desktop (adjust path for your OS)
# On Windows, replace backslashes with double backslashes or use raw strings
(r"C:\...")
destination_path = "C:\\Users\\BroCode\\Desktop\\[Link]" #
# You can also rename the file during the move: destination_path = "C:\\Users\\
BroCode\\Desktop\\new_name.txt"
try:
if [Link](destination_path): # Check if a file already exists at the
destination
print("There is already a file at the destination. Skipping move.") #
else:
# [Link](source, destination) - Moves or renames a file/directory
[Link](source_path, destination_path) #
print(f"'{source_path}' was moved to '{destination_path}'.") #
except FileNotFoundError: # Handles if the source file doesn't exist
print(f"'{source_path}' was not found.") #
except PermissionError:
print(f"Permission denied to move '{source_path}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example of moving a directory
# Assume 'folder' exists in the current project folder
# source_dir = "folder" #
# destination_dir = "C:\\Users\\BroCode\\Desktop\\folder" #
# try:
# [Link](source_dir, destination_dir) #
# print(f"'{source_dir}' was moved to '{destination_dir}'.")
# except FileNotFoundError:
# print(f"'{source_dir}' was not found.")
# except PermissionError:
# print(f"Permission denied to move '{source_dir}'.")
# except Exception as e:
# print(f"An unexpected error occurred: {e}")
```
### 36. Deleting Files
The `os` and `shutil` modules provide functions for deleting files and directories.
**Code Example:**
```python
import os #
import shutil #
# Assume '[Link]' exists in the project folder for this example
file_to_delete = "[Link]" #
# Deleting a file using [Link]()
try:
[Link](file_to_delete) #
print(f"'{file_to_delete}' was deleted.") #
except FileNotFoundError: # Handle if file doesn't exist
print(f"That file '{file_to_delete}' was not found.") #
except Exception as e:
print(f"An error occurred: {e}")
# Deleting an empty directory using [Link]()
empty_folder = "empty_folder" #
# [Link](empty_folder) # Create an empty folder for testing
try:
[Link](empty_folder) #
print(f"Empty folder '{empty_folder}' was deleted.") #
except FileNotFoundError:
print(f"That folder '{empty_folder}' was not found.")
except PermissionError: # Handles permission issues
print(f"You do not have permission to delete '{empty_folder}'.") #
except OSError as e: # Catches if directory is not empty
print(f"You cannot delete '{empty_folder}' using rmdir. {e}") #
# Deleting a non-empty directory using [Link]()
# BE CAREFUL: This deletes the directory and all its contents!
folder_with_files = "folder_with_files" #
# [Link]([Link](folder_with_files, "subfolder"), exist_ok=True)
# with open([Link](folder_with_files, "[Link]"), "w") as f:
# [Link]("content")
try:
[Link](folder_with_files) #
print(f"Folder '{folder_with_files}' and its contents were deleted.") #
except FileNotFoundError:
print(f"That folder '{folder_with_files}' was not found.")
except PermissionError:
print(f"You do not have permission to delete '{folder_with_files}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
```
### 37. Modules
A **module** is a file containing Python code (functions, classes, etc.). Modular
programming is the concept of separating a program into useful different parts.
**File: `[Link]`**
```python
# This is a separate module named '[Link]'
def hello(): #
print("Hello! Have a nice day.") #
def bye(): #
print("Bye! Have a wonderful time.") #
```
**File: `[Link]`** (or your main working file)
```python
# Import the entire module
import messages #
[Link]() # Call function from module: "Hello! Have a nice day."
[Link]() # Call function from module: "Bye! Have a wonderful time."
# Import with an alias (nickname)
import messages as msg #
[Link]() # Use alias: "Hello! Have a nice day."
[Link]() # Use alias: "Bye! Have a wonderful time."
# Import specific functions directly
from messages import hello, bye #
hello() # Call directly: "Hello! Have a nice day."
bye() # Call directly: "Bye! Have a wonderful time."
# Import all functions/classes (use with caution in large programs)
# from messages import * #
# hello()
# bye()
# View available modules (run in terminal)
# help("modules") #
```
### 38. Basic Rock Paper Scissors Game
This game uses the `random` module, loops, conditional statements, and string
methods.
**Code Example:**
```python
import random #
choices = ["rock", "paper", "scissors"] # List of possible choices
computer = [Link](choices) # Computer picks a random choice
player = None # Initialize player choice
# Loop until player makes a valid choice
while player not in choices: #
player = input("rock, paper, or scissors? ").lower() # Get input and convert to
lowercase
print("Computer:", computer) #
print("Player:", player) #
# Determine win/loss/tie
if player == computer: #
print("It's a tie!") #
elif player == "rock": #
if computer == "paper": #
print("You lose!") #
elif computer == "scissors": #
print("You win!") #
elif player == "scissors": #
if computer == "rock": #
print("You lose!") #
elif computer == "paper": #
print("You win!") #
elif player == "paper": #
if computer == "scissors": #
print("You lose!") #
elif computer == "rock": #
print("You win!") #
# Play again feature
# To integrate this, wrap the above game logic in a while True loop and add the
following at the end:
# play_again = input("Play again? (yes/no): ").lower() #
# if play_again != "yes": #
# break # Exit the game loop
# print("Bye!") #
```
### 39. Basic Quiz Game
This program demonstrates functions, dictionaries, 2D lists, loops, and user input
to create a simple quiz.
**Code Example:**
```python
# Define quiz questions and options
questions = { # Dictionary for questions and correct answers
"Who created Python?: ": "A",
"What year was Python created?: ": "B",
"Python is attributed to which comedy group?: ": "C",
"Is the Earth round?: ": "A"
}
options = [ # 2D list for answer options
["A. Guido van Rossum", "B. Elon Musk", "C. Bill Gates", "D. Mark Zuckerburg"],
["A. 1989", "B. 1991", "C. 2000", "D. 2008"],
["A. Lonely Island", "B. Smosh", "C. Monty Python", "D. SNL"],
["A. True", "B. False", "C. Sometimes", "D. What's Earth?"]
]
# Function definitions (skeletal structure)
def new_game():
guesses = [] # To store user's guesses
correct_guesses = 0 # To track correct answers
question_num = 1 # To track current question number
for key in questions: # Iterate through questions
print("--------------------") #
print(key) # Print the question
for i in options[question_num - 1]: # Print options for the current
question
print(i)
guess = input("Enter (A, B, C, or D): ").upper() # Get user's guess and
convert to uppercase
[Link](guess) # Add guess to list
correct_guesses += check_answer([Link](key), guess) # Check answer
and update score
question_num += 1 # Move to next question
display_score(correct_guesses, guesses) # Display final score
def check_answer(answer, guess):
if answer == guess: #
print("CORRECT!") #
return 1 # Return 1 for correct answer
else:
print("WRONG!") #
return 0 # Return 0 for incorrect answer
def display_score(correct_guesses, guesses):
print("--------------------") #
print("RESULTS") #
print("--------------------") #
print("Answers: ", end="") #
for question_key in questions:
print([Link](question_key), end=" ") # Print correct answers
print() # New line
print("Guesses: ", end="") #
for guess in guesses:
print(guess, end=" ") # Print user's guesses
print() # New line
score = int((correct_guesses / len(questions)) * 100) # Calculate percentage
score
print("Your score is: " + str(score) + "%") # Display score
def play_again():
response = input("Do you want to play again? (yes/no): ").upper() #
if response == "YES": #
return True #
else:
return False #
# Main game loop
while play_again(): # Loop as long as user wants to play again
new_game() # Start a new quiz game
print("Bye!") # Exit message
```
### 40. Object-Oriented Programming (OOP) - Classes and Objects
**Object-Oriented Programming (OOP)** allows you to create representations of real-
life objects using **classes** and **objects**. A **class** acts as a blueprint,
describing what **attributes** (what an object is or has) and **methods** (what an
object can do) a distinct type of object will have. An **object** is an instance of
a class. The **`__init__` method** is a special method (constructor) that creates
objects and initializes their attributes. `self` refers to the object itself.
**File: `[Link]`**
```python
# This is a separate module named '[Link]'
class Car: # Class definition
# __init__ method (constructor)
def __init__(self, make, model, year, color): # 'self' is required, then
parameters
[Link] = make # Assign arguments to attributes
[Link] = model #
[Link] = year #
[Link] = color #
# Methods (what the object can do)
def drive(self): # 'self' is required
print([Link] + " is driving") # Access object's attribute using self
def stop(self): #
print([Link] + " is stopped") #
```
**File: `[Link]`** (or your main working file)
```python
from car import Car # Import the Car class from [Link]
# Create Car objects (instantiate the class)
car_one = Car("Chevy", "Corvette", 2021, "blue") # Pass arguments to the
constructor
car_two = Car("Ford", "Mustang", 2022, "red") #
# Access object attributes
print(car_one.make) # Prints "Chevy"
print(car_one.model) # Prints "Corvette"
print(car_one.year) # Prints 2021
print(car_one.color) # Prints "blue"
# Call object methods
car_one.drive() # Prints "Corvette is driving"
car_one.stop() # Prints "Corvette is stopped"
car_two.drive() # Prints "Mustang is driving"
car_two.stop() # Prints "Mustang is stopped"
```
### 41. Class Variables vs. Instance Variables
**Instance variables** are declared inside the constructor (`__init__`) and each
object can have its own unique values assigned to them. **Class variables** are
declared inside the class but outside the constructor, and they set a default value
for all instances (objects) of that class.
**Code Example:**
```python
# Assuming the Car class from [Link] is modified as follows:
class Car:
# Class variable: shared by all instances
wheels = 4 # Default value for all cars
def __init__(self, make, model, year, color):
# Instance variables: unique to each object
[Link] = make
[Link] = model
[Link] = year
[Link] = color
# Creating Car objects
car_1 = Car("Chevy", "Corvette", 2021, "blue") #
car_2 = Car("Ford", "Mustang", 2022, "red") #
# Accessing class variable via object
print(car_1.wheels) # Prints 4
print(car_2.wheels) # Prints 4
# Changing instance's copy of class variable
car_1.wheels = 2 # Changes only car_1's 'wheels' to 2
print(car_1.wheels) # Prints 2
print(car_2.wheels) # Prints 4 (still using default)
# Accessing class variable via class name
print([Link]) # Prints 4
# Changing class variable via class name affects all instances
[Link] = 2 # Changes the default for all future and existing objects (if not
overridden by instance)
print(car_1.wheels) # Prints 2 (if not previously set to 2 by instance, it would
pick up the class change)
print(car_2.wheels) # Prints 2
```
### 42. Inheritance
**Inheritance** allows a **child class** to inherit attributes and methods from a
**parent class**. This forms a parent-child relationship where the child receives
everything the parent has.
**Code Example:**
```python
# Parent class
class Animal: #
alive = True # Class variable
def eat(self): # Method
print("This animal is eating") #
def sleep(self): # Method
print("This animal is sleeping") #
# Child classes inheriting from Animal
class Rabbit(Animal): # Rabbit inherits from Animal
def run(self): # Unique method for Rabbit
print("This rabbit is running") #
class Fish(Animal): # Fish inherits from Animal
def swim(self): # Unique method for Fish
print("This fish is swimming") #
class Hawk(Animal): # Hawk inherits from Animal
def fly(self): # Unique method for Hawk
print("This hawk is flying") #
# Creating objects from child classes
rabbit = Rabbit() #
fish = Fish() #
hawk = Hawk() #
# Accessing inherited attributes
print([Link]) # Prints True
# Calling inherited methods
[Link]() # Prints "This animal is eating"
[Link]() # Prints "This animal is sleeping"
# Calling unique methods of child classes
[Link]() # Prints "This rabbit is running"
[Link]() # Prints "This fish is swimming"
[Link]() # Prints "This hawk is flying"
```
### 43. Multi-Level Inheritance
**Multi-level inheritance** is a concept where a derived class (child class)
inherits from another derived class. It creates a hierarchy like a family tree.
**Code Example:**
```python
# Grandparent class
class Organism: #
alive = True #
# Parent class (inherits from Organism)
class Animal(Organism): #
def eat(self): #
print("This animal is eating") #
# Child class (inherits from Animal)
class Dog(Animal): #
def bark(self): #
print("This dog is barking") #
# Creating an object from the lowest level child class
dog = Dog() #
# Accessing inherited attributes and methods from all levels
print([Link]) # Inherited from Organism: Prints True
[Link]() # Inherited from Animal: Prints "This animal is eating"
[Link]() # Defined in Dog class: Prints "This dog is barking"
```
### 44. Multiple Inheritance
**Multiple inheritance** is the concept where a child class is derived from more
than one parent class.
**Code Example:**
```python
# Parent class 1
class Prey: #
def flee(self): #
print("This animal flees") #
# Parent class 2
class Predator: #
def hunt(self): #
print("This animal is hunting") #
# Child class inheriting from one parent
class Rabbit(Prey): # Inherits only from Prey
pass
# Child class inheriting from another parent
class Hawk(Predator): # Inherits only from Predator
pass
# Child class inheriting from multiple parents
class Fish(Prey, Predator): # Inherits from both Prey and Predator
pass
# Creating objects
rabbit = Rabbit() #
hawk = Hawk() #
fish = Fish() #
# Testing inherited methods
[Link]() # Prints "This animal flees"
[Link]() # Prints "This animal is hunting"
[Link]() # Prints "This animal flees"
[Link]() # Prints "This animal is hunting"
```
### 45. Method Overriding
**Method overriding** is the ability of a subclass (child class) to provide a
specific implementation of a method that is already provided by one of its parents.
This is done by defining a method with the same **method signature** (name +
parameters) in the child class. An object will use a method that is more closely
associated with itself first.
**Code Example:**
```python
# Parent class
class Animal: #
def eat(self): #
print("This animal is eating") #
# Child class
class Rabbit(Animal): # Rabbit inherits from Animal
# Method overriding: providing a specific implementation for 'eat'
def eat(self): # Same method signature as parent's eat method
print("This rabbit is eating a carrot") #
# Creating an object
rabbit = Rabbit() #
# Calling the overridden method
[Link]() # Prints "This rabbit is eating a carrot" (uses the overridden method)
```
### 46. Method Chaining
**Method chaining** is used to call multiple methods sequentially. Each call
performs an action on the same object. For method chaining to work, each method
must **`return self`**.
**Code Example:**
```python
class Car: #
def turn_on(self): #
print("You start the engine") #
return self # Must return self for chaining
def drive(self): #
print("You drive the car") #
return self #
def brake(self): #
print("You step on the brakes") #
return self #
def turn_off(self): #
print("You turn off the engine") #
return self #
car = Car() # Create a Car object
# Chaining methods
car.turn_on().drive().brake().turn_off() # Calls all methods sequentially
# For readability, methods can be chained on new lines
car.turn_on()\
.drive()\
.brake()\
.turn_off()
```
### 47. Super Function
The **`super()` function** is used to give access to the methods of a parent class.
It returns a temporary object of a parent class when used. This is useful for
reusing common initialization or methods defined in a parent class.
**Code Example:**
```python
# Parent class
class Rectangle: #
def __init__(self, length, width): #
[Link] = length #
[Link] = width #
# Child class inheriting from Rectangle
class Square(Rectangle): #
def __init__(self, length, width): #
# Using super() to call the parent's __init__ method
super().__init__(length, width) # Passes length and width to Rectangle's
__init__
def area(self): # Unique method for Square
return [Link] * [Link] #
# Child class inheriting from Rectangle
class Cube(Rectangle): #
def __init__(self, length, width, height): #
# Using super() to call the parent's __init__ method for common attributes
super().__init__(length, width) #
[Link] = height # Unique attribute for Cube
def volume(self): # Unique method for Cube
return [Link] * [Link] * [Link] #
# Create objects
square = Square(3, 3) #
cube = Cube(3, 3, 3) #
# Call methods to verify __init__ was successful
print([Link]()) # Prints 9
print([Link]()) # Prints 27
```
### 48. Abstract Classes
**Abstract classes** prevent a user from creating an object of that class; they
function more as a template or idea. An abstract class also compels a user to
override any abstract methods within a child class. To create an abstract class,
import `ABC` (Abstract Base Class) and `abstractmethod` from the `abc` module.
**Code Example:**
```python
from abc import ABC, abstractmethod # Import necessary modules
# Abstract class
class Vehicle(ABC): # Inherit from ABC to make it an abstract class
@abstractmethod # Decorator to declare an abstract method
def go(self): # Abstract method: declared but no implementation
pass # Placeholder
@abstractmethod #
def stop(self): #
pass #
# Concrete child class
class Car(Vehicle): # Inherits from Vehicle
def go(self): # Must override abstract 'go' method
print("You drive the car") # Provides implementation
def stop(self): # Must override abstract 'stop' method
print("This car is stopped") #
# Concrete child class
class Motorcycle(Vehicle): # Inherits from Vehicle
def go(self): # Must override abstract 'go' method
print("You ride the motorcycle") # Provides implementation
def stop(self): # Must override abstract 'stop' method
print("This motorcycle is stopped") #
# Cannot create an object of an abstract class
# vehicle = Vehicle() # This would raise a TypeError: Can't instantiate abstract
class Vehicle with abstract methods go, stop
car = Car() # Can create objects of concrete child classes
motorcycle = Motorcycle() #
[Link]() # Prints "You drive the car"
[Link]() # Prints "You ride the motorcycle"
[Link]() # Prints "This car is stopped"
[Link]() # Prints "This motorcycle is stopped"
```
### 49. Passing Objects as Arguments
You can pass objects as arguments to functions, similar to how you pass variables.
**Code Example:**
```python
class Car: #
color = None # Class variable
class Motorcycle: #
color = None # Class variable
# Function that accepts an object and a color as arguments
def change_color(vehicle_object, color): # Parameter 'vehicle_object' will receive
the object
vehicle_object.color = color # Changes the color attribute of the passed object
# Create objects
car_one = Car() #
car_two = Car() #
car_three = Car() #
bike_one = Motorcycle() #
# Initial colors (None)
print(car_one.color, car_two.color, car_three.color, bike_one.color) # Prints None
None None None
# Pass objects as arguments to the function
change_color(car_one, "red") #
change_color(car_two, "white") #
change_color(car_three, "blue") #
change_color(bike_one, "black") #
# Check updated colors
print(car_one.color, car_two.color, car_three.color, bike_one.color) # Prints red
white blue black
```
### 50. Duck Typing
**Duck typing** is a concept where the class of an object is less important than
the methods and/or attributes that the object might have. The class type is not
checked if the minimum methods and/or attributes are present. It's based on the
phrase: "If it walks like a duck and it quacks like a duck, then it must be a
duck".
**Code Example:**
```python
class Duck: #
def walk(self): #
print("This duck is walking") #
def talk(self): #
print("This duck is quacking") #
class Chicken: #
def walk(self): #
print("This chicken is walking") #
def talk(self): #
print("This chicken is clucking") #
class Person: #
def catch(self, duck_object): # Parameter expects a 'duck_object'
duck_object.walk() # Calls walk method of the passed object
duck_object.talk() # Calls talk method of the passed object
print("You caught the critter!") #
# Create objects
duck = Duck() #
chicken = Chicken() #
person = Person() #
# Pass a Duck object
[Link](duck) # Prints duck's walk/talk methods
print("--------------")
# Pass a Chicken object (demonstrates duck typing)
# Even though the parameter is 'duck_object', a Chicken can be passed because it
has 'walk' and 'talk' methods
[Link](chicken) # Prints chicken's walk/talk methods
# Example of error if required method is missing
# class BrokenChicken:
# # def walk(self):
# # print("This chicken is walking")
# def talk(self):
# print("This chicken is clucking")
# broken_chicken = BrokenChicken()
# [Link](broken_chicken) # This would cause an AttributeError:
'BrokenChicken' object has no attribute 'walk'
```
### 51. Walrus Operator (`:=`)
The **walrus operator** (`:=`), also known as an **assignment expression**, is a
new feature for Python 3.8 and beyond. It assigns values to variables as part of a
larger expression.
**Code Example:**
```python
# Assign and print in one line
print(happy := True) # Prints True, and assigns True to 'happy'
print(happy) # Prints True
# Practical example: simplified loop for user input
foods = [] #
while food := input("What food do you like? ").lower() != "quit": # Assigns input
to 'food' and checks condition
[Link](food) #
print("Your favorite foods are:", foods)
```
### 52. Assigning a Function to a Variable
In Python, functions are treated as objects. You can assign a function's memory
address to a variable, allowing the variable to be called like the original
function.
**Code Example:**
```python
# Define a function
def hello(): #
print("Hello") #
# Print the memory address of the function
print(hello) # Prints something like <function hello at 0x...>
# Assign the function (its memory address) to a variable
hi = hello # No parentheses after 'hello'
# Both variables now point to the same function
print(hi) # Prints the same memory address
# Call the function using the new variable name
hi() # Prints "Hello"
hello() # Original name still works
# Assigning a built-in function to a variable
say = print # 'say' now refers to the built-in 'print' function
say("Whoa! This works!") # Prints "Whoa! This works!"
```
### 53. Higher Order Functions
**Higher order functions** are functions that either:
1. Accept a function as an argument.
2. Return a function as output.
**Code Example (Accepting a function as an argument):**
```python
def loud(text): # Function to make text uppercase
return [Link]() #
def quiet(text): # Function to make text lowercase
return [Link]() #
def hello(func): # Higher order function: accepts another function 'func' as an
argument
text = func("Hello") # Calls the passed function with "Hello"
print(text) #
hello(loud) # Pass 'loud' function as an argument: Prints "HELLO"
hello(quiet) # Pass 'quiet' function as an argument: Prints "hello"
```
**Code Example (Returning a function as output):**
```python
def divisor(x): # Outer function
def dividend(y): # Inner (nested) function
return y / x #
return dividend # Higher order function: returns the 'dividend' function
# Call the outer function, which returns the inner function
divide_by_2 = divisor(2) # 'divide_by_2' now holds the 'dividend' function with x=2
divide_by_5 = divisor(5) # 'divide_by_5' holds 'dividend' with x=5
# Call the returned function
print(divide_by_2(10)) # Calls dividend(10) where x is 2: Prints 5.0
print(divide_by_5(10)) # Calls dividend(10) where x is 5: Prints 2.0
```
### 54. Lambda Functions
**Lambda functions** are anonymous functions written in one line using the `lambda`
keyword. They accept any number of arguments but only have one expression. They are
useful for short, single-use functions.
**Code Example:**
```python
# Standard function to double a number
def double(x):
return x * 2
print(double(5)) # Prints 10
# Lambda function for doubling
double_lambda = lambda x: x * 2 # lambda parameter(s): expression
print(double_lambda(5)) # Prints 10
# Lambda with two parameters
multiply = lambda x, y: x * y #
print(multiply(5, 6)) # Prints 30
# Lambda with three parameters
add = lambda x, y, z: x + y + z #
print(add(5, 6, 7)) # Prints 18
# Lambda with strings
full_name = lambda first_name, last_name: first_name + " " + last_name #
print(full_name("Bro", "Code")) # Prints "Bro Code"
# Lambda for a conditional check
age_check = lambda age: True if age >= 18 else False #
print(age_check(12)) # Prints False
print(age_check(18)) # Prints True
```
### 55. Sorting Iterables
Python provides methods and functions to sort data in iterables like lists and
tuples.
**Code Example:**
```python
students = ["Squidward", "Sandy", "Patrick", "Spongebob", "Mr. Krabs"] #
# .sort() method (for lists only, sorts in-place)
[Link]() # Sorts alphabetically
for s in students:
print(s) # Prints Mr. Krabs, Patrick, Sandy, Spongebob, Squidward
# .sort(reverse=True) for reverse alphabetical order
[Link](reverse=True) #
for s in students:
print(s) # Prints Squidward, Spongebob, Sandy, Patrick, Mr. Krabs
# sorted() function (returns a new sorted list, works with any iterable like
tuples)
student_tuple = ("Squidward", "Sandy", "Patrick", "Spongebob", "Mr. Krabs") #
sorted_students = sorted(student_tuple) #
print(sorted_students) # Prints ['Mr. Krabs', 'Patrick', 'Sandy', 'Spongebob',
'Squidward']
# sorted(reverse=True) for reverse order
sorted_students_rev = sorted(student_tuple, reverse=True) #
print(sorted_students_rev) # Prints ['Squidward', 'Spongebob', 'Sandy', 'Patrick',
'Mr. Krabs']
# Sorting by a custom key (e.g., specific element in a tuple)
student_records = [
("Squidward", "F", 60),
("Sandy", "A", 33),
("Patrick", "D", 25),
("Spongebob", "B", 20),
("Mr. Krabs", "C", 78)
] #
# Sort by name (default, first element)
student_records.sort()
print("Sorted by name:", student_records)
# Sort by grade (index 1) using a lambda function as key
grade_key = lambda record: record # Lambda function returns the element at index 1
student_records.sort(key=grade_key) #
print("Sorted by grade:", student_records)
# Sort by age (index 2) using a lambda function as key
age_key = lambda record: record #
student_records.sort(key=age_key) #
print("Sorted by age (youngest first):", student_records)
# Sort by age (oldest first)
student_records.sort(key=age_key, reverse=True) #
print("Sorted by age (oldest first):", student_records)
```
### 56. Map Function
The **`map()` function** applies a function to each item in an iterable. It accepts
two arguments: the iterable and the function. `map()` returns a map object, which
can then be cast to other iterables like a list.
**Code Example:**
```python
store = [("shirt", 20.00),
("pants", 25.00),
("jacket", 50.00),
("socks", 10.00)] # List of tuples (item name, price)
# Function (lambda) to convert USD to EUR
# data is item name, data is price. Multiply price by 0.82
to_euros = lambda data: (data, data * 0.82) #
# Apply 'to_euros' function to each item in 'store' using map()
# Cast the map object to a list
store_euros = list(map(to_euros, store)) #
for item in store_euros:
print(item) # Prints items with prices in Euros
# Example: converting back to USD
to_dollars = lambda data: (data, data / 0.82) #
store_dollars = list(map(to_dollars, store_euros)) #
for item in store_dollars:
print(item) # Prints items with prices back in USD
```
### 57. Filter Function
The **`filter()` function** creates a collection of elements from an iterable for
which a given function returns `True`. It accepts an iterable and a function, and
returns a filter object.
**Code Example:**
```python
friends = [("Rachel", 19),
("Monica", 18),
("Phoebe", 17),
("Chandler", 16),
("Joey", 15),
("Ross", 21)] # List of tuples (name, age)
# Function (lambda) to check if age is 18 or older
# data is the age element in each tuple
age_check = lambda data: data >= 18 #
# Apply 'age_check' function to 'friends' using filter()
# Cast the filter object to a list
drinking_buddies = list(filter(age_check, friends)) #
for buddy in drinking_buddies:
print(buddy) # Prints friends who are 18 or older
```
### 58. Reduce Function
The **`reduce()` function** applies a function of your choosing to an iterable and
reduces that iterable to a single cumulative value. It performs the function on the
first two elements, then repeats the process with the result and the next element
until only one value remains. It needs to be imported from `functools`.
**Code Example:**
```python
from functools import reduce #
letters = ["H", "E", "L", "L", "O"] # List of letters
# Lambda function to combine two elements
# x is the cumulative result, y is the next element
concatenate_strings = lambda x, y: x + y #
# Apply 'concatenate_strings' to 'letters' using reduce()
word = reduce(concatenate_strings, letters) #
print(word) # Prints "HELLO"
# Example: Factorial calculation
numbers_for_factorial = #
# Lambda function to multiply two elements
multiply_numbers = lambda x, y: x * y #
# Apply 'multiply_numbers' to 'numbers_for_factorial'
factorial_result = reduce(multiply_numbers, numbers_for_factorial) #
print(factorial_result) # Prints 120 (5*4*3*2*1)
```
### 59. List Comprehensions
A **list comprehension** is a concise way to create a new list with less syntax. It
can mimic `map()` and `filter()` functions.
**Formula:** `[expression for item in iterable (if conditional) (if/else
expression)]`
**Code Example:**
```python
# Create a list of squares from 1 to 10 (traditional loop)
squares_loop = [] #
for i in range(1, 11): #
squares_loop.append(i * i) #
print("Traditional Loop:", squares_loop)
# List comprehension for squares
squares_comp = [i * i for i in range(1, 11)] #
print("List Comprehension:", squares_comp)
# Mimicking filter() with a list comprehension
student_grades = #
# Passing grades (60 or above)
passing_grades_comp = [i for i in student_grades if i >= 60] #
print("Passing Grades (if):", passing_grades_comp)
# List comprehension with if-else
# Replace failing grades with "FAILED"
# Formula: [expression if condition else else_expression for item in iterable]
processed_grades = [i if i >= 60 else "FAILED" for i in student_grades] #
print("Processed Grades (if-else):", processed_grades)
```
### 60. Dictionary Comprehensions
**Dictionary comprehensions** are similar to list comprehensions but create
dictionaries using an expression. They can replace `for` loops and certain lambda
functions for creating dictionaries.
**Formula:** `{key: expression for key, value in iterable (if conditional) (if/else
expression)}`
**Code Example:**
```python
# Convert Fahrenheit temperatures to Celsius
cities_in_f = {"New York": 32, "Boston": 75, "Los Angeles": 100, "Chicago": 50} #
# Dictionary comprehension for Celsius conversion
# Formula: (value - 32) * 5/9
cities_in_c = {key: round((value - 32) * (5/9)) for (key, value) in
cities_in_f.items()} #
print("Cities in Celsius:", cities_in_c)
# Create a dictionary with a conditional (only sunny weather)
weather = {"New York": "snowing", "Boston": "sunny", "Los Angeles": "sunny",
"Chicago": "cloudy"} #
# Dictionary comprehension with if conditional
sunny_weather = {key: value for (key, value) in [Link]() if value ==
"sunny"} #
print("Sunny Weather:", sunny_weather)
# Dictionary comprehension with if-else (temperature description)
# Return "warm" if value >= 40, else "cold"
desc_cities = {key: ("warm" if value >= 40 else "cold") for (key, value) in
cities_in_f.items()} #
print("Description Cities (warm/cold):", desc_cities)
# Dictionary comprehension with a function call for complex conditions
def check_temp(value): #
if value >= 70: #
return "hot" #
elif value >= 40: #
return "warm" #
else: #
return "cold" #
desc_cities_func = {key: check_temp(value) for (key, value) in cities_in_f.items()}
#
print("Description Cities (function):", desc_cities_func)
```
### 61. Zip Function
The **`zip()` function** aggregates elements from two or more iterables. It creates
a **zip object** with paired (or grouped) elements from each iterable, stored in
tuples. This zip object is iterable and can be cast to other types like lists or
dictionaries.
**Code Example:**
```python
usernames = ["dude", "bro", "mr"] # List
passwords = ("password", "abc123", "guest") # Tuple
# Create a zip object
users_zip = zip(usernames, passwords) #
# Iterate through the zip object (each item is a tuple)
for i in users_zip:
print(i) # Prints ('dude', 'password'), ('bro', 'abc123'), ('mr', 'guest')
# Reset zip object because it's exhausted after one iteration
users_zip = zip(usernames, passwords)
# Cast zip object to a list
users_list = list(users_zip) #
print("As List:", users_list) # Prints [('dude', 'password'), ('bro', 'abc123'),
('mr', 'guest')]
# Reset zip object again
users_zip = zip(usernames, passwords)
# Cast zip object to a dictionary (if two iterables are used, keys and values)
users_dict = dict(users_zip) #
print("As Dictionary:", users_dict) # Prints {'dude': 'password', 'bro': 'abc123',
'mr': 'guest'}
# Zip with three iterables
login_dates = ["1/1/2021", "1/2/2021", "1/3/2021"] #
users_full_info = zip(usernames, passwords, login_dates) #
for i in users_full_info:
print(i) # Prints ('dude', 'password', '1/1/2021'), etc.
```
### 62. If `__name__ == '__main__'`
The statement `if __name__ == '__main__'` gives Python modules flexibility,
allowing them to be run as a standalone program or imported and used by other
modules. The special variable `__name__` is assigned `"__main__"` if the module is
the initial one being run, and its module name if imported.
**File: `[Link]`**
```python
# [Link]
def hello(): #
print("Hello") #
print("This is [Link]") # This will always print when imported or run directly
print(f"__name__ in module1: {__name__}") #
if __name__ == '__main__': # This block only runs if [Link] is executed
directly
print("Running this module directly (module1)") #
hello() #
else: # This block runs if [Link] is imported
print("Running other module indirectly (module1)") #
```
**File: `[Link]`**
```python
# [Link]
import module1 # Imports [Link]
print("This is [Link]") #
print(f"__name__ in module2: {__name__}") # This will be '__main__' if module2 is
run directly
print(f"__name__ in module1 (imported): {module1.__name__}") # This will be
'module1'
if __name__ == '__main__': # This block only runs if [Link] is executed
directly
print("Running this module directly (module2)") #
[Link]() # Can call functions from imported module
else: # This block runs if [Link] is imported
print("Running other module indirectly (module2)")
```
**To test:**
* Run `[Link]` directly:
* Output will show `__name__ in module1: __main__` and "Running this module
directly (module1)"
* Run `[Link]` directly:
* Output will show `__name__ in module1: module1` and `__name__ in module2:
__main__` (from module2) then "Running this module directly (module2)".
### 63. Time Module
The `time` module provides various time-related functions.
**Code Example:**
```python
import time #
# [Link](0) - Converts a time expressed in seconds since epoch to a readable
string
# Epoch is the computer's reference point for time (e.g., Wed Dec 31 18:00:00 1969
for some systems)
print([Link](0)) # Prints the epoch time
print([Link](1000000)) # Prints date 1 million seconds after epoch
# [Link]() - Returns the current seconds that have passed since epoch
print([Link]()) # Prints a large float representing seconds since epoch
# Get current readable date and time
print([Link]([Link]())) # Combines [Link]() and [Link]()
# [Link]() - Creates a time object (struct_time) based on current local
time
time_obj = [Link]() #
print(time_obj) # Prints a struct_time object with various attributes (year, month,
day, etc.)
# [Link]() - Creates a time object based on current UTC (Coordinated Universal
Time)
utc_time_obj = [Link]() #
print(utc_time_obj)
# [Link](format, time_object) - Formats a time object into a string based on
directives
# Directives (e.g., %B for full month name, %d for day, %Y for year, %H for hour
(24-hour), %I for hour (12-hour), %M for minute, %S for second, %p for AM/PM)
formatted_time = [Link]("%I:%M:%S %p", time_obj) # Example: "03:45:30 PM"
print(formatted_time)
formatted_date = [Link]("%B %d, %Y", time_obj) # Example: "January 23, 2021"
print(formatted_date)
# [Link](string, format) - Parses a string representation of time/date into
a time object
time_string = "20 April, 2020" #
parsed_time_obj = [Link](time_string, "%d %B, %Y") #
print(parsed_time_obj) # Prints a struct_time object
# [Link](time_object/tuple) - Converts a time object or tuple to a readable
string
# Tuple must follow a specific order (year, month, day, hour, min, sec, weekday,
yearday, dst)
time_tuple = (2020, 4, 20, 4, 20, 0, 0, 0, 0) #
print([Link](time_tuple)) # Prints "Mon Apr 20 04:20:00 2020"
# [Link](time_tuple) - Converts a time tuple to seconds since epoch
print([Link](time_tuple)) # Prints seconds since epoch for that date/time
```
### 64. Multi-threading
**Multi-threading** involves having multiple threads (flows of execution) running
concurrently. In Python, due to the Global Interpreter Lock (GIL), threads run
concurrently but not truly in parallel (only one thread holds control of the
interpreter at any one time). It is better for **I/O bound tasks** (tasks that
spend most time waiting for external events like user input).
**Code Example:**
```python
import threading #
import time #
# CPU bound task vs I/O bound task distinction
# CPU bound: heavy computation (better for multiprocessing)
# I/O bound: waiting for input, web scraping (better for multithreading)
# Get current number of active threads
print(threading.active_count()) # Initially 1 (main thread)
# Get a list of all active threads
print([Link]()) # Shows the MainThread
# Define functions for tasks
def eat_breakfast(): #
[Link](3) # Simulate task duration
print("You eat breakfast") #
def drink_coffee(): #
[Link](4) #
print("You drank coffee") #
def study(): #
[Link](5) #
print("You finished studying") #
# Run tasks sequentially on the main thread (takes total_time = 3+4+5 = 12 seconds)
print("Running tasks sequentially:")
start_time_sequential = time.perf_counter() # Performance counter to measure time
eat_breakfast()
drink_coffee()
study()
end_time_sequential = time.perf_counter()
print(f"Sequential tasks finished in {round(end_time_sequential -
start_time_sequential, 2)} seconds\n")
# Run tasks concurrently using multi-threading (takes max_time = 5 seconds)
print("Running tasks concurrently with threads:")
start_time_concurrent = time.perf_counter() #
# Create threads for each task
# [Link](target=function_name, args=(arg1, arg2,...))
thread_eat = [Link](target=eat_breakfast) #
thread_drink = [Link](target=drink_coffee) #
thread_study = [Link](target=study) #
# Start the threads
thread_eat.start() #
thread_drink.start() #
thread_study.start() #
# The main thread can continue its work while other threads run
# print(threading.active_count()) # May show more than 1 thread before they
complete
# print([Link]()) # Lists all active threads
# Thread synchronization: Use .join() to make the main thread wait for other
threads to finish
thread_eat.join() # Main thread waits for thread_eat to complete
thread_drink.join() # Main thread waits for thread_drink to complete
thread_study.join() # Main thread waits for thread_study to complete
end_time_concurrent = time.perf_counter() #
print(f"Concurrent tasks finished in {round(end_time_concurrent -
start_time_concurrent, 2)} seconds") #
print(f"Active threads after join: {threading.active_count()}") # Will be 1 (only
main thread left)
print([Link]()) # Will only show MainThread
```
### 65. Daemon Threads
A **daemon thread** runs in the background and is typically not important for your
program to complete. The program will not wait for daemon threads to complete
before exiting. **Non-daemon threads** will keep the program alive until their task
is complete. Common uses for daemon threads include background tasks like garbage
collection or timers.
**Code Example:**
```python
import threading #
import time #
# Function for a background timer
def timer(): #
count = 0 #
while True: #
[Link](1) # Sleep for 1 second
count += 1 # Increment count
print(f"Logged in for {count} seconds") #
# Create a thread for the timer
x = [Link](target=timer) #
# Set the thread as a daemon thread
# If daemon=False (default), program waits for it. If True, program exits when non-
daemon threads finish.
[Link] = True #
# Alternative way: [Link](True) #
# Start the daemon thread
[Link]() #
# Check if the thread is a daemon (returns True/False)
print(f"Is timer thread a daemon? {[Link]()}") #
# Main thread's task: wait for user input
user_input = input("Do you wish to exit?\n") # Main thread waits for this input
print("Program exited.")
# When user_input is entered, the main thread finishes.
# If 'x' is a daemon thread, it will be killed. If non-daemon, it would continue.
```
### 66. Multi-processing
**Multi-processing** is the act of running tasks in parallel on different CPU
cores. Unlike multi-threading, it bypasses the GIL, allowing true parallel
execution. It is better for **CPU bound tasks** (tasks requiring heavy CPU usage).
**Code Example:**
```python
from multiprocessing import Process, cpu_count #
import time #
# On Windows, main code should be wrapped in if __name__ == '__main__':
# This prevents child processes from re-importing and re-executing the main script.
def main():
# Define a CPU-bound function
def counter(num): #
count = 0 #
while count < num: #
count += 1 #
print(f"Number of CPU cores: {cpu_count()}") #
# Measure time for sequential execution (single process)
print("\nStarting sequential execution...")
start_time_sequential = time.perf_counter()
counter(1_000_000_000) # Count to 1 billion
end_time_sequential = time.perf_counter()
print(f"Sequential count finished in {round(end_time_sequential -
start_time_sequential, 2)} seconds") #
# Measure time for parallel execution (multiple processes)
print("\nStarting parallel execution with multiple processes...")
start_time_parallel = time.perf_counter()
# Create processes
# Process(target=function_name, args=(arg1,))
# Note: args must be a tuple, even for a single argument (hence the comma)
num_to_count = 1_000_000_000 # Total count
num_processes = cpu_count() # Use number of CPU cores for optimal performance
count_per_process = num_to_count // num_processes
processes = []
for i in range(num_processes):
p = Process(target=counter, args=(count_per_process,)) #
[Link](p)
# Start all processes
for p in processes:
[Link]() #
# Join all processes (main process waits for children to finish)
for p in processes:
[Link]() #
end_time_parallel = time.perf_counter()
print(f"Parallel count finished in {round(end_time_parallel -
start_time_parallel, 2)} seconds") #
if __name__ == '__main__': # Required for multiprocessing on Windows
main()
```
### 67. Sending an Email using Python
This demonstrates how to send an email using Python's `smtplib` library. A Gmail
account and its password are required, and less secure app access may need to be
enabled temporarily in Gmail settings.
**Code Example:**
```python
import smtplib # Simple Mail Transfer Protocol library
# Email credentials and details
sender_email = "your_email@[Link]" # Replace with your sender email
receiver_email = "recipient_email@[Link]" # Replace with recipient email
password = "your_gmail_password" # Replace with your Gmail password
# Note: You might need to enable "Less secure app access" in your Google Account
settings
# (Google Account -> Security -> Less secure app access). Turn it off after use for
security.
subject = "Python Email Test" #
body = "I wrote an email from Python!" #
# Create the email header (f-string for easy variable insertion)
message = f"""From: {sender_email}
To: {receiver_email}
Subject: {subject}
{body}
""" #
try:
# Create an SMTP server object
# '[Link]' is for Gmail, port 587 is the default mail submission port
server = [Link]("[Link]", 587) #
# Start TLS (Transport Layer Security) encryption
[Link]() #
# Log in to your Gmail account
[Link](sender_email, password) #
print("Logged in!") #
# Send the email
[Link](sender_email, receiver_email, message) #
print("Email has been sent!") #
except [Link]: # Catches authentication errors (wrong
username/password or access denied)
print("Unable to sign in. Check your email, password, or 'Less secure app
access' settings.") #
except Exception as e:
print(f"An error occurred: {e}")
finally:
if 'server' in locals() and server: # Ensure server object was created before
quitting
[Link]() # Close the SMTP connection
```
### 68. Running a Python File using Command Prompt
To run a Python file using the command prompt (CMD on Windows, Terminal on
Mac/Linux), you need to navigate to the directory where your Python file is saved
and then invoke the Python interpreter.
**Steps:**
1. **Create a Python script:** Save a simple Python file (e.g., `hello_world.py`)
to an easily accessible location like your Desktop.
**Example `hello_world.py` content:**
```python
print("Hello world!") #
name = input("What's your name? ") #
print(f"Hello {name}!") #
```
2. **Open Command Prompt/Terminal:** Search for `cmd` (Windows) or open `Terminal`
(Mac/Linux).
3. **Navigate to the directory:** Use the `cd` (change directory) command to go to
the folder containing your Python file.
* **Find file path:** Right-click your Python file, go to "Properties"
(Windows) or "Get Info" (Mac), and copy the "Location" or "Where" path.
* **In CMD/Terminal:** Type `cd ` (note the space after `cd`) and then paste
the copied directory path. Press Enter.
* Example: `cd C:\Users\BroCode\Desktop`
4. **Run the script:** Type `python ` (note the space) followed by the name of
your Python script (including `.py` extension). Press Enter.
* Example: `python hello_world.py`
### 69. Using Pip for Python
**Pip** is a package manager for packages and modules from the Python Package Index
([Link]). Pip is usually included with Python versions 3.4 and above.
**Commands:**
* **Check Pip version:** `pip --version`
* **Upgrade Pip:** `pip install --upgrade pip`
* **List installed packages:** `pip list`
* **List outdated packages:** `pip list --outdated`
* **Upgrade a specific package:** `pip install package_name --upgrade` (e.g.,
`pip install pygame --upgrade`)
* **Install a new package:** `pip install package_name` (e.g., `pip install
pandas`)
### 70. Convert a Python File to an Executable
You can convert a Python file into a standalone executable (`.exe` on Windows)
using the `PyInstaller` package.
**Steps:**
1. **Prerequisites:** Ensure `pip` and `pyinstaller` are installed and up to date
(`pip install pyinstaller`).
2. **Create a dedicated folder:** Create a new, empty folder on your Desktop
(e.g., "MyExecutable").
3. **Copy files:** Copy your Python script (`.py` file) and any necessary assets
(like images, if it's a GUI app, ensuring images are in `.ico` format for the icon)
into this new folder.
* To convert an image to `.ico`: Use an online converter like
`[Link]`.
4. **Open Command Prompt/Terminal in the folder:** Navigate to the new folder's
directory in your command prompt. (See "Running a Python File using Command Prompt"
for how to `cd`).
5. **Run PyInstaller command:** Use the `pyinstaller` command with desired
options.
* **Basic command:** `pyinstaller your_script_name.py`
* **Common options:**
* `-F` (or `--onefile`): Packages everything into a single executable
file.
* `-w` (or `--noconsole`): Hides the console window for GUI applications.
(Omit for console applications)
* `-i [Link]` (or `--icon [Link]`): Sets a custom icon for the
executable (must be `.ico` format).
* **Example for a GUI script:** `pyinstaller -F -w -i [Link] [Link]`
6. **Find the executable:** After successful execution, the executable will be
found in the `dist` folder within your project directory. You can move it to your
Desktop or desired location.