Day 1
Open IDLE. For reference, revise write a python program.
Write print("Hello World!")
Now there's a bunch of things you should notice. print() is a standard function (More on that later).
The quotes are important. Missing one of them will show an error looking something like:
>>> print("Hello World!)
File "", line 1
print("Hello World!)
SyntaxError: unterminated string literal (detected at line 1)
That's pretty cryptic. No worries. For now, all you have to know is to remember to quote-unquote the strs (Which is what text is called in python).
In the parentheses are the arguments of a function. print() is a function, and "Hello, World!" is an argument.
Day 2
Basics of Errors
By now you might have experienced an error. If you have not, try messing around with the code.
There are many types of errors in python, and they are highlighted in red when they come up, and the program stops abruptly.
For now, here are the most common errors you may see:
SyntaxError
This happens when something is wrong with the way you have written the code. It could be missing a character for example.¨
Example
>>> print("Welcome to the python world)
SyntaxError: unterminated string literal
NameError
Usually due to a typo, e.g. pront instead of print
Example
>>> pront("Welcome to the python world")
NameError: name 'pront' not defined
Runtime errors
e.g. dividing by zero...
Logical errors
These are pretty hard to find. These are like checking if something that never actually happens...
Day 3
Making a very simple game
Let's explore a simple game where each fork in the road, we can go left, straight or right.
And one random branch in the road is a dead end.
Lines starting with hashtags are comments in Python. They are not interpreted by the compiler, but they are useful to humans, especially if you come back to a program after a while away from it, or if someone else is looking at it.
from random import randint # IMPORT the FUNCTION randint from the standard python library called random.
print("Roadtrip") # PRINT "Roadtrip"
no_dead_end = True # SET A VARIABLE called no_dead_end to True
score = 0 # SET A VARIABLE called score to 0
valid_forks = ["left", "straight", "right"] # SET A LIST OF STRINGS called valid_forks of "left", "straight", and "right"
while no_dead_end: # REPEAT THE INDENTED CODE UNTIL no_dead_end IS False
dead_end_branch = randint(0, 2) # SET dead_end_branch TO a random number BETWEEN 0 and 2
chosen_fork = input("left, straight, or right? ").lower() # SET chosen_fork TO a user input CONVERTED TO lowercase
if chosen_fork not in valid_forks: # CHECK IF valid_forks DOESN'T CONTAIN chosen_fork
print("UNSUPPORTED FORK.")
continue # GO BACK TO THE START OF THE LOOP.
# IF INVALID INPUT THEN THIS WOULD NOT HAVE RUN, SO CONTINUE HERE IF VALID
int_fork = 1
if chosen_fork == "right": # IS chosen_fork EQUAL TO "right"?
int_fork = 2
elif chosen_fork == "left": # IS chosen_fork EQUAL TO "left"?
int_fork = 0
if int_fork == dead_end_branch: # IS int_fork EQUAL TO dead_end_branch?
print("DEADEND!") # DEAD end
no_dead_end = False
else:
print("You're moving on...")
score = score + 1 # SET score TO THE (CURRENT score) + 1
# END OF GAME
print("Your score:", score)
NOTE! Usually this many comments are not recommended, but this is for explanation purposes only.
This is a bit complicated, but let's see each bit one-by-one.
Imports
from random import randint imports the randint function from the random library. This allows us to generate random numbers, which is useful for our game.
Variables
Variables are like boxes that hold values. In our game, we have several variables:
no_dead_end: A boolean variable that controls the game loop. It starts as True and becomes False when the player reaches a dead end.
score: An integer variable that keeps track of the player's score.
valid_forks: A list of valid choices for the player to make at each fork in the road.
Loops
The while no_dead_end: loop runs as long as no_dead_end is True. Inside this loop, the player is prompted to choose a direction at each fork in the road.
Input
The input() function is used to get input from the player. The player's choice is converted to lowercase using the .lower() method to ensure consistency.
Conditionals
The if statements check the player's choice against the valid options and determine if the player has reached a dead end. If the player's choice is not valid, an error message is printed, and the loop continues to prompt for input.
If the player chooses a valid direction, the game checks if it leads to a dead end. If it does, the game ends; otherwise, the score is incremented.
Output
The final score is printed at the end of the game, giving the player feedback on their performance.
Running the Game
To run the game, copy the code into IDLE, save it as a Python file (e.g., roadtrip.py), and run it. You can play the game by entering your choices at each fork in the road.
This simple game demonstrates the use of variables, loops, conditionals, and input/output in Python. As you continue learning, you'll discover more advanced concepts and techniques to enhance your programming skills.
Day 4
Variables
Variables are like containers that hold data. In Python, you can create a variable by assigning a value to it using the equals sign (=).
Example
name = "Alice" # A string variable
age = 30 # An integer variable
height = 5.5 # A float variable
is_student = True # A boolean variable
print(name, age, height, is_student) # Output: Alice 30 5.5 True
In this example, we create four variables: name, age, height, and is_student. We then print their values using the print() function.
Data Types
Python has several built-in data types, including:
- String: A sequence of characters enclosed in quotes (e.g., "Hello, World!").
- Integer: A whole number (e.g., 42).
- Float: A number with a decimal point (e.g., 3.14).
- Boolean: Represents either
True or False.
- List: An ordered collection of items (e.g., [1, 2, 3]).
- Tuple: An ordered, immutable collection of items (e.g., (1, 2, 3)).
- Dictionary: A collection of key-value pairs (e.g., {"name": "Alice", "age": 30}).
Each data type has its own characteristics and methods for manipulation. For example, you can concatenate strings, perform arithmetic operations on integers and floats, and access elements in lists and dictionaries.
Type Conversion
You can convert between different data types using built-in functions like int(), float(), and str(). This is useful when you need to perform operations on different types of data.
Example
num_str = "42" # A string representation of a number
num_int = int(num_str) # Convert to integer
num_float = float(num_str) # Convert to float
print(num_int, num_float) # Output: 42 42.0
In this example, we convert a string representation of a number to both an integer and a float using the int() and float() functions.
Understanding variables, data types, and type conversion is essential for writing effective Python programs. As you continue learning, you'll explore more advanced concepts and techniques to manipulate data and create powerful applications.
Day 5
Operators
Operators are symbols that perform operations on variables and values. Python supports various types of operators, including arithmetic, comparison, logical, and assignment operators.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. The most common arithmetic operators in Python are:
+: Addition
-: Subtraction
*: Multiplication
/: Division (returns a float)
//: Floor Division (returns an integer)
%: Modulus (returns the remainder)
**: Exponentiation (raises to a power)
Example
a = 10
b = 3
print(a + b) # Output: 13 (Addition)
print(a - b) # Output: 7 (Subtraction)
print(a * b) # Output: 30 (Multiplication)
print(a / b) # Output: 3.333... (Division)
print(a // b) # Output: 3 (Floor Division)
print(a % b) # Output: 1 (Modulus)
print(a ** b) # Output: 1000 (Exponentiation)
Comparison Operators
Comparison operators are used to compare two values and return a boolean result (True or False). The most common comparison operators in Python are:
==: Equal to
!=: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
Example
x = 5
y = 10
print(x == y) # Output: False (Equal to)
print(x != y) # Output: True (Not equal to)
print(x > y) # Output: False (Greater than)
print(x < y) # Output: True (Less than)
print(x >= y) # Output: False (Greater than or equal to)
print(x <= y) # Output: True (Less than or equal to)
Logical Operators
Logical operators are used to combine conditional statements. The most common logical operators in Python are:
and: Returns True if both conditions are true
or: Returns True if at least one condition is true
not: Reverses the result of a condition
Example
a = True
b = False
print(a and b) # Output: False (Both conditions must be true)
print(a or b) # Output: True (At least one condition is true)
print(not a) # Output: False (Reverses the result)
print(not b) # Output: True (Reverses the result)
Assignment Operators
Assignment operators are used to assign values to variables. The most common assignment operator in Python is the equals sign (=). However, Python also supports compound assignment operators that combine assignment with arithmetic operations:
+=: Add and assign
-=: Subtract and assign
*=: Multiply and assign
/=: Divide and assign
//=: Floor divide and assign
%=: Modulus and assign
**=: Exponentiate and assign
Example
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
x -= 2 # Equivalent to x = x - 2
print(x) # Output: 6
x *= 2 # Equivalent to x = x * 2
print(x) # Output: 12
x /= 4 # Equivalent to x = x / 4
print(x) # Output: 3.0
x //= 2 # Equivalent to x = x // 2
print(x) # Output: 1.0
x %= 1 # Equivalent to x = x % 1
print(x) # Output: 0.0
x **= 3 # Equivalent to x = x ** 3
print(x) # Output: 0.0
Understanding operators is crucial for performing calculations, making comparisons, and controlling the flow of your Python programs. As you continue learning, you'll explore more advanced concepts and techniques to leverage operators effectively in your code.
Day 6
Control Flow
Control flow refers to the order in which the statements in a program are executed. In Python, control flow is primarily managed using conditional statements and loops.
Conditional Statements
Conditional statements allow you to execute different blocks of code based on certain conditions. The most common conditional statement in Python is the if statement, which can be combined with elif (else if) and else to create complex decision-making structures.
Example
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You are an adult.")
else:
print("You are a senior citizen.")
In this example, the program checks the value of the age variable and prints a message based on the condition that is met. If age is less than 18, it prints "You are a minor." If age is equal to 18, it prints "You are an adult." Otherwise, it prints "You are a senior citizen."
Loops
Loops allow you to repeat a block of code multiple times. Python supports two main types of loops: for loops and while loops.
Example
for i in range(5):
print(i)
In this example, the for loop iterates over a range of numbers from 0 to 4 (inclusive) and prints each number. The range(5) function generates a sequence of numbers from 0 to 4.
While Loop
A while loop continues to execute as long as a specified condition is True. It is useful when you don't know in advance how many times you need to iterate.
Example
count = 0
while count < 5:
print(count)
count += 1
In this example, the while loop continues to execute as long as count is less than 5. The loop prints the value of count and increments it by 1 in each iteration until the condition becomes False.
Break and Continue Statements
The break statement is used to exit a loop prematurely, while the continue statement skips the current iteration and moves to the next one.
Example
for i in range(10):
if i == 5:
break # Exit the loop when i is 5
print(i)
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
In the first example, the loop exits when i reaches 5, so it only prints numbers from 0 to 4. In the second example, the loop skips even numbers and only prints odd numbers from 0 to 9.
Understanding control flow is essential for creating dynamic and responsive programs. By using conditional statements and loops effectively, you can build complex logic and handle various scenarios in your Python applications.
Day 7
Functions
Functions are reusable blocks of code that perform a specific task. They allow you to organize your code into logical units, making it easier to read, maintain, and reuse. In Python, you can define your own functions using the def keyword.
Defining a Function
To define a function, you use the def keyword followed by the function name and parentheses. You can also specify parameters inside the parentheses, which are variables that the function can accept as input.
Example
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
In this example, we define a function called greet that takes a parameter name. When we call the function with different names, it prints a personalized greeting.
Return Statement
Functions can also return a value using the return statement. This allows you to pass data back to the caller of the function.
Example
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
In this example, we define a function called add that takes two parameters a and b. The function returns the sum of the two numbers, which we then print.
Default Parameters
You can also define default values for function parameters. If the caller does not provide a value for a parameter with a default value, the function will use the default value.
Example
def format_name(first, last, middle=''):
if middle:
return first + " " + middle + " " + last
else:
return first + " " + last
Day 8
Lists and List Operations
Lists are one of the most versatile data structures in Python. They allow you to store multiple items in a single variable.
Creating a List
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
Accessing List Elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Modifying Lists
fruits.append("orange") # Add to end
fruits[1] = "blueberry" # Change value
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'orange']
Iterating Over a List
for fruit in fruits:
print(fruit)
List Methods
append(): Add an item to the end
insert(): Insert at a specific position
remove(): Remove a specific item
pop(): Remove and return an item
sort(): Sort the list
reverse(): Reverse the list
Day 9
Dictionaries
Dictionaries store data as key-value pairs. They are useful for when you want to associate a value with a specific key.
Creating a Dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"]) # Output: Alice
Adding and Modifying Entries
person["email"] = "alice@example.com"
person["age"] = 31
print(person)
Iterating Over a Dictionary
for key, value in person.items():
print(key, value)
Dictionary Methods
keys(): Returns all keys
values(): Returns all values
items(): Returns all key-value pairs
get(): Returns the value for a key
pop(): Removes a key-value pair
Day 10
Tuples and Sets
Tuples
Tuples are like lists, but they are immutable (cannot be changed).
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
Sets
Sets are unordered collections of unique elements.
numbers = {1, 2, 3, 2, 1}
print(numbers) # Output: {1, 2, 3}
Set Operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union: {1, 2, 3, 4, 5}
print(a & b) # Intersection: {3}
print(a - b) # Difference: {1, 2}
Day 11
Scope
Scope refers to the visibility and lifetime of variables in a program. In Python, there are two main types of scope: local and global.
Local Scope
Variables defined inside a function have local scope, meaning they are only accessible within that function.
Example
def my_function():
local_var = "I am local"
print(local_var) # Output: I am local
my_function()
# print(local_var) # This would raise an error because local_var is not defined outside the function
Global Scope
Variables defined outside of any function have global scope, meaning they can be accessed from anywhere in the program.
Example
global_var = "I am global"
def another_function():
print(global_var) # Output: I am global
another_function()
print(global_var) # Output: I am global
Global Keyword
You can use the global keyword to modify a global variable inside a function.
Example
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1
If you forget to write global, then print(count) will show 0, the unincremented count.
Day 12
Modules and Packages
Modules are files containing Python code that can be imported into other Python programs. They allow you to organize your code into reusable components.
Creating a Module
To create a module, simply create a Python file with a .py extension. You can define functions, classes, and variables in this file.
Example
# my_module.py
def greet(name):
return "Hello, " + name + "!"
def add(a, b):
return a + b
Importing a Module
You can import a module using the import statement. You can then access the functions and variables defined in the module.
Example
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
print(my_module.add(3, 5)) # Output: 8
Importing Specific Functions
You can also import specific functions from a module using the from keyword.
Example
from my_module import greet
print(greet("Bob")) # Output: Hello, Bob!
Packages
Packages are a way to organize related modules into a directory hierarchy. A package is simply a directory containing an __init__.py file.
Example
my_package/
├── __init__.py
├── module1.py
└── module2.py
You can import modules from a package using the dot notation.
Example
from my_package import module1, module2
print(module1.some_function())
print(module2.another_function())
Day 13
File Handling
File handling in Python allows you to read from and write to files on your computer. This is useful for storing data, logging information, or processing large datasets.
Opening a File
You can open a file using the open() function. The first argument is the file name, and the second argument specifies the mode (e.g., read, write, append).
Example
file = open("example.txt", "r") # Open a file for reading
content = file.read() # Read the entire file content
print(content)
file.close() # Close the file
Reading from a File
You can read the contents of a file using methods like read(), readline(), or readlines().
Example
file = open("example.txt", "r")
line = file.readline() # Read a single line
print(line)
lines = file.readlines() # Read all lines into a list
print(lines)
file.close()
Writing to a File
You can write to a file using the write() or writelines() methods. Make sure to open the file in write mode ("w") or append mode ("a").
Example
file = open("output.txt", "w") # Open a file for writing
file.write("Hello, World!\n") # Write a string to the file
file.writelines(["Line 1\n", "Line 2\n"]) # Write multiple lines
file.close() # Close the file
Using Context Managers
It's a good practice to use context managers (the with statement) when working with files. This ensures that the file is properly closed, even if an error occurs.
Example
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need to explicitly close the file
with open("output.txt", "w") as file:
file.write("This is a new file.\n")
file.writelines(["Line A\n", "Line B\n"])
File handling is an essential skill for any programmer, as it allows you to work with data stored in files. By mastering file handling in Python, you can create applications that read, write, and manipulate data efficiently.
Day 14
Exception Handling
Exception handling in Python allows you to gracefully handle errors and exceptions that may occur during the execution of your program. This is important for maintaining the stability and reliability of your code.
Try and Except Blocks
You can use try and except blocks to catch exceptions and handle them appropriately. The code inside the try block is executed, and if an exception occurs, the control is transferred to the corresponding except block.
Example
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print("An error occurred:", e)
In this example, we attempt to divide by zero, which raises a ZeroDivisionError. The corresponding except block catches the exception and prints an error message.
Multiple Except Blocks
You can have multiple except blocks to handle different types of exceptions. This allows you to provide specific error handling for each type of exception.
Example
coming soon...