Learn Python by Mehdi Karimi
Learn Python by Mehdi Karimi
Python
Full Course for
Beginners
Mehdi Karimi
Welcome to Learn Python: Full Course for Beginners, your comprehensive guide to mastering
one of the world’s most popular and versatile programming languages. Written by Mehdi
Karimi, this book is designed with beginners in mind, ensuring that even those with no prior
coding experience can develop a solid foundation in Python programming.
Python has become the language of choice for countless developers, data scientists, and tech
enthusiasts because of its simplicity, readability, and power. Whether you’re aiming to build
interactive web applications, automate repetitive tasks, analyze data, or dive into the fascinating
world of artificial intelligence, Python offers the tools and flexibility to turn your ideas into
reality.
Throughout this book, you’ll embark on a step-by-step journey through Python’s core concepts,
practical applications, and real-world use cases. Each chapter is carefully crafted to break down
complex topics into manageable sections, enriched with hands-on exercises, detailed
explanations, and projects to reinforce your learning.
By the end of this course, you’ll have not only the technical know-how to write Python code but
also the confidence to tackle challenges and continue growing as a programmer. Whether you’re
a student, a professional seeking a career pivot, or someone simply curious about coding, this
book is your gateway to unlocking the limitless potential of Python.
Let’s get started on this exciting journey to learn, explore, and create with Python!
We’ll start by setting up Python and a text editor to write our programs. First, we need to install Python.
Open your web browser and go to www.python.org/downloads. On this page, you’ll see two buttons:
one to download Python 3.6.3 (or the latest version of Python 3) and another for Python 2.7.14 (or the
latest Python 2 version).
Python 2 is an older, legacy version that is no longer actively maintained. While it has more
libraries and existing code written for it, it’s becoming outdated, and in a few years, it won’t be
used at all.
Python 3 is the current and future version of Python. It’s actively maintained and supported,
making it the better choice for most purposes.
In this tutorial, we’ll be learning Python 3, so we’ll download and install it. While Python 2 and
Python 3 are slightly different, the differences are minor. If you learn Python 3, you’ll still be
able to understand and work with Python 2 if needed. Python 3 is ideal for beginners, so that’s
what we’ll focus on.
To start:
1. Download Python 3: Go to the Python website, download Python 3, and open the file in your
Downloads folder.
2. Install Python 3: Double-click the installer and follow the prompts to complete the installation.
Once Python 3 is installed, the next step is to choose a text editor for writing and running your
code. You can technically use any text editor, like Notepad or TextEdit, but specialized tools
called IDEs (Integrated Development Environments) are better. IDEs are designed for
programming and can help spot errors and guide you in fixing them.
For this course, we’ll use PyCharm, one of the most popular IDEs for Python:
Now that you have Python 3 and PyCharm installed, you’re ready to start programming!
In this tutorial, we’ll create our first Python program and run it. Let’s get started!
1. Open PyCharm: Search for PyCharm on your computer and open it.
o When PyCharm starts, you’ll see a window prompting you to create a project.
o Optionally, you can change the appearance by going to Configure > Preferences
> Appearance and Behavior > Appearance and selecting a dark theme if you
prefer.
2. Create a New Project:
o Click Create New Project and name it (e.g., “draft”).
o In the Interpreter section, make sure to select Python 3. On Macs, Python 2
might be the default, so switch it to Python 3 to follow this tutorial properly.
3. Create a Python File:
o Inside the new project folder (e.g., “draft”), right-click, select New > Python File,
and name it (e.g., “app”).
o This file will contain our first Python program.
4. Write Your First Program:
o Type the following code in your Python file:
print("Hello, Mehdi!")
Congratulations! You’ve just written and executed your first Python program. From here, we’ll
dive into more exciting projects and learn new Python skills.
In this tutorial, we’ll write a simple Python program, learn how Python executes our code, and
use it to draw a basic shape on the screen. Let’s dive in!
When we program in Python, we’re giving the computer a set of instructions to follow. These
instructions can be simple or complex, and the computer will execute them in the order we write
them.
We’ll use Python’s print function to display a triangle on the screen. Here’s how it works:
The print function displays text or shapes in the console (a window where Python shows
output).
Inside the print() parentheses, we can type anything in quotes, and it will appear on the
screen.
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/____|")
Steps:
1. Write the Code: Copy and type the code above into your Python file. Each print() statement
draws a part of the shape.
2. Run the Code: Save the file, then click the Run button or the play button in PyCharm.
3. View the Output: Look at the console window below. You’ll see the triangle displayed.
Key Concepts:
Order Matters: Python runs the instructions in the order you write them. If you move a line of
code, it will change the output. For example, putting the last line ( ___) at the top would show
the base of the triangle first, followed by the rest of the shape.
The Console: This is where Python shows the results of your code. It’s like a window into what
your program is doing.
In this lesson, we learned the basics of writing and running Python code:
This is just the beginning! As we continue, we’ll explore more Python functions and build more
complex programs.
What will the output of the following code be? Write down your answer before running it in
Python.
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/____|")
print("Triangle Complete!")
/|
/ |
/ |
/ |
/____|
Triangle Complete!
Reorder the following lines to display the base of the triangle first, then the rest of the triangle:
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/----|")
print("/----|")
print(" /|")
print(" / |")
print(" / |")
print(" / |")
/----|
/|
/ |
/ |
/ |
Use the print function to draw the triangle with a base that is two lines longer.
python
Copy code
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print(" / |")
print(" / |")
print("/------|")
Output:
/|
/ |
/ |
/ |
/ |
/ |
/------|
python
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/----|")
Output:
perl
Copy code
/|
/ |
/ |
/ |
/----|
Write comments explaining what each line in the following code does:
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/----|")
Answer:
print(" ______")
print("| |")
print("| |")
print("|______|")
Output:
______
| |
| |
|______|
print("\\----/")
print(" \\ /")
print(" \\/")
Output:
\----/
\ /
\/
Combine triangles and rectangles to draw a house. Write the code for this.
Answer:
Output:
/\
/ \
/____\
| |
| |
|______|
1. Purpose of Variables:
o They help manage and modify data in programs efficiently, avoiding repetitive manual
changes.
2. Creating Variables:
o Variable names should be descriptive and separate words with underscores (e.g.,
character_name).
3. Benefits of Variables:
o Numbers: Store integers (e.g., 35) or decimals (e.g., 50.5). No quotation marks required.
6. Modifying Variables:
7. Practical Example:
o A story can dynamically use variables for names and ages. Changes to variables
automatically reflect throughout the program.
o String: "Tom"
o Integer: 35
o Decimal: 50.56
9. Key Takeaway:
Variables are a fundamental concept in Python programming. Mastering their use is essential for
creating efficient, readable, and maintainable code.
Code Example:
# Defining variables
character_name = "John"
character_age = 35
character_name = "Alice"
character_age = 28
print("Once upon a time, there was a person named " + character_name + ".")
print("She was " + str(character_age) + " years old.")
character_name = "Eve"
print(character_name + " decided to change her name.")
Test 2: Debugging
name = John
age = 25
print("His name is " + name + " and he is " + str(age) + " years old.")
Answer: The variable name should be a string, so it needs quotation marks(NameError: name
'John' is not defined). The corrected code is:
name = "John"
age = 25
print("His name is " + name + " and he is " + str(age) + " years old.")
Output:
Define a variable of each data type (string, integer, decimal, and boolean), and print their values.
Answer:
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is a student:", is_student)
Output:
Name: Tom
Age: 30
Height: 5.9
Is a student: False
Write a program where you define a variable, modify its value twice, and print it after each
modification.
Answer:
city = "Chicago"
print("Final city:", city)
Output:
Answer:
print(name + " is " + str(age) + " years old and her favorite color is " +
favorite_color + ".")
Output:
Create a program to check whether someone is eligible to vote. Use a boolean variable.
Answer:
age = 18
is_eligible = age >= 18 # Boolean condition
print("Age:", age)
print("Eligible to vote:", is_eligible)
Output:
Age: 18
Eligible to vote: True
Create a program that uses variables to create a dynamic story. The variables should include a
character's name, age, and a favorite activity.
Answer:
character_name = "Liam"
character_age = 10
favorite_activity = "playing soccer"
Output:
What happens if you try to concatenate a string with a number without converting the number to
a string? For example:
age = 30
print("Age: " + age)
Answer: This will result in a TypeError because Python does not automatically convert
integers to strings during concatenation. The error message would be:
Output:
Age: 30
name = "Emily"
age = 21
height = 5.4
is_graduate = True
Answer:
Output:
Answer:
a = 5
b = 10
print("Before swap: a =", a, ", b =", b)
Output:
Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5
Strings are a common data type in Python and represent plain text.
print("Wordnik Academy")
Wordnik Academy
print("Draft\nAcademy")
Output:
Draft
Academy
Escape Characters (\): Lets you include special characters like quotation marks.
print("This is a \"quote\".")
print("This is a backslash: \\")
Output:
This is a "quote".
This is a backslash: \
Using Variables
Output:
Draft Academy
String Concatenation
Output:
String Functions
Check Case:
print(phrase.islower()) # False
print(phrase.upper().isupper()) # True
print(len(phrase)) # 13
Access Characters: Use square brackets with index (starting from 0):
print(phrase[0]) # D
print(phrase[6]) # A
print(phrase.index("A")) # 6
print(phrase.index("Academy")) # 6
Replace Substring:
Output:
True
Answer: Output:
python programming
PYTHON PROGRAMMING
False
True
Write code to calculate the length of the string "Hello, World!" and predict the output.
Answer:
Output:
13
Write code to access and print the first and last characters of the string "Python".
Answer:
python
Copy code
word = "Python"
print(word[0]) # First character
print(word[-1]) # Last character
Output:
css
Copy code
P
n
python
Copy code
text = "Programming in Python"
print(text.index("P"))
print(text.index("Python"))
print(text.index("in"))
Answer: Output:
Copy code
0
16
11
Write code to replace the word "World" with "Universe" in the string "Hello, World!".
Answer:
python
Copy code
greeting = "Hello, World!"
print(greeting.replace("World", "Universe"))
Output:
arduino
Copy code
"This is a "quoted" word and a backslash: \."
Answer:
python
Copy code
print("\"This is a \"quoted\" word and a backslash: \\.\"")
Output:
arduino
Copy code
"This is a "quoted" word and a backslash: \."
Write code to store "Python" and "is awesome" in separate variables and combine them into a
single string.
Answer:
python
Copy code
first_part = "Python"
second_part = "is awesome"
print(first_part + " " + second_part)
Output:
csharp
Copy code
Python is awesome
python
Copy code
Answer: Output:
Copy code
JAVA PROGRAMMING
20
Answer:
python
Copy code
word = "Python"
print(word[::-1])
Output:
Copy code
nohtyP
Answer: Errors:
Corrected code:
Output:
Write code to create a personalized greeting where a user can input their name.
Answer:
mathematica
Copy code
Enter your name: Alice
Hello, Alice! Welcome to Python.
Python is fun.
Learn it.
Love it.
Answer:
Output:
Python is fun.
Learn it.
Love it.
Key Takeaways
In Python, numbers are a fundamental part of programming. Almost every program you'll create
will use numbers at some point. Here's a quick guide to the basics of working with numbers,
performing mathematical operations, and using functions related to numbers in Python.
1. Printing Numbers
print(2) # Prints: 2
print(2.0987) # Prints: 2.0987
print(-5) # Prints: -5
print(3 * 4 + 5) # Prints: 17
print(3 * (4 + 5)) # Prints: 27
Modulus (Remainder):
If you want to combine numbers with text, convert the number to a string using str():
5. Common Functions
print(abs(-5)) # Prints: 5
Rounding Numbers:
print(round(3.7)) # Prints: 4
print(round(3.2)) # Prints: 3
Square Root:
The math module contains many more functions. You can explore these by searching for
"Python math functions" online.
# Basic Arithmetic
print(7 + 3)
print(9 / 2)
# Variables
my_num = 8
print(my_num)
# String Conversion
print("The number is: " + str(my_num))
# Math Functions
print(abs(-10))
print(pow(2, 3))
print(max(10, 20))
print(min(10, 20))
print(round(3.6))
With these basics, you can perform many mathematical operations and build programs that
handle numbers effectively.
In Python, you can make your programs interactive by asking the user to input information. This
input can be stored in variables and used in your program. Here's how to do it.
You can use the input() function to get data from the user. Inside the parentheses, you can
include a prompt to guide the user. Here's an example:
name = input("Enter your name: ") # Asks the user to input their name and
stores it in the variable `name`
print("Hello, " + name + "!") # Prints a greeting using the name
How it works:
You can prompt the user for more than one piece of information by repeating the input()
function. For example:
How it works:
The program shows two prompts: Enter your name: and Enter your age:
The user types a name (e.g., John) and an age (e.g., 25).
The program prints: Hello, John, you are 25 years old!
Here’s the complete code for getting two inputs and responding:
mathematica
mathematica
4. The user types their age (e.g., 25) and presses Enter.
5. The program responds with:
sql
Key Points
1. Using input(): It allows the user to type information during the program's execution.
2. Storing Input: Save the input into variables for later use.
3. Combining Strings and Variables: Use + to combine text and variables.
4. Interactivity: Getting user input makes your programs more dynamic and engaging.
This is just the beginning! Inputs can be used to create more complex and interactive programs
as you continue learning Python.
Let's create a simple calculator in Python that allows users to enter two numbers. The program
will add the numbers and display the result. Along the way, we'll discuss how to handle user
input and convert it into numbers.
Use the input() function to get numbers from the user. Since input() always returns a string,
we need to convert the input into numbers. Here's the code for the calculator:
# Add the numbers (this will fail unless we convert the input to numbers
first)
result = num1 + num2
print("The result is:", result)
If you run this code and enter 5 and 8, the output will be 58 because Python is treating the inputs
as strings and concatenating them.
4. How It Works
5. Example Runs
plaintext
Copy code
Enter the first number: 4
Enter the second number: 5
The result is: 9.0
plaintext
Copy code
Enter the first number: 4.3
Enter the second number: 5.5
The result is: 9.8
1. User Input is a String: The input() function returns strings, so you must convert them into
numbers using int() or float().
2. Using float(): For this calculator, float() is more versatile because it handles both whole
and decimal numbers.
3. Simple Arithmetic: You can add numbers directly after conversion.
This is a simple yet functional calculator. In future lessons, you can extend it to perform other
operations like subtraction, multiplication, and division, or even handle invalid input gracefully!
Madlibs is a fun word game where players input random words like colors, nouns, or names, and
those words are inserted into a story. Let’s create a simple Madlibs game in Python using a short
poem as the base.
1. Ask the user for inputs: Prompt the user to enter specific types of words like a color, a plural
noun, and a celebrity.
2. Store the inputs: Save the user's responses in variables.
3. Insert inputs into a story: Use the collected words to fill in placeholders in a poem or story.
4. Print the result: Display the customized Madlibs story.
1. Input Collection:
o The input() function prompts the user to type in a word (e.g., a color, plural noun, or
celebrity name).
o The responses are stored in variables: color, plural_noun, and celebrity.
2. String Formatting:
o A formatted string (f-string) is used to insert the user’s words into a prewritten story.
3. Output:
o The print() function displays the final Madlibs story.
Example Run
Input:
plaintext
Copy code
Enter a color: magenta
Enter a plural noun: microwaves
Enter a celebrity: Tom Hanks
Output:
plaintext
Copy code
Roses are magenta, microwaves are blue, I love Tom Hanks.
Add more placeholders for user input (e.g., verbs, adjectives, or locations).
Include multiple print statements to create longer stories.
Use randomization for even more unpredictable results.
Homework Challenge
Try creating your own Madlibs game! Use a longer story, add more prompts, and make it as
funny or creative as you like. Here's a template to start with:
python
Copy code
# Create your own Madlibs story here
adjective = input("Enter an adjective: ")
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
famous_person = input("Enter a famous person: ")
# Story
madlib = f"Today was a {adjective} day. I saw a {noun} and decided to {verb}.
It reminded me of {famous_person}!"
⌨️--------------------------------------------------------------------------------------------------------------------------------Lists
Lists in Python are a way to organize and manage multiple pieces of data. Instead of creating a separate
variable for each value, you can store all related values in a single list. Let’s explore how to create,
access, and modify lists in Python.
Structure: Lists can hold multiple data types (strings, numbers, booleans).
Indexing: You can access elements by their position (starting from 0 for the first item).
Code Walkthrough
You can access specific items in the list using their index:
Negative Indexing: Start counting backward from -1 for the last item.
python
3. Slicing a List
python
# Slicing examples
4. Modifying Elements
# Modify an element
friends[1] = "Mike"
# Create a list
# Accessing elements
# Modifying an element
Next Steps
In the next tutorial, you’ll learn more advanced list operations, such as:
Adding elements
Removing elements
Copying lists
Lists are a powerful tool for managing and processing data in Python, and mastering them will make
your programming much more efficient!
⌨️………………………………………………………………………………………………………………………….List Functions
This tutorial explains how to use functions with lists in Python. Lists are essential data
structures for storing and organizing multiple values in Python. You can store various types of
information in lists, such as numbers, names, or anything else, and they can handle massive
amounts of data.
The tutorial introduces common list functions that help you manipulate and retrieve information
from lists. Below are the key list operations discussed, with Python examples for each:
lucky_numbers.sort()
print(lucky_numbers) # Outputs numbers in ascending order
⌨️------------------------------------------------------------------------------------------------------------------------Tuples
In this tutorial, we’ll discuss tuples in Python. A tuple is a type of data structure, similar to a list,
used to store multiple values. However, the main difference between tuples and lists is that
tuples are immutable, meaning their content cannot be changed after they are created.
Tuples are created using parentheses () (unlike lists, which use square brackets []).
Tuples are used when you want data that should not be changed.
# Creating a tuple
coordinates = (4, 5) # A tuple with two elements
1. Tuples:
o Immutable: Cannot change, add, or remove elements after creation.
o Syntax: Use parentheses () to define.
o Use case: Store fixed data (e.g., coordinates, configuration settings).
# A list
mutable_coordinates = [4, 5]
# Modifying a list
mutable_coordinates[1] = 10 # This works for a list
print(mutable_coordinates) # Output: [4, 10]
Tuples are often used inside lists when you want to store immutable data within a mutable
structure. For example:
Use tuples when the data should remain constant (e.g., fixed settings, points on a map).
Use lists when you need to modify the data.
Tuples are a great addition to your Python toolkit for specific situations where immutability is
required.
⌨️…………………………………………………………………………………………………………………………………………Functions
A function in Python is a reusable block of code that performs a specific task. Functions help
organize your code, make it easier to read, and reduce repetition.
Here’s an example:
# Defining a function
def say_hi():
print("Hello, User!") # This line is indented and part of the function
The function definition starts with def, followed by the function name and parentheses ().
The code inside the function must be indented to show it belongs to the function.
Functions are not executed automatically; they are executed only when called.
Parameters allow you to pass information to a function, making it more flexible. For example:
In this example:
You can define functions with multiple parameters to handle more data:
Here:
Flow of Execution
print("Top")
say_hi("Alice", 25)
print("Bottom")
Output:
Explanation:
Instead of writing similar code multiple times, use functions to centralize the logic:
Functions are a fundamental part of Python programming and will make your code cleaner,
reusable, and more efficient as you progress.
⌨️……………………………………………………………………………………………………………………Return Statement
The return statement in Python is used inside a function to send a value back to the code that
called the function. This allows functions to not only perform tasks but also provide results for
further use.
Let’s create a function that cubes a number (raises it to the power of 3) and returns the result.
Here:
You can store the result of a function in a variable for later use:
def example_function():
return "Done"
print("This will not run!") # This line is ignored
def return_string():
return "Hello, World!"
def return_boolean():
return True
def calculate_square(num):
return num * num
Parameters let you provide input to a function, and return lets you get output back.
result = multiply(6, 7)
print(result) # Output: 42
python
Copy code
def no_return():
print("No return here!")
Here:
The no_return function prints a message but does not use return.
When you print the result of no_return, it outputs None.
1. Reusability: The function can send results back for further use.
2. Modularity: Functions become more flexible and useful in larger programs.
3. Data Handling: Allows functions to process inputs and return meaningful outputs.
Summary
return sends data back to the caller and stops the function.
Use it when a function needs to provide a result.
Any code after return inside a function will not run.
You can return any data type (numbers, strings, lists, etc.).
It’s a powerful way to make functions more dynamic and reusable.
⌨️………………………………………………………………………………………………………………………………..If Statements
In Python, if statements let your program make decisions based on conditions. They allow you
to write code that can respond differently depending on the data or inputs. Here's an example to
illustrate:
Everyday Example:
Python's if statements work similarly. Let’s break it down with actual code examples.
Example:
Output:
o If is_male = True, prints: "You are a male."
o If is_male = False, nothing happens.
Example:
is_male = False
if is_male:
print("You are a male.") # Runs if True
else:
print("You are not a male.") # Runs if False
Output:
o If is_male = False, prints: "You are not a male."
You can check multiple conditions with and (both must be true) or or (one must be true).
Example:
is_male = True
is_tall = True
Use elif (short for else if) to add extra checks between the if and else.
Example:
is_hungry = False
is_thirsty = True
if is_hungry:
print("You should eat something.") # If hungry
elif is_thirsty:
print("You should drink water.") # If thirsty
else:
print("You are neither hungry nor thirsty.") # If neither
Important Notes:
1. Indentation Matters: Indent the code after if, elif, and else properly.
2. not Keyword: Negates a condition (e.g., not is_tall means "is not tall").
3. Code Stops After return: Once a return or a matched if condition runs, the program skips
the rest of the checks in the block.
python
Copy code
is_male = True
is_tall = False
In Python, you can use if statements not only to check True or False values directly but also to
compare numbers, strings, or other data types. These comparisons return True or False, which
the if statement uses to decide what action to take.
Let’s create a function called max_num that takes three numbers as input and returns the largest.
We'll use comparison operators like > (greater than) and >= (greater than or equal to) to
compare the numbers.
Explanation
1. Parameters: The function takes three numbers (num1, num2, num3) as input.
2. Comparison:
o The first if checks if num1 is greater than or equal to both num2 and num3.
o The elif checks if num2 is greater than or equal to both num1 and num3.
o The else assumes that num3 is the largest (if the first two conditions are false).
3. Return: The function returns the largest number.
4. Testing: We test the function by passing different sets of numbers.
You can compare numbers, strings, or even Booleans using these operators. For example:
python
Copy code
print("dog" == "dog") # Outputs: True
print("cat" != "dog") # Outputs: True
print(5 > 3) # Outputs: True
print(2 <= 1) # Outputs: False
Comparisons are a common way to make decisions in Python, and mastering them will help you
write more flexible and powerful programs.
Here’s a simplified and paraphrased explanation along with the Python code for creating a
calculator that performs basic arithmetic operations:
Python Code
# Get input from the user
num1 = float(input("Enter first number: ")) # Convert the input to a number
op = input("Enter operator (+, -, *, /): ") # Operator is a string
num2 = float(input("Enter second number: ")) # Convert the input to a number
1. Input:
o The program asks the user for two numbers (num1 and num2) and an operator (op).
o The float() function converts numeric input to a floating-point number for
calculations.
o The operator remains a string.
2. Conditions:
o if statements check the value of op to determine the operation:
+ for addition.
- for subtraction.
* for multiplication.
/ for division (with a special check to prevent division by zero).
o If the operator is invalid, an error message is displayed.
3. Output:
o The program prints the result of the operation or an error message if the input is invalid.
Sample Run
Example 1: Valid Inputs
Key Features:
1. Input Validation: Converts inputs to numbers and ensures the operator is valid.
2. Error Handling: Prevents division by zero and handles unknown operators.
This program demonstrates the practical use of if statements to build interactive and useful
applications in Python.
------------------------------------------------------------------------------------------
⌨️Dictionaries
Think of it like a real dictionary where words (keys) are linked to definitions (values).
We’ll create a dictionary to map three-letter month abbreviations (e.g., "JAN") to their full
names (e.g., "January") and learn how to use it.
Python Code
# Create a dictionary with abbreviated month names as keys and full names as
values
month_conversions = {
"JAN": "January",
"FEB": "February",
"MAR": "March",
"APR": "April",
"MAY": "May",
"JUN": "June",
"JUL": "July",
"AUG": "August",
"SEP": "September",
"OCT": "October",
"NOV": "November",
"DEC": "December"
}
1. Dictionary Creation:
o We define month_conversions using {} curly braces.
o Keys are three-letter abbreviations (e.g., "JAN").
o Values are full month names (e.g., "January").
2. Accessing Values:
o Use [] with a key (e.g., month_conversions["NOV"]) to get the associated value.
o Use .get(key) to retrieve values safely, avoiding errors if the key doesn’t exist.
Features of Dictionaries:
Unique Keys: Each key must be unique; duplicate keys cause errors.
Key Types: Keys can be strings, numbers, or other immutable types.
Efficient Lookup: Dictionaries provide quick access to values using keys.
Sample Output
Valid Key
November
March
Invalid Key with .get()
Notes on Flexibility
This tutorial demonstrates the basics of creating, accessing, and using dictionaries effectively in
Python.
-------------------------------------------------------------------------------------------------------------------Loops in Python
A while loop is a structure in Python that lets you repeat a block of code as long as a specific
condition is true.
The code inside the loop runs again and again until the condition becomes false.
We’ll create a simple program to print numbers from 1 to 10 and show how a while loop works.
# Initialize a variable
i = 1
How It Works
1. Initialize a Variable:
o We start by defining i = 1.
4. Condition Rechecked:
o After each loop, Python goes back to check if i <= 10.
o If the condition is still true, the loop runs again.
o If i > 10, the loop stops, and the program continues with the code after the loop.
Output
plaintext
Copy code
1
2
3
4
5
6
7
8
9
10
Done with loop
1. Condition Checking:
o Before every iteration, Python checks the condition in the while statement.
2. Incrementing Variables:
o Always make sure something inside the loop changes the condition (e.g., i += 1) to
prevent an infinite loop.
3. Loop Termination:
o When the condition becomes false, the loop stops, and the program continues with the
next lines of code.
Example Walkthrough
Iteration Process:
1. First Iteration:
o i = 1, 1 <= 10 → True → Print 1, then i = 2.
2. Second Iteration:
Summary
A while loop repeatedly executes code while the condition remains true.
Ensure the loop condition changes within the loop to prevent infinite loops.
While loops are versatile and can handle repetitive tasks, such as counting, waiting for user
input, or controlling programs.
This code and explanation show the basics of while loops, providing a foundation for using them
in Python effectively.
Here’s the code for the simplest version, where the user guesses until they get it right:
How It Works:
1. Track Guesses:
o Use guess_count to count how many guesses the user has made.
o Use guess_limit to set the maximum number of guesses.
2. Loop Condition:
o The loop continues while the guess is wrong and the user is not out of guesses.
3. Check Guesses:
o If the user still has guesses left (guess_count < guess_limit), ask for a guess.
o Otherwise, set out_of_guesses = True to end the loop.
1. Variables:
o secret_word: Stores the correct answer.
o guess: Holds the user’s current guess.
o guess_count and guess_limit: Track the number of attempts.
o out_of_guesses: Boolean to determine if the user ran out of guesses.
2. While Loops:
o Repeatedly prompt the user for input until the conditions change.
3. If Statements:
o Check if the user guessed correctly or used all their attempts.
Final Thoughts
This guessing game showcases how Python structures like variables, loops, and conditionals
work together. You can expand the game by adding:
A for loop in Python is a tool for iterating over collections like strings, arrays (lists), or ranges
of numbers. It lets you perform actions on each item in a collection, one at a time. Below are
examples of how for loops work and how they can be used:
What Happens?
D
r
a
f
t
A
c
a
d
e
m
y
What Happens?
Jim
Karen
Kevin
What Happens?
0
1
2
3
4
4. Custom Ranges
What Happens?
3
4
What Happens?
Prints each name in the friends list, one by one, using its index.
Output:
Jim
Karen
Kevin
You can include logic in a for loop, like checking if it’s the first iteration.
What Happens?
The program identifies and prints a special message for the first loop.
Output:
First iteration
Not the first iteration
Not the first iteration
Not the first iteration
Not the first iteration
These tools make Python's for loops highly versatile for repetitive tasks.
----------------------------------------------------------------------------------⌨️Exponent
Function
An exponent function raises a base number to a specific power. Python provides a simple way
to do this using **, but we’ll build our own version using a for loop to understand the process.
We'll create a function called raise_to_power that uses a for loop to calculate the result.
A two-dimensional list is a list where each element is another list. It can represent a grid or table
structure.
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
Accessing Elements
Example:
A nested loop is a loop inside another loop. You can use it to go through all elements in a two-
dimensional list.
1
2
3
4
5
6
7
8
9
0
Key Takeaways
1. Exponent Function:
o Use loops to manually compute powers when needed.
o Understand how Python's ** works for direct calculations.
2. Two-Dimensional Lists:
o Represent grids or tables in Python.
o Use nested loops to traverse all elements.
---------------------------------------------------------------------------------⌨️Building a
Translator
This translator converts a phrase into a custom language where all vowels (a, e, i, o, u) are
replaced by the letter "G". Here's how to create it step by step:
def translate(phrase):
We’ll let the user input a phrase, call the translate function, and print the result.
Example Runs
Input 1:
plaintext
Output:
plaintext
Copy code
dgg
Input 2:
plaintext
Copy code
Enter a phrase: TO BE OR NOT TO BE
Output:
plaintext
Copy code
TG BG GR NGT TG BG
plaintext
Copy code
Enter a phrase: On
Output:
plaintext
Copy code
Gn
1. Case Handling:
o Maintains the case of the original letters (uppercase or lowercase).
2. Efficiency:
o Simplified vowel checking using .lower() to avoid duplicating uppercase and
lowercase vowels.
3. Customizable:
o You can modify the if letter.lower() in "aeiou" condition to translate vowels
into other letters or symbols.
This program combines loops, conditionals, and string operations to create a useful and fun
translator app in Python!
Comments in Python are lines of text in your code that are ignored when the program runs.
They're meant for humans—either yourself or other developers—to leave notes or explanations
in the code. Python simply skips them during execution.
Example:
python
Copy code
# This is a single-line comment
print("Comments are fun!") # This prints a message
The comment doesn't show up in the program's output. It's purely for explanation.
2. Multi-Line Comments
Example:
python
Copy code
# This program prints a message.
# It demonstrates how comments work.
print("Hello, World!")
You can use triple quotes (''' or """) for multi-line comments.
python
Copy code
'''
This is a multi-line comment.
It can span multiple lines.
Useful for adding long explanations.
'''
print("Multi-line comments can use triple quotes!")
Triple quotes are technically treated as strings but ignored if not assigned to a variable. Still, # is
preferred for comments by Python standards.
Uses of Comments
1. Explain Code
Example:
python
Copy code
# This prints a greeting message
print("Hello, World!")
2. Leave Notes or Reminders
Write notes for yourself or collaborators about the purpose or functionality of certain parts of
the code.
Example:
python
Copy code
# print("This line is commented out and won't run.")
print("This line will run.")
1. Ignored by Python:
2. Best Practices:
o Use comments sparingly to explain why a piece of code exists, not what it does (good
code should already be self-explanatory).
3. Multi-Line Comments:
o Prefer multiple # lines over triple quotes for consistency with Python style guides.
# Print a message
print("Comments are fun!")
'''
This is a multi-line comment.
It can span multiple lines for detailed explanations.
Still, using multiple # symbols is the recommended style.
'''
print("Multi-line comments are cool!")
Output:
plaintext
Copy code
Comments are fun!
Multi-line comments are cool!
Comments help make your code more understandable and easier to maintain. Use them
effectively for explanations and debugging!
In Python, errors (also called exceptions) can stop your program from running. To avoid this,
you can use try-except blocks to "catch" errors and handle them, so your program doesn't crash.
Here's an overview of how to use them effectively.
Errors in Python
Errors happen when something goes wrong in the program. For example:
These errors will stop the program unless we handle them with try-except blocks.
Basic Example:
try:
number = int(input("Enter a number: ")) # Ask for a number and convert it
to an integer
print(f"You entered: {number}")
except:
print("Invalid input.") # This runs if the user enters something that
isn't a number
You can handle different types of errors separately for better clarity.
Example:
Using a generic except catches any error but is too broad and not a good practice.
Example:
python
Copy code
try:
value = 10 / 0
except:
print("An error occurred.")
This works but doesn't tell you what went wrong. Instead, handle specific errors like in the
example above.
You can also store the error in a variable and print it.
Example:
python
Copy code
try:
result = 10 / 0
except ZeroDivisionError as err:
print(f"Error: {err}") # Prints: Error: division by zero
python
Copy code
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
except Exception as err: # Catches any other unexpected errors
print(f"An unexpected error occurred: {err}")
Best Practices
Without error handling, simple mistakes like entering the wrong type of input can crash your
program. With try-except, your program becomes more robust and user-friendly!
----------------------------------------------------------------------------------⌨️Reading Files
In Python, you can work with external files like text, CSV, or HTML files using the open()
function. This lets you access the file's content for various tasks such as reading, writing, or
appending data. Here's how to do it step-by-step:
2. Reading Content
You can read the content of the file using:
o .read(): Reads the entire file as a string.
o .readline(): Reads one line at a time.
o .readlines(): Reads all lines and returns them as a list of strings.
3. Checking Readability
Use .readable() to verify if a file can be read. It returns True or False.
4. Closing the File
Always close the file after you're done using it with .close(). This ensures resources are
freed up and avoids potential issues.
5. Using Loops for Efficient Reading
Use a for loop with .readlines() to process files line by line.
python
Copy code
# Opening a file in read mode
employee_file = open("employees.txt", "r")
Instead of manually closing the file, use a with block for better safety:
python
Copy code
with open("employees.txt", "r") as employee_file:
print(employee_file.read()) # File is automatically closed after this
block
Key Points Recap:
By mastering these basics, you'll be ready to work with external files in Python for various
applications.
---------------------------------------------------------------------------------⌨️Writing to Files
In Python, you can not only read files but also write to files or append to existing files. Writing
lets you create or modify content, while appending adds new content without changing the
existing data. Here’s a breakdown of how these operations work:
Key Concepts
3. Appending to a File
o Appending ('a') adds content to the end of the file.
o To add text on a new line, use the escape character \n to specify a newline.
6. Escape Characters
o Use \n for a new line.
o Escape characters let you format the content properly when appending or writing.
1. Always Close Files: Use the with statement to automatically close files after use.
2. Escape Characters: Use \n to properly format content in new lines.
3. Avoid Overwriting by Accident: Be cautious when using 'w' mode as it will erase all existing
data.
This functionality makes Python a powerful tool for file management and automation tasks.
Modules are Python files (ending with .py) that contain reusable code, such as functions or
variables.
You can import modules into other Python scripts to access their functionality without copying
code.
Avoid duplicating code: Write functions/variables once, reuse them in multiple files.
Simplify your codebase by organizing code into logical pieces.
Access built-in or third-party modules to enhance your projects.
useful_tools.py
python
Copy code
# Variables
feet_in_mile = 5280
meters_in_kilometer = 1000
beatles = ["John", "Paul", "George", "Ringo"]
# Functions
def get_file_extension(filename):
return filename.split(".")[-1]
def roll_dice(sides):
import random
return random.randint(1, sides)
Using the useful_tools.py Module:
In another file, app.py, you can import and use this module like this:
# Accessing variables
print(f"Feet in a mile: {useful_tools.feet_in_mile}")
print(f"Beatles: {useful_tools.beatles}")
# Using functions
extension = useful_tools.get_file_extension("example.txt")
print(f"File extension: {extension}")
import math
bash
Copy code
pip install python-docx
import docx
doc = docx.Document()
doc.add_paragraph("Hello, world!")
doc.save("example.docx")
Install a module:
bash
Copy code
pip install module_name
bash
Copy code
pip --version
Uninstall a module:
bash
Copy code
pip uninstall module_name
1. Explore Built-in Modules: Check the Python Documentation for a complete list.
2. Find External Modules: Search online for specialized functionality (e.g., "Python module for X").
3. Read Instructions: Each module usually comes with usage guides.
4. Practice: Experiment with different modules to expand your Python skills.
Modules make Python a powerful and flexible language. By learning to use them effectively, you
can save time and create more robust programs.
Classes and objects are tools in Python that help you organize your code and model real-world
entities. Here's the main idea:
1. Classes: A class is like a blueprint for creating objects. It defines the structure (attributes) and
behavior (methods) that its objects will have.
2. Objects: An object is an instance of a class. It represents a specific entity created based on the
class.
In Python, we work with data types like strings, numbers, and booleans, and we use structures
like lists and dictionaries to store them. However, real-world entities—like a student, phone, or
computer—can't always be fully represented by basic data types. Classes allow us to create our
own custom data types to represent such entities.
Imagine we need to model students in a program for a university. Each student will have:
Name: A string.
Major: A string.
GPA: A float.
On probation: A boolean indicating probation status.
python
Copy code
# File: student.py
class Student:
def __init__(self, name, major, gpa, is_on_probation):
# Initialize attributes for each student object
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
__init__: A special method called when you create a new object. It sets up attributes for the
object.
self: Refers to the current object being created.
Now, use this class in another Python file to create specific students.
# File: app.py
from student import Student
1. Class: The blueprint defining what attributes and behaviors objects will have.
2. Object: A specific instance of the class.
3. Attributes: Data stored in the object (e.g., name, major).
4. Methods: Functions defined inside the class to perform actions.
Flexibility of Classes
Using classes, you can model any real-world entity by defining its attributes and behaviors. For
example, you can create classes for a Phone, Car, or even a Building, each with its own
properties.
This structure makes your programs organized, reusable, and closer to real-world concepts.
In this explanation, I'll show you how to create a simple multiple-choice quiz using Python. The
quiz will ask the user questions, track their score, and display the results at the end. We’ll use
key programming concepts like classes, loops, and conditional statements.
1. Question Prompts
First, create a list of questions. For example:
o What color are apples? (Options: A. Red, B. Purple, C. Orange)
o What color are bananas? (Options: A. Teal, B. Magenta, C. Yellow)
o What color are strawberries? (Options: A. Yellow, B. Red, C. Blue)
Python Code
python
Copy code
# Step 1: Create a Question class
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
Explanation
1. Class Question:
o Stores the prompt and answer for each question.
2. Question Array:
o We store multiple Question objects in a list, each with a specific prompt and answer.
3. Function run_test:
o Loops through the questions, takes user input, compares it with the correct answer, and
updates the score.
4. Output:
o After the quiz, it prints the number of correct answers.
Example Run
plaintext
Copy code
What color are apples?
(A) Red
(B) Purple
(C) Orange
> A
This program can be easily extended by adding more questions or features like scoring
percentages or timed quizzes.
⌨️Inheritance
Inheritance allows one class (a subclass) to inherit attributes and methods from another class (a
parent class). This means the subclass can use or override the parent class’s methods and add its
own new methods without duplicating code.
Explanation
1. Parent Class: Create a base class (Chef) with general attributes and methods, like making
dishes.
2. Subclass: Create a new class (ChineseChef) that inherits from Chef. This subclass gains all the
functionality of Chef but can also define its own methods or override parent methods.
3. Inheritance Benefits: Avoid repeating code when the subclass shares functionality with the
parent class.
4. Overriding Methods: A subclass can modify specific methods from the parent class to better suit
its needs.
Code Implementation
chef.py
python
Copy code
class Chef:
def make_chicken(self):
print("The chef makes chicken.")
def make_salad(self):
print("The chef makes salad.")
def make_special_dish(self):
print("The chef makes barbecue ribs.")
chinese_chef.py
python
class ChineseChef(Chef):
def make_fried_rice(self):
print("The chef makes fried rice.")
app.py
python
Copy code
from chinese_chef import ChineseChef
from chef import Chef
Output
yaml
Copy code
Generic Chef:
The chef makes chicken.
The chef makes barbecue ribs.
Chinese Chef:
The chef makes chicken.
The chef makes orange chicken.
The chef makes fried rice.
Key Concepts
This example showcases how you can effectively use inheritance to design structured and
efficient code in Python.
⌨️Python Interpreter
The Python interpreter is a tool that allows you to run Python code directly in a command-line
environment. It's like a quick way to test Python commands without needing to write a full script
or use an IDE. You can try out small pieces of code, functions, or test ideas quickly.
You can open the Python interpreter by using the command prompt (Windows) or terminal
(Mac). To use the interpreter, just type python3 in the terminal, and it will open up an interactive
environment where you can start typing Python code.
If you're using Windows and encounter problems with the command python3, it might be
because Python isn’t added to the Windows path variable. In that case, you need to adjust your
system settings so that Python can be recognized from the command prompt.
However, it’s not recommended for writing large programs. It’s more for quick tests. For bigger
projects, it's better to use a text editor or an IDE.
Code Examples
1. Printing a message:
python
Copy code
2. Simple arithmetic:
python
Copy code
num1 = 10
num2 = 90
print(num1 + num2) # Output: 100
3. Defining a function:
python
Copy code
def say_hi(name):
print("Hello " + name)
4. Using a loop:
python
Copy code
for i in range(5):
print(i)
5. Using an if statement:
python
Copy code
x = 10
if x > 5:
print("x is greater than 5")
Summary
The Python interpreter is great for testing small code snippets quickly without needing a full
project setup.
It's not ideal for writing large programs, so it's better for short, temporary tasks.
For more structured work, use a text editor or an IDE.
This tool is useful for experimentation and learning but not for serious software development.
It’s great for quick testing or trying out new Python ideas.