Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
74 views

Learn Python by Mehdi Karimi

Learn Python by Mehdi Karimi telegram @MehdiSufi ?✨ Dive into the world of Python with Mehdi Karimi's insightful book! ? Whether you’re a beginner or looking to enhance your coding skills, this book covers everything from the basics to advanced concepts. With clear explanations, practical examples, and hands-on projects, you'll master Python in no time! ?? For updates, tips, and more coding inspiration, follow Mehdi on Instagram at @Mehdi_._Sufi Happy coding! #مهدی_کریمی #مهدی_کریمی_آیلتس #آیلتس #mehdi_karimi #mehdi_karimi_ielts #ielts #english مهدی_کریمی مهدی_کریمی_آیلتس آیلتس mehdi_karimi mehdi_karimi_ielts ielts مهدی کریمی آیلتس آیلتس mehdi karimi mehdi karimi ielts english

Uploaded by

liamk3198
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
74 views

Learn Python by Mehdi Karimi

Learn Python by Mehdi Karimi telegram @MehdiSufi ?✨ Dive into the world of Python with Mehdi Karimi's insightful book! ? Whether you’re a beginner or looking to enhance your coding skills, this book covers everything from the basics to advanced concepts. With clear explanations, practical examples, and hands-on projects, you'll master Python in no time! ?? For updates, tips, and more coding inspiration, follow Mehdi on Instagram at @Mehdi_._Sufi Happy coding! #مهدی_کریمی #مهدی_کریمی_آیلتس #آیلتس #mehdi_karimi #mehdi_karimi_ielts #ielts #english مهدی_کریمی مهدی_کریمی_آیلتس آیلتس mehdi_karimi mehdi_karimi_ielts ielts مهدی کریمی آیلتس آیلتس mehdi karimi mehdi karimi ielts english

Uploaded by

liamk3198
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Learn

Python
Full Course for
Beginners
Mehdi Karimi

Instagram >> @IELTS_Wordnik


Introduction

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!

Mehdi Karimi  Telegram: @MehdiSufi

Instagram >> @IELTS_Wordnik


⭐️Contents ⭐
⌨️ Introduction
⌨️ Installing Python & PyCharm
⌨️ Setup & Hello World
⌨️ Drawing a Shape
⌨️ Variables & Data Types
⌨️ Working With Strings
⌨️ Working With Numbers
⌨️ Getting Input From Users
⌨️ Building a Basic Calculator
⌨️ Mad Libs Game
⌨️ Lists
⌨️List Functions
⌨️ Tuples
⌨️ Functions
⌨️ Return Statement
⌨️ If Statements
⌨️ If Statements & Comparisons
⌨️ Building a better Calculator
⌨️ Dictionaries
⌨️ While Loop
⌨️ Building a Guessing Game
⌨️ For Loops

Instagram >> @IELTS_Wordnik


⌨️ Exponent Function
⌨️ 2D Lists & Nested Loops
⌨️ Building a Translator
⌨️ Comments
⌨️Try / Except
⌨️ Reading Files
⌨️ Writing to Files
⌨️ Modules & Pip
⌨️ Classes & Objects
⌨️ Building a Multiple Choice Quiz
⌨️ Object Functions
⌨️ Inheritance
⌨️ Python Interpreter

Instagram >> @IELTS_Wordnik


⌨️----------------------------------------------------------------------------------------
Introduction

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).

Here’s the key difference between the two:

 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.

⌨️----------------------------------------------------------------------------Installing Python &


PyCharm

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:

1. Download PyCharm: Go to jetbrains.com/pycharm and click "Download Now."


2. Choose the Free Version: Select the Community Edition, which is free and open-source.

Instagram >> @IELTS_Wordnik


3. Install PyCharm: Open the downloaded file and follow the instructions to install it. (On a Mac,
drag it to your Applications folder.)

Now that you have Python 3 and PyCharm installed, you’re ready to start programming!

⌨️-----------------------------------------------------------------------------------Setup & Hello


World

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!")

o This simple program will display “Hello, Mehdi!” in the console.


5. Run the Program:
o Click Run at the top of the PyCharm window, then select the file you created
(e.g., “app”).
o Look at the bottom console panel, where you’ll see Hello, Mehdi! printed.

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.

Instagram >> @IELTS_Wordnik


⌨️-----------------------------------------------------------------------------------------Drawing a
Shape

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!

What is Programming in Python?

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.

Writing Our First Shape

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.

Example: Drawing a Triangle

Here’s the code to create a right triangle:

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.

Instagram >> @IELTS_Wordnik


Summary

In this lesson, we learned the basics of writing and running Python code:

1. Use print() to display output.


2. Python runs instructions in order.
3. The console shows the results of our program.

This is just the beginning! As we continue, we’ll explore more Python functions and build more
complex programs.

Test 1: Predict the Output

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!")

Answer: The output will be:

/|
/ |
/ |
/ |
/____|
Triangle Complete!

The print("Triangle Complete!") line adds text below the triangle.

Test 2: Rearrange the Code

Reorder the following lines to display the base of the triangle first, then the rest of the triangle:

print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/----|")

Instagram >> @IELTS_Wordnik


Answer: The reordered code should look like this:

print("/----|")
print(" /|")
print(" / |")
print(" / |")
print(" / |")

The output will be:

/----|
/|
/ |
/ |
/ |

Test 3: Modify the Shape

Use the print function to draw the triangle with a base that is two lines longer.

Answer: Modified code:

python
Copy code
print(" /|")
print(" / |")
print(" / |")
print(" / |")
print(" / |")
print(" / |")
print("/------|")

Output:

/|
/ |
/ |
/ |
/ |
/ |
/------|

Test 4: Debug the Code

Fix the following code so that it displays a triangle correctly:

python

Instagram >> @IELTS_Wordnik


Copy code
print(" /|")
print(" / |")
print(" / |")
print(" / |") # Error here
print("/----|")

Answer: The corrected code:

print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/----|")

Output:

perl
Copy code
/|
/ |
/ |
/ |
/----|

Test 5: Add Comments

Write comments explaining what each line in the following code does:

print(" /|")
print(" / |")
print(" / |")
print(" / |")
print("/----|")

Answer:

# Draws the top part of the triangle


print(" /|")
# Draws the second line of the triangle
print(" / |")
# Draws the third line of the triangle
print(" / |")
# Draws the fourth line of the triangle
print(" / |")
# Draws the base of the triangle
print("/----|")

Instagram >> @IELTS_Wordnik


Test 6: Experiment with Shapes

Use the print function to draw a different shape, like a rectangle.

Answer: Code for a rectangle:

print(" ______")
print("| |")
print("| |")
print("|______|")

Output:

______
| |
| |
|______|

Test 7: Create an Inverted Triangle

Write code to display an inverted triangle.

Answer: Code for an inverted triangle:

print("\\----/")
print(" \\ /")
print(" \\/")

Output:

\----/
\ /
\/

Test 8: Creative Challenge

Combine triangles and rectangles to draw a house. Write the code for this.

Answer:

# Roof of the house


print(" /\\")
print(" / \\")
print(" /____\\")

Instagram >> @IELTS_Wordnik


# Body of the house
print("| |")
print("| |")
print("|______|")

Output:

/\
/ \
/____\
| |
| |
|______|

⌨️-------------------------------------------------------------------------------------------------------Variables & Data


Types

1. Purpose of Variables:

o Variables act as containers for storing data values.

o They help manage and modify data in programs efficiently, avoiding repetitive manual
changes.

2. Creating Variables:

o Use the syntax variable_name = value.

o Variable names should be descriptive and separate words with underscores (e.g.,
character_name).

3. Benefits of Variables:

o Simplify updates: Changing a variable's value updates it everywhere in the program.

o Enhance code readability and maintainability.

4. Data Types in Variables:

o Strings: Represent text (e.g., "John"). Use quotation marks.

o Numbers: Store integers (e.g., 35) or decimals (e.g., 50.5). No quotation marks required.

o Booleans: Represent True or False. Useful for conditional logic.

5. Using Variables in Print Statements:

o Concatenate text and variables using the + operator. Example:

Instagram >> @IELTS_Wordnik


print("There once was a man named " + character_name + ".")

6. Modifying Variables:

o Variables can be updated during the program's execution. Example:

character_name = "Mike" # Changes the value of the variable.

7. Practical Example:

o A story can dynamically use variables for names and ages. Changes to variables
automatically reflect throughout the program.

8. Data Type Examples:

o String: "Tom"

o Integer: 35

o Decimal: 50.56

o Boolean: True or False

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

# Using variables in print statements


print("There once was a man named " + character_name + ".")
print("He was " + str(character_age) + " years old.")
character_name = "Mike" # Modifying the variable
print("Later, his name changed to " + character_name + ".")

Instagram >> @IELTS_Wordnik


Test 1: Identify the Output

What will the following code output?

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.")

Answer: The output will be:

Once upon a time, there was a person named Alice.


She was 28 years old.
Eve decided to change her name.

Test 2: Debugging

Find and fix the error in this code:

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:

His name is John and he is 25 years old.

Test 3: Experimenting with Data Types

Define a variable of each data type (string, integer, decimal, and boolean), and print their values.

Answer:

Instagram >> @IELTS_Wordnik


name = "Tom" # String
age = 30 # Integer
height = 5.9 # Decimal
is_student = False # Boolean

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

Test 4: Modify Variables

Write a program where you define a variable, modify its value twice, and print it after each
modification.

Answer:

city = "New York"


print("Original city:", city)

city = "Los Angeles"


print("Updated city:", city)

city = "Chicago"
print("Final city:", city)

Output:

Original city: New York


Updated city: Los Angeles
Final city: Chicago

Test 5: Concatenate Variables

Write code to display the sentence:


"Sarah is 25 years old and her favorite color is blue."

Answer:

Instagram >> @IELTS_Wordnik


name = "Sarah"
age = 25
favorite_color = "blue"

print(name + " is " + str(age) + " years old and her favorite color is " +
favorite_color + ".")

Output:

Sarah is 25 years old and her favorite color is blue.

Test 6: Boolean Logic

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

Test 7: Dynamic Story

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"

print(character_name + " is " + str(character_age) + " years old.")


print("He loves " + favorite_activity + " every afternoon.")

Output:

Instagram >> @IELTS_Wordnik


Liam is 10 years old.
He loves playing soccer every afternoon.

Test 8: Type Conversion Error

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:

TypeError: can only concatenate str (not "int") to str

The correct code is:

print("Age: " + str(age))

Output:

Age: 30

Test 9: Data Type Check

Write a program to print the data types of the following variables:

name = "Emily"
age = 21
height = 5.4
is_graduate = True

Answer:

print(type(name)) # Output: <class 'str'>


print(type(age)) # Output: <class 'int'>
print(type(height)) # Output: <class 'float'>
print(type(is_graduate)) # Output: <class 'bool'>

Output:

Instagram >> @IELTS_Wordnik


<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Test 10: Update Variables

Write a program to swap the values of two variables.

Answer:

a = 5
b = 10
print("Before swap: a =", a, ", b =", b)

# Swapping the variables


temp = a
a = b
b = temp

print("After swap: a =", a, ", b =", b)

Output:

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5

⌨️--------------------------------------------------------------------------------------------------------Working With Strings

Strings are a common data type in Python and represent plain text.

Creating and Printing Strings

To create a string, use quotation marks (" " or ' '):

print("Wordnik Academy")

Instagram >> @IELTS_Wordnik


This prints:

Wordnik Academy

Special Characters in Strings

 New Line (\n): Adds a line break.

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

Store strings in variables:

phrase = "Draft Academy"


print(phrase)

Output:

Draft Academy

String Concatenation

Combine strings using +:

Instagram >> @IELTS_Wordnik


print(phrase + " is cool!")

Output:

Draft Academy is cool!

String Functions

Functions perform specific tasks with strings. Use variable.function_name() syntax.

 Convert to Lowercase or Uppercase:

print(phrase.lower()) # draft academy


print(phrase.upper()) # DRAFT ACADEMY

 Check Case:

print(phrase.islower()) # False
print(phrase.upper().isupper()) # True

 Find String Length:

print(len(phrase)) # 13

 Access Characters: Use square brackets with index (starting from 0):

print(phrase[0]) # D
print(phrase[6]) # A

 Find Substring or Character Index:

print(phrase.index("A")) # 6
print(phrase.index("Academy")) # 6

 Replace Substring:

print(phrase.replace("Draft", "Elephant")) # Elephant Academy

Advanced Example: Combining Functions

You can chain functions for advanced operations:

Instagram >> @IELTS_Wordnik


print(phrase.upper().isupper()) # Converts to uppercase, then checks if it's
uppercase

Output:

True

Test 1: Predict the Output

What will the following code output?

phrase = "Python Programming"


print(phrase.lower())
print(phrase.upper())
print(phrase.islower())
print(phrase.upper().isupper())

Answer: Output:

python programming
PYTHON PROGRAMMING
False
True

Test 2: String Length

Write code to calculate the length of the string "Hello, World!" and predict the output.

Answer:

text = "Hello, World!"


print(len(text))

Output:

13

Instagram >> @IELTS_Wordnik


Test 3: Access Characters

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

Test 4: Find Substring or Character Index

What will the following code output?

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

Test 5: Replace Substring

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:

Instagram >> @IELTS_Wordnik


Copy code
Hello, Universe!

Test 6: Escape Characters

Write code to display the following output exactly as shown:

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: \."

Test 7: Combining Strings

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

Test 8: Combining String Functions

What will the following code output?

python
Copy code

Instagram >> @IELTS_Wordnik


phrase = "Python Programming"
print(phrase.replace("Python", "Java").upper())
print(len(phrase.lower().replace("Programming", "Coding")))

Answer: Output:

Copy code
JAVA PROGRAMMING
20

Test 9: Challenge – Reverse a String

Write code to reverse the string "Python".

Answer:

python
Copy code
word = "Python"
print(word[::-1])

Output:

Copy code
nohtyP

Test 10: Debug the Code

Find and fix the error in the following code:

sentence = "Learning Python is fun!"


print(sentence.index("python"))
print(sentence[0].upper)

Answer: Errors:

1. "python" should be "Python" because .index() is case-sensitive.


2. sentence[0].upper is missing parentheses to call the .upper() function.

Corrected code:

sentence = "Learning Python is fun!"


print(sentence.index("Python"))
print(sentence[0].upper())

Output:

Instagram >> @IELTS_Wordnik


Test 11: Create a Dynamic String

Write code to create a personalized greeting where a user can input their name.

Answer:

name = input("Enter your name: ")


print("Hello, " + name + "! Welcome to Python.")

Example input and output:

mathematica
Copy code
Enter your name: Alice
Hello, Alice! Welcome to Python.

Test 12: Multiline String

Write a multiline string to display the following text:

Python is fun.
Learn it.
Love it.

Answer:

multiline_text = """Python is fun.


Learn it.
Love it."""
print(multiline_text)

Output:

Python is fun.
Learn it.
Love it.

Key Takeaways

 Strings are versatile and essential in Python.

Instagram >> @IELTS_Wordnik


 Use functions like lower(), upper(), replace(), and index() to manipulate them.
 Practice using variables and operations like concatenation to get comfortable.

⌨️…………………………………………………………………………………Working with Numbers

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

 Printing a number is as simple as using the print() function:

print(2) # Prints: 2
print(2.0987) # Prints: 2.0987
print(-5) # Prints: -5

2. Basic Arithmetic Operations

Python supports basic math operations:

 Addition, Subtraction, Multiplication, Division:

print(3 + 4.5) # Prints: 7.5


print(8 - 2) # Prints: 6
print(5 * 2) # Prints: 10
print(10 / 2) # Prints: 5.0

 Order of Operations (Parentheses):

print(3 * 4 + 5) # Prints: 17
print(3 * (4 + 5)) # Prints: 27

 Modulus (Remainder):

print(10 % 3) # Prints: 1 (remainder of 10 ÷ 3)

3. Variables to Store Numbers

You can store numbers in variables and use them later:

Instagram >> @IELTS_Wordnik


my_num = 5
print(my_num) # Prints: 5

4. Converting Numbers to Strings

If you want to combine numbers with text, convert the number to a string using str():

print("My favorite number is " + str(my_num)) # Prints: My favorite number is


5

5. Common Functions

Python provides useful functions to work with numbers:

 Absolute Value: abs()

print(abs(-5)) # Prints: 5

 Power Function: pow(base, exponent)

print(pow(3, 2)) # Prints: 9 (3^2)

 Max and Min Values:

print(max(4, 6)) # Prints: 6


print(min(4, 6)) # Prints: 4

 Rounding Numbers:

print(round(3.7)) # Prints: 4
print(round(3.2)) # Prints: 3

6. Advanced Math Functions (Using the math Module)

To access more complex math functions, import the math module:

from math import *

Here are some additional functions you can use:

Instagram >> @IELTS_Wordnik


 Floor and Ceiling:

print(floor(3.7)) # Prints: 3 (rounds down)


print(ceil(3.7)) # Prints: 4 (rounds up)

 Square Root:

print(sqrt(36)) # Prints: 6.0

7. Exploring More Math Functions

The math module contains many more functions. You can explore these by searching for
"Python math functions" online.

Key Python Code Examples:


# Printing Numbers
print(5)
print(-3.14)

# 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))

# Using Math Module


from math import *
print(floor(3.9))
print(ceil(3.2))
print(sqrt(49))

With these basics, you can perform many mathematical operations and build programs that
handle numbers effectively.

Instagram >> @IELTS_Wordnik


⌨️………………………………………………………………………………Getting Input from Users

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.

1. Basic User Input

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:

 The program shows the prompt: Enter your name:.


 The user types their name, e.g., Mike.
 The program prints: Hello, Mike!.

2. Getting Multiple Inputs

You can prompt the user for more than one piece of information by repeating the input()
function. For example:

name = input("Enter your name: ") # Stores the name


age = input("Enter your age: ") # Stores the age
print("Hello, " + name + ", you are " + age + " years old!") # Combines and
prints the input

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!

Instagram >> @IELTS_Wordnik


3. Example Program

Here’s the complete code for getting two inputs and responding:

# Ask the user for their name


name = input("Enter your name: ")

# Ask the user for their age


age = input("Enter your age: ")

# Print a personalized message


print("Hello, " + name + ", you are " + age + " years old!")

How to Run the Program

1. When the program runs, it will display:

mathematica

Enter your name:

2. The user types a name (e.g., John) and presses Enter.


3. Then it displays:

mathematica

Enter your age:

4. The user types their age (e.g., 25) and presses Enter.
5. The program responds with:

sql

Hello, John, you are 25 years old!

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.

Full Example Code


# Get user's name
name = input("Enter your name: ")

Instagram >> @IELTS_Wordnik


# Get user's age
age = input("Enter your age: ")

# Respond with a personalized message


print("Hello, " + name + ", you are " + age + " years old!")

This is just the beginning! Inputs can be used to create more complex and interactive programs
as you continue learning Python.

⌨️………………………………………………………………………………………………………………Building a Basic Calculator

Building a Basic Calculator in 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.

1. The Basic Plan

1. Ask the user for two numbers.


2. Add the numbers together.
3. Print the result.

2. Getting User Input

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:

# Get the first number from the user


num1 = input("Enter the first number: ")

# Get the second number from the user


num2 = input("Enter the second number: ")

# 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.

Instagram >> @IELTS_Wordnik


3. Converting Strings to Numbers

To treat the inputs as numbers, we use conversion functions:

 int() for whole numbers (e.g., 1, 2, 3).


 float() for decimal numbers (e.g., 1.5, 2.75).

Here’s the updated code:

# Get the first number and convert to a float


num1 = float(input("Enter the first number: "))

# Get the second number and convert to a float


num2 = float(input("Enter the second number: "))

# Add the numbers and store the result


result = num1 + num2

# Print the result


print("The result is:", result)

4. How It Works

1. The program prompts the user to enter two numbers.


2. The float() function converts the string input into a decimal number.
3. The program adds the numbers and prints the result.

5. Example Runs

Run 1 (Adding Whole Numbers):

plaintext
Copy code
Enter the first number: 4
Enter the second number: 5
The result is: 9.0

Run 2 (Adding Decimal Numbers):

plaintext
Copy code
Enter the first number: 4.3
Enter the second number: 5.5
The result is: 9.8

Instagram >> @IELTS_Wordnik


Key Points

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.

Full Calculator Code


# Get the first number and convert to a float
num1 = float(input("Enter the first number: "))

# Get the second number and convert to a float


num2 = float(input("Enter the second number: "))

# Add the numbers and store the result


result = num1 + num2

# Print the result


print("The result is:", result)

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!

⌨️…………………………………………………………………………………………………………………….Mad Libs Game

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.

Steps to Build the Madlibs Game

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.

Instagram >> @IELTS_Wordnik


Code Walkthrough

Here’s how you can create the Madlibs game:

# Prompt the user to enter a color


color = input("Enter a color: ")

# Prompt the user to enter a plural noun


plural_noun = input("Enter a plural noun: ")

# Prompt the user to enter a celebrity name


celebrity = input("Enter a celebrity: ")

# Create the Madlibs story using the user inputs


madlib = f"Roses are {color}, {plural_noun} are blue, I love {celebrity}."

# Print the customized story


print(madlib)

How the Code Works

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.

Instagram >> @IELTS_Wordnik


How to Expand This Game

 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}!"

# Print the result


print(madlib)

⌨️--------------------------------------------------------------------------------------------------------------------------------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.

Key Features of Lists

 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).

 Modifiable: List elements can be updated or changed.

Code Walkthrough

Instagram >> @IELTS_Wordnik


1. Creating a List

To create a list, use square brackets [] to store multiple values:

# Create a list of friends

friends = ["Kevin", "Karen", "Jim"]

Here, friends contains three strings: "Kevin", "Karen", and "Jim".

2. Accessing Elements in a List

You can access specific items in the list using their index:

 Positive Indexing: Start counting from 0 for the first item.

 Negative Indexing: Start counting backward from -1 for the last item.

python

print(friends) # Output: ['Kevin', 'Karen', 'Jim']

# Access elements using positive indexes

print(friends[0]) # Output: Kevin (1st element)

print(friends[2]) # Output: Jim (3rd element)

# Access elements using negative indexes

print(friends[-1]) # Output: Jim (last element)

print(friends[-2]) # Output: Karen (2nd last element)

3. Slicing a List

You can extract a portion of a list using slicing with a colon ::

 list[start:end] grabs elements from start up to (but not including) end.

 list[start:] grabs all elements from start to the end.

python

Instagram >> @IELTS_Wordnik


# Add more elements for slicing demonstration

friends = ["Kevin", "Karen", "Jim", "Oscar", "Pam"]

# Slicing examples

print(friends[1:4]) # Output: ['Karen', 'Jim', 'Oscar']

print(friends[2:]) # Output: ['Jim', 'Oscar', 'Pam']

4. Modifying Elements

You can update an element in a list by referring to its index:

# Modify an element

friends[1] = "Mike"

print(friends) # Output: ['Kevin', 'Mike', 'Jim', 'Oscar', 'Pam']

Summary of Python Code

Here’s a complete example combining everything:

# Create a list

friends = ["Kevin", "Karen", "Jim"]

# Accessing elements

print(friends[0]) # Output: Kevin

print(friends[-1]) # Output: Jim

# Slicing the list

friends = ["Kevin", "Karen", "Jim", "Oscar", "Pam"]

print(friends[1:4]) # Output: ['Karen', 'Jim', 'Oscar']

# Modifying an element

Instagram >> @IELTS_Wordnik


friends[1] = "Mike"

print(friends) # Output: ['Kevin', 'Mike', 'Jim', 'Oscar', 'Pam']

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:

Examples of Python List Functions


# Example Lists
lucky_numbers = [4, 8, 15, 16, 23, 42]
friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"]

# 1. Print the list


print(friends) # Output: ['Kevin', 'Karen', 'Jim', 'Oscar', 'Toby']

# 2. Extend: Combine two lists


friends.extend(lucky_numbers)
print(friends) # Combines friends and lucky_numbers into one list

# 3. Append: Add a single item at the end


friends.append("Creed")
print(friends) # Adds "Creed" to the end

# 4. Insert: Add an item at a specific index


friends.insert(1, "Kelly")

Instagram >> @IELTS_Wordnik


print(friends) # Adds "Kelly" at index 1

# 5. Remove: Delete a specific item


friends.remove("Jim")
print(friends) # Removes "Jim" from the list

# 6. Clear: Remove all items from the list


friends.clear()
print(friends) # Outputs an empty list

# 7. Pop: Remove the last item


friends = ["Kevin", "Karen", "Jim", "Oscar"]
friends.pop()
print(friends) # Removes "Oscar"

# 8. Index: Find the position of an item


index = friends.index("Kevin")
print(index) # Output: 0 (Kevin is at index 0)

# 9. Count: Count how many times an item appears


friends.append("Jim")
count = friends.count("Jim")
print(count) # Output: 2 (Jim appears twice)

# 10. Sort: Arrange the list in ascending/alphabetical order


friends.sort()
print(friends) # Outputs the list in alphabetical order

lucky_numbers.sort()
print(lucky_numbers) # Outputs numbers in ascending order

# 11. Reverse: Reverse the order of the list


lucky_numbers.reverse()
print(lucky_numbers) # Outputs the reversed order of lucky_numbers

# 12. Copy: Create a duplicate of a list


friends_copy = friends.copy()
print(friends_copy) # Outputs a copy of the "friends" list

Overview of Key Concepts:

1. Extend combines two lists.


2. Append adds a single item to the end.
3. Insert adds an item at a specific position.
4. Remove deletes a specified item.
5. Clear empties the list entirely.
6. Pop removes the last item.
7. Index finds the position of an item.
8. Count counts how many times an item appears.
9. Sort orders the list alphabetically or numerically.
10. Reverse reverses the order of the list.
11. Copy duplicates the list.

Instagram >> @IELTS_Wordnik


These basic functions help you work efficiently with lists in Python. The more you practice, the
more comfortable you'll become.

⌨️------------------------------------------------------------------------------------------------------------------------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.

What Are Tuples?

 Tuples are created using parentheses () (unlike lists, which use square brackets []).
 Tuples are used when you want data that should not be changed.

How to Create and Use Tuples

Here’s an example of creating and accessing elements in a tuple:

# Creating a tuple
coordinates = (4, 5) # A tuple with two elements

# Accessing elements using index


print(coordinates[0]) # Output: 4
print(coordinates[1]) # Output: 5

# Trying to modify an element (this will cause an error)


# coordinates[1] = 10 # Uncommenting this line will cause a TypeError

Key Differences Between Tuples and Lists

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).

Instagram >> @IELTS_Wordnik


2. Lists:
o Mutable: Can change, add, or remove elements.
o Syntax: Use square brackets [] to define.
o Use case: Store data that needs to be modified.

Example: Tuples vs. Lists


# A tuple
coordinates = (4, 5)

# A list
mutable_coordinates = [4, 5]

# Modifying a list
mutable_coordinates[1] = 10 # This works for a list
print(mutable_coordinates) # Output: [4, 10]

# Modifying a tuple (causes an error)


# coordinates[1] = 10 # This will raise a TypeError

Practical Use Case: Tuples in a List

Tuples are often used inside lists when you want to store immutable data within a mutable
structure. For example:

# A list of tuples (e.g., coordinates)


coordinates_list = [(4, 5), (6, 7), (8, 34)]

# Accessing a tuple in the list


print(coordinates_list[0]) # Output: (4, 5)

# Accessing an element within a tuple


print(coordinates_list[0][1]) # Output: 5

# Modifying the list (allowed)


coordinates_list.append((10, 12))
print(coordinates_list) # Output: [(4, 5), (6, 7), (8, 34), (10, 12)]

# Modifying a tuple directly (not allowed)


# coordinates_list[0][0] = 100 # Raises a TypeError

Why Use Tuples?

 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.

Instagram >> @IELTS_Wordnik


Summary

 Tuples are immutable, and their content cannot change.


 They are created with (), while lists use [].
 Tuples are ideal for data that must remain unchanged.
 Lists are flexible and more commonly used for general-purpose data storage.

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.

How to Create and Use a Function

1. Define a function using the def keyword.


2. Give the function a name.
3. Write the code inside the function, indented under its definition.

Here’s an example:

# Defining a function
def say_hi():
print("Hello, User!") # This line is indented and part of the function

# Calling the function


say_hi() # Output: Hello, User!

Key Points About Functions

 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.

Instagram >> @IELTS_Wordnik


Adding Parameters to a Function

Parameters allow you to pass information to a function, making it more flexible. For example:

# Function with one parameter


def say_hi(name):
print(f"Hello, {name}!")

# Calling the function with different names


say_hi("Mike") # Output: Hello, Mike!
say_hi("Steve") # Output: Hello, Steve!

In this example:

 name is a parameter, which the function uses to customize its behavior.


 You provide the parameter's value (e.g., "Mike") when calling the function.

Using Multiple Parameters

You can define functions with multiple parameters to handle more data:

# Function with two parameters


def say_hi(name, age):
print(f"Hello, {name}! You are {age} years old.")

# Calling the function with different inputs


say_hi("Mike", 35) # Output: Hello, Mike! You are 35 years old.
say_hi("Steve", 70) # Output: Hello, Steve! You are 70 years old.

Here:

 The function takes name and age as parameters.


 You can pass any data type (strings, numbers, etc.) as arguments.

Flow of Execution

Functions are executed in the order they are called:

print("Top")
say_hi("Alice", 25)
print("Bottom")

Output:

Instagram >> @IELTS_Wordnik


Top
Hello, Alice! You are 25 years old.
Bottom

Explanation:

1. Python executes the print("Top") statement first.


2. Then it jumps to the say_hi function, executes it, and returns.
3. Finally, it executes the print("Bottom").

Using Functions to Simplify Repetitive Code

Instead of writing similar code multiple times, use functions to centralize the logic:

def greet_person(name, age):


print(f"Hello, {name}! You are {age}.")

# Reusing the same function with different data


greet_person("Emma", 28)
greet_person("John", 40)

Passing Data of Different Types

Functions can handle various types of data (strings, integers, etc.):

def describe_person(name, age):


print(f"{name} is {str(age)} years old.")

describe_person("Anna", 30) # Output: Anna is 30 years old.

Key Benefits of Functions

 Reusability: Write once, use many times.


 Organization: Group related tasks into separate blocks.
 Flexibility: Use parameters to make functions adaptable.

General Naming Guidelines

 Function names should be descriptive and in lowercase.


 Use underscores _ to separate words for clarity (e.g., say_hi, calculate_sum).

Instagram >> @IELTS_Wordnik


Summary

1. Use def to define a function.


2. Indent the code inside the function.
3. Use parameters to make the function flexible.
4. Call the function to execute its code.

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.

Why Use return?

 Normally, a function runs its code and stops.


 With return, the function can send back a result to the caller.
 This is useful when you need to use the result of a function in other parts of your program.

Basic Example: Cubing a Number

Let’s create a function that cubes a number (raises it to the power of 3) and returns the result.

# Function to cube a number


def cube(num):
return num * num * num # Return the cube of the number

# Call the function and print the result


print(cube(3)) # Output: 27

Here:

1. The cube function takes a parameter num.


2. It calculates num * num * num.
3. The return statement sends this result back to the caller.

Instagram >> @IELTS_Wordnik


Storing Returned Values

You can store the result of a function in a variable for later use:

# Store the returned value


result = cube(4)
print(result) # Output: 64

 The cube function is called with 4.


 The result (4 * 4 * 4 = 64) is stored in the variable result.
 Printing result outputs 64.

Important Points About return

1. Function Stops After return:


o Any code written after return inside a function will not execute.

def example_function():
return "Done"
print("This will not run!") # This line is ignored

print(example_function()) # Output: Done

2. return Can Send Back Any Data Type:


o Strings, numbers, lists, dictionaries, etc.

def return_string():
return "Hello, World!"

def return_boolean():
return True

print(return_string()) # Output: Hello, World!


print(return_boolean()) # Output: True

Flow of a Function With return

When you call a function that uses return:

1. Python executes the function code.


2. When it encounters return, it sends the result back to the caller and exits the function.

def calculate_square(num):
return num * num

Instagram >> @IELTS_Wordnik


# Call the function
print(calculate_square(5)) # Output: 25

Using Parameters and return Together

Parameters let you provide input to a function, and return lets you get output back.

def multiply(a, b):


return a * b

result = multiply(6, 7)
print(result) # Output: 42

 The function multiply takes two parameters, a and b.


 It calculates their product and returns it.
 The result is stored in result and printed.

What Happens If You Don’t Use return?

If a function does not have a return statement, it returns None by default.

python
Copy code
def no_return():
print("No return here!")

print(no_return()) # Output: No return here! None

Here:

 The no_return function prints a message but does not use return.
 When you print the result of no_return, it outputs None.

Key Benefits of return

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.

Complete Example: Using return

Here’s a complete example that shows how return works:

Instagram >> @IELTS_Wordnik


# Function to calculate the area of a rectangle
def calculate_area(length, width):
return length * width

# Store the result


area = calculate_area(10, 5)

# Use the result


print(f"The area of the rectangle is {area}.") # Output: The area of the
rectangle is 50.

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:

 If you’re hungry, eat breakfast.


o If the condition (hungry) is true → eat breakfast.
o If not → skip it.

Python's if statements work similarly. Let’s break it down with actual code examples.

Basic Syntax of if Statements in Python:

1. Create a Condition: Write an if statement that checks if something is true or false.


2. Run Code if True: Execute the indented block of code only if the condition is true.

Example:

is_male = True # Boolean variable


if is_male:

Instagram >> @IELTS_Wordnik


print("You are a male.") # Runs if is_male is True

 Output:
o If is_male = True, prints: "You are a male."
o If is_male = False, nothing happens.

Adding else: The "Otherwise" Condition

To handle cases where the if condition is false, use else.

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."

Using Logical Operators (and, or): Combine Conditions

You can check multiple conditions with and (both must be true) or or (one must be true).

Example:

is_male = True
is_tall = True

if is_male and is_tall:


print("You are a tall male.") # Both must be True
elif is_male and not is_tall:
print("You are a short male.") # Male but not tall
elif not is_male and is_tall:
print("You are not a male but are tall.") # Tall but not male
else:
print("You are neither male nor tall.") # All conditions False

 Outputs based on variable values:


o is_male = True, is_tall = True: "You are a tall male."
o is_male = True, is_tall = False: "You are a short male."
o is_male = False, is_tall = True: "You are not a male but are tall."
o is_male = False, is_tall = False: "You are neither male nor tall."

Instagram >> @IELTS_Wordnik


Adding elif: Check Additional Conditions

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.

Full Example: Covering All Conditions

Here’s an extended example:

python
Copy code
is_male = True
is_tall = False

if is_male and is_tall:


print("You are a tall male.")
elif is_male and not is_tall:
print("You are a short male.")
elif not is_male and is_tall:
print("You are not a male but are tall.")
else:
print("You are not a male and not tall.")

Future Steps: Using Comparisons

In future examples, you can:

 Compare numbers (age > 18) or strings (name == "Alice").


 Use those comparisons in if conditions.

Instagram >> @IELTS_Wordnik


This is just the basics of if statements and how they help programs make decisions!

⌨️………………………………………………………………………………………………………….If Statements & Comparisons

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.

# Define the function to find the maximum of three numbers


def max_num(num1, num2, num3):
# Check if num1 is the largest
if num1 >= num2 and num1 >= num3:
return num1
# Check if num2 is the largest
elif num2 >= num1 and num2 >= num3:
return num2
# If neither num1 nor num2 is the largest, num3 must be the largest
else:
return num3

# Test the function


print(max_num(3, 4, 5)) # Outputs: 5
print(max_num(10, 140, 30)) # Outputs: 140
print(max_num(300, 50, 10)) # Outputs: 300

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.

Comparison Operators in Python

 == (equal to): Checks if two values are the same.


 != (not equal to): Checks if two values are different.
 > (greater than): Checks if the first value is larger than the second.

Instagram >> @IELTS_Wordnik


 < (less than): Checks if the first value is smaller than the second.
 >= (greater than or equal to): Checks if the first value is larger or equal to the second.
 <= (less than or equal to): Checks if the first value is smaller or equal to the second.

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.

------------------------------------------------------------------------⌨️Building a Better Calculator

Here’s a simplified and paraphrased explanation along with the Python code for creating a
calculator that performs basic arithmetic operations:

This program builds a simple calculator that:

1. Accepts two numbers and an operator (+, -, *, or /) from the user.


2. Performs the specified operation and displays the result.
3. Validates the input operator to ensure it's valid and handles invalid operators.

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

# Perform the operation based on the operator


if op == "+": # Addition
print(f"Result: {num1 + num2}")
elif op == "-": # Subtraction
print(f"Result: {num1 - num2}")
elif op == "*": # Multiplication
print(f"Result: {num1 * num2}")
elif op == "/": # Division
if num2 != 0: # Avoid division by zero
print(f"Result: {num1 / num2}")
else:

Instagram >> @IELTS_Wordnik


print("Error: Cannot divide by zero.")
else: # Invalid operator
print("Error: Invalid operator.")

Explanation of the Code

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

Enter first number: 5


Enter operator (+, -, *, /): +
Enter second number: 3
Result: 8.0
Example 2: Division by Zero

Enter first number: 5


Enter operator (+, -, *, /): /
Enter second number: 0
Error: Cannot divide by zero.
Example 3: Invalid Operator

Enter first number: 5


Enter operator (+, -, *, /): %
Enter second number: 3
Error: Invalid operator.

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.

Instagram >> @IELTS_Wordnik


3. User-Friendly: Prints clear messages for valid results and errors.

This program demonstrates the practical use of if statements to build interactive and useful
applications in Python.

------------------------------------------------------------------------------------------
⌨️Dictionaries

What Are Dictionaries?

A dictionary in Python is a data structure that stores information as key-value pairs.

 A key acts as a unique identifier (e.g., "JAN").


 A value is the information associated with that key (e.g., "January").

Think of it like a real dictionary where words (keys) are linked to definitions (values).

Task: Convert Abbreviated Month Names to Full Month Names

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"
}

Instagram >> @IELTS_Wordnik


# Access values using keys
print(month_conversions["NOV"]) # Outputs: November
print(month_conversions["MAR"]) # Outputs: March

# Access values using the `get()` method


print(month_conversions.get("DEC")) # Outputs: December

# Handling invalid keys with a default value


print(month_conversions.get("LUV", "Not a valid key")) # Outputs: Not a valid
key

Explanation of the Code

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.

3. Default Values with .get():


o If a key doesn’t exist, .get() returns None by default.
o You can specify a custom message for invalid keys, e.g., "Not a valid key".

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()

Not a valid key

Notes on Flexibility

Dictionaries are versatile:

Instagram >> @IELTS_Wordnik


 Keys can be numbers:

num_dict = {1: "One", 2: "Two"}


print(num_dict[1]) # Outputs: One

 Useful for organizing and retrieving data efficiently.

This tutorial demonstrates the basics of creating, accessing, and using dictionaries effectively in
Python.

-------------------------------------------------------------------------------------------------------------------Loops in Python

What Is a While Loop?

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.

Python Code Example: Counting Numbers

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

# Define a while loop


while i <= 10: # Loop as long as i is less than or equal to 10
print(i) # Print the current value of i
i += 1 # Increment i by 1 (same as i = i + 1)

# Code after the loop


print("Done with loop") # This runs after the loop finishes

How It Works

1. Initialize a Variable:
o We start by defining i = 1.

2. While Loop Condition:

Instagram >> @IELTS_Wordnik


o The loop runs as long as i <= 10 is true.

3. Code Inside the Loop:


o First, print(i) displays the value of i.
o Then, i += 1 increases i by 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

Key Points to Remember

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:

Instagram >> @IELTS_Wordnik


o i = 2, 2 <= 10 → True → Print 2, then i = 3.
3. ...
4. Last Iteration:
o i = 10, 10 <= 10 → True → Print 10, then i = 11.
5. Loop Ends:
o i = 11, 11 <= 10 → False → Exit the loop, print "Done with loop".

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.

Building a Guessing Game

Objective of the Game

 The program has a secret word (e.g., "draft").


 The user tries to guess the secret word.
 The game continues until:
1. The user guesses the secret word, or
2. The user runs out of a set number of allowed guesses.

Basic Version of the Guessing Game

Here’s the code for the simplest version, where the user guesses until they get it right:

# Secret word and initial guess


secret_word = "draft"
guess = "" # Empty string to store user's guess

# Loop until the guess matches the secret word


while guess != secret_word:
guess = input("Enter your guess: ")

print("You win!") # Success message

Instagram >> @IELTS_Wordnik


How it Works:

1. The secret word is stored in the variable secret_word.


2. The program keeps asking for guesses using a while loop.
3. The loop ends when the user enters the correct word.
4. After exiting the loop, the program prints "You win!".

Improved Version with Guess Limit

To make the game more challenging:

 Users get only a limited number of guesses (e.g., 3 guesses).


 If they fail to guess correctly within the limit, they lose.

Here’s the code:

# Secret word and variables


secret_word = "draft"
guess = "" # Stores the user's guess
guess_count = 0 # Keeps track of the number of guesses
guess_limit = 3 # Maximum number of guesses
out_of_guesses = False # Tracks if the user has used all guesses

# Loop until the user guesses correctly or runs out of guesses


while guess != secret_word and not out_of_guesses:
if guess_count < guess_limit: # Check if guesses remain
guess = input("Enter your guess: ") # Prompt the user
guess_count += 1 # Increment the guess count
else:
out_of_guesses = True # No more guesses allowed

# Determine win/lose outcome


if out_of_guesses:
print("Out of guesses! You lose.") # Failure message
else:
print("You win!") # Success message

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.

Instagram >> @IELTS_Wordnik


4. Game Outcome:
o After the loop, check out_of_guesses:
 If True, print "Out of guesses! You lose.".
 If False, print "You win!".

Example Game Run


Scenario 1: User Wins
plaintext
Copy code
Enter your guess: apple
Enter your guess: tree
Enter your guess: draft
You win!
Scenario 2: User Loses
plaintext
Copy code
Enter your guess: apple
Enter your guess: tree
Enter your guess: sky
Out of guesses! You lose.

Key Concepts Used

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:

 Feedback for wrong guesses (e.g., "Try again!").


 Case-insensitive matching (e.g., "Draft" == "draft").
 More features like hints or difficulty levels.

This is a fun way to practice basic programming concepts!

Instagram >> @IELTS_Wordnik


-------------------------------------------------------------------------------------------⌨️For
Loops

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:

1. Looping Through a String

The for loop can iterate over each letter in a string.

for letter in "Draft Academy":


print(letter)

What Happens?

 Each letter in the string "Draft Academy" is printed, one by one.


 Output:

D
r
a
f
t

A
c
a
d
e
m
y

2. Looping Through a List

You can loop through the items in a list (array).

friends = ["Jim", "Karen", "Kevin"]

Instagram >> @IELTS_Wordnik


for friend in friends:
print(friend)

What Happens?

 Each name in the list friends is printed.


 Output:

Jim
Karen
Kevin

3. Looping Through a Range of Numbers

Use range() to loop through numbers.

for index in range(5):


print(index)

What Happens?

 Prints numbers from 0 to 4 (but not 5).


 Output:

0
1
2
3
4

4. Custom Ranges

You can specify a start and end for the range.

for index in range(3, 10):


print(index)

What Happens?

 Prints numbers from 3 to 9 (but not 10).


 Output:

3
4

Instagram >> @IELTS_Wordnik


5
6
7
8
9

5. Using a Range with a List

Use range(len(list)) to loop through a list by index.

friends = ["Jim", "Karen", "Kevin"]


for index in range(len(friends)):
print(friends[index])

What Happens?

 Prints each name in the friends list, one by one, using its index.
 Output:

Jim
Karen
Kevin

6. Adding Conditions Inside a Loop

You can include logic in a for loop, like checking if it’s the first iteration.

for index in range(5):


if index == 0:
print("First iteration")
else:
print("Not 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

Instagram >> @IELTS_Wordnik


Summary

 Strings: Loop through each character.


 Lists: Loop through each item.
 Ranges: Loop through a sequence of numbers.
 Logic: Add conditions to customize what happens during iterations.

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.

Using Python's Built-in Exponentiation

print(2 ** 3) # Outputs: 8 (2 raised to the power of 3)


Custom Exponent Function

We'll create a function called raise_to_power that uses a for loop to calculate the result.

1. Define the function:


o Accept two inputs: base_num (the base) and power_num (the power).
o Initialize a variable result to 1.

2. Use a for loop:


o Loop power_num times, multiplying result by base_num in each iteration.

3. Return the result:


o After the loop finishes, return result.

def raise_to_power(base_num, power_num):


result = 1
for _ in range(power_num): # Loop 'power_num' times
result *= base_num
return result
Using the Function

Call the function with different inputs:

Instagram >> @IELTS_Wordnik


print(raise_to_power(3, 2)) # Outputs: 9 (3^2)
print(raise_to_power(3, 4)) # Outputs: 81 (3^4)
print(raise_to_power(2, 3)) # Outputs: 8 (2^3)

Two-Dimensional Lists and Nested Loops


What is a Two-Dimensional List?

A two-dimensional list is a list where each element is another list. It can represent a grid or table
structure.

Creating a Two-Dimensional List

Here’s a grid with 4 rows and 3 columns:

number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
Accessing Elements

To access a specific element:

 Use the row index and column index.

Example:

print(number_grid[0][0]) # Outputs: 1 (Row 0, Column 0)


print(number_grid[2][1]) # Outputs: 8 (Row 2, Column 1)
Nested for Loops

-------------------------------------------------------------------------------------2D Lists & Nested Loops

A nested loop is a loop inside another loop. You can use it to go through all elements in a two-
dimensional list.

1. Loop through each row.


2. Inside the row loop, loop through each column (element in the row).

for row in number_grid: # Loop through each row


for column in row: # Loop through each element in the row

Instagram >> @IELTS_Wordnik


print(column)
Output:

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:

Steps to Create the Translator


1. Define the Translate Function

The function will:

 Take a phrase as input.


 Loop through each letter in the phrase.
 Replace vowels with "G" and keep other letters unchanged.

def translate(phrase):

Instagram >> @IELTS_Wordnik


translation = "" # Initialize an empty string to store the result
for letter in phrase:
# Check if the letter is a vowel
if letter.lower() in "aeiou": # Convert letter to lowercase for
comparison
# Check if the letter is uppercase to maintain case
if letter.isupper():
translation += "G" # Add uppercase G for uppercase vowels
else:
translation += "g" # Add lowercase g for lowercase vowels
else:
translation += letter # Add non-vowel letters unchanged
return translation # Return the translated phrase

2. Allow User Input and Call the Function

We’ll let the user input a phrase, call the translate function, and print the result.

# Prompt the user to enter a phrase


print(translate(input("Enter a phrase: ")))

Explanation of the Code

1. Initialize the Result:


o Start with an empty string translation.

2. Loop Through Each Letter:


o Use a for loop to examine each letter in the phrase.
o Use .lower() to check for vowels in a case-insensitive way.

3. Check Uppercase Vowels:


o Use letter.isupper() to determine if the original letter is uppercase.
o Replace uppercase vowels with uppercase "G" and lowercase vowels with lowercase
"g".

4. Add Non-Vowel Letters Unchanged:


o If the letter isn’t a vowel, add it directly to translation.

5. Return and Print the Result:


o After processing all letters, return the final translated phrase.

Example Runs

Input 1:

plaintext

Instagram >> @IELTS_Wordnik


Copy code
Enter a phrase: dog

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

Input 3 (Preserves Case):

plaintext
Copy code
Enter a phrase: On

Output:

plaintext
Copy code
Gn

Improvements and Notes

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!

Instagram >> @IELTS_Wordnik


-----------------------------------------------------------------------------------------------------------------------⌨️
Comments

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.

Types of Comments in Python


1. Single-Line Comments

 Start with a # symbol.


 Anything after the # on that line is treated as a comment.

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

 Use multiple # symbols, one per line, to write multi-line comments.

Example:

python
Copy code
# This program prints a message.
# It demonstrates how comments work.
print("Hello, World!")

 Python style guides recommend using multiple # for multi-line comments.

3. Alternative Multi-Line Comments

 You can use triple quotes (''' or """) for multi-line comments.

Instagram >> @IELTS_Wordnik


Example:

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

 Add clarity to complex or important sections of your 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.

3. Commenting Out Code

 Temporarily disable a line or block of code without deleting it.

Example:

python
Copy code
# print("This line is commented out and won't run.")
print("This line will run.")

 Useful for debugging or testing changes in your program.

Key Points About Comments

1. Ignored by Python:

Instagram >> @IELTS_Wordnik


o Comments don’t affect the program's execution.

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.

Example Program with Comments


python
Copy code
# This program demonstrates different types of comments.

# Print a message
print("Comments are fun!")

# Commenting out a line of code


# print("This line is disabled and won't execute.")

'''
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!

Instagram >> @IELTS_Wordnik


------------------------------------------------------------------------------------------⌨️Try /
Except

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:

1. Asking the user to input a number but receiving text instead.


2. Dividing a number by zero.

These errors will stop the program unless we handle them with try-except blocks.

Using Try-Except Blocks

A try-except block works like this:

1. Try: Python runs the code in this block.


2. Except: If an error happens, Python runs this block instead of crashing.

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

 If you enter 4, the program prints You entered: 4.


 If you enter hello, the program prints Invalid input.

Handling Specific Errors

You can handle different types of errors separately for better clarity.

Example:

Instagram >> @IELTS_Wordnik


try:
number = int(input("Enter a number: "))
result = 10 / number # Dividing 10 by the user's input
print(f"Result: {result}")
except ValueError:
print("Invalid input. Please enter a number.") # Handles non-numeric
inputs
except ZeroDivisionError:
print("Division by zero is not allowed.") # Handles division by zero

 Entering hello shows: Invalid input. Please enter a number.


 Entering 0 shows: Division by zero is not allowed.

Catching All Errors (Not Recommended)

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.

Printing the Error Message

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

This gives detailed information about what went wrong.

Instagram >> @IELTS_Wordnik


Full Example

Here’s a complete program showing how to handle multiple errors:

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

1. Catch Specific Errors:


o Avoid generic except: blocks unless necessary.
2. Explain Errors:
o Use clear messages to guide the user.
3. Test for Edge Cases:
o Handle errors like invalid inputs and division by zero separately.

Why Try-Except Blocks Matter

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:

Instagram >> @IELTS_Wordnik


1. Opening a File
Use the open() function to open a file. You need to provide the file name and the mode.
The modes are:
o 'r': Read (default mode; you can only view the content).
o 'w': Write (overwrites the file's content or creates a new file).
o 'a': Append (adds content to the end of the file without modifying existing data).
o 'r+': Read and write (lets you do both).

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 Code Examples

Here’s how you can perform these operations:

python
Copy code
# Opening a file in read mode
employee_file = open("employees.txt", "r")

# Checking if the file is readable


print("Is readable:", employee_file.readable()) # Outputs: True

# Reading the entire file


print("Full content:")
print(employee_file.read())

# Reading individual lines


employee_file.seek(0) # Reset cursor to the start of the file
print("First line:", employee_file.readline())
print("Second line:", employee_file.readline())

# Reading all lines into a list


employee_file.seek(0) # Reset cursor again
lines = employee_file.readlines()
print("All lines as a list:", lines)

# Accessing specific lines using index

Instagram >> @IELTS_Wordnik


print("Second line from the list:", lines[1])

# Iterating through lines with a loop


print("Iterating through lines:")
for line in lines:
print(line.strip()) # Strip removes extra whitespace/newlines

# Closing the file


employee_file.close()
Using with Statement (Recommended)

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:

1. Use open() with appropriate mode ('r', 'w', etc.).


2. Use .read(), .readline(), or .readlines() for reading content.
3. Always close the file, or use with for automatic closure.
4. Use loops for efficient processing of file content.

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

1. Opening Files for Writing/Appending


o Use the open() function with these modes:
 'w': Write mode. Overwrites the file's content or creates a new file if it doesn't
exist.
 'a': Append mode. Adds content to the end of the file without altering existing
data.

Instagram >> @IELTS_Wordnik


2. Writing to a File
o Use .write() to insert content into the file.
o Be cautious: 'w' overwrites the entire file, so all previous data is lost.

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.

4. Creating New Files


o If the specified file doesn’t exist, Python will create it in 'w' or 'a' mode.

5. Special Use Case: HTML or Other File Formats


o You can write files with different extensions like .txt, .csv, or .html, and Python will
save them accordingly.

6. Escape Characters
o Use \n for a new line.
o Escape characters let you format the content properly when appending or writing.

Python Code Examples


1. Appending Data to a File
# Open file in append mode
with open("employees.txt", "a") as employee_file:
# Add a new employee to the file
employee_file.write("\nKelly - Customer Service")

 Adds "Kelly - Customer Service" at the end of employees.txt on a new line.

2. Writing Data to a File


python
Copy code
# Open file in write mode
with open("employees.txt", "w") as employee_file:
# Overwrite the file with new content
employee_file.write("Kelly - Customer Service")

 Overwrites all content in employees.txt with "Kelly - Customer Service".

3. Creating a New File


python
Copy code
# Create and write to a new file
with open("new_employees.txt", "w") as new_file:
new_file.write("John - Manager\nEmily - Sales")

Instagram >> @IELTS_Wordnik


 Creates new_employees.txt (if it doesn't exist) and writes two lines.

4. Writing an HTML File


python
Copy code
# Create an HTML file and write basic HTML content
with open("index.html", "w") as html_file:
html_file.write("<!DOCTYPE html>\n")
html_file.write("<html>\n<head><title>My Page</title></head>\n")
html_file.write("<body>\n<p>This is a paragraph.</p>\n</body>\n</html>")

 Creates index.html and writes a simple web page structure.

5. Handling New Lines While Appending


python
Copy code
# Appending with a newline character
with open("employees.txt", "a") as employee_file:
# Add new entries on separate lines
employee_file.write("\nToby - Human Resources")
employee_file.write("\nAngela - Accounting")

 Ensures each entry is added on a new line.

Tips and Good Practices

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.

Applications of Writing/Appending Files

 Storing logs or records.


 Creating configuration files.
 Generating HTML, CSV, or other formatted documents programmatically.
 Maintaining and updating lists, such as employee data.

This functionality makes Python a powerful tool for file management and automation tasks.

Instagram >> @IELTS_Wordnik


⌨️Modules & Pip

What Are Python Modules?

 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.

Why Use Modules?

 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.

Example: Using a Custom Module

Imagine a file called useful_tools.py with the following content:

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:

# Importing the custom module


import useful_tools

# 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}")

Instagram >> @IELTS_Wordnik


dice_roll = useful_tools.roll_dice(6)
print(f"Rolled a dice: {dice_roll}")

Output might be:

Feet in a mile: 5280


Beatles: ['John', 'Paul', 'George', 'Ringo']
File extension: txt
Rolled a dice: 4

Built-in and External Modules

 Built-in Modules: Pre-installed with Python (e.g., math, random).


 External Modules: Created by other developers, not included by default. Install them with PIP.

Example: Built-in Module (math):

import math

print(math.sqrt(16)) # Output: 4.0


Example: Installing and Using an External Module:

1. Install a module (e.g., docx) with PIP:

bash
Copy code
pip install python-docx

2. Use the module:

import docx

doc = docx.Document()
doc.add_paragraph("Hello, world!")
doc.save("example.docx")

Where Are Modules Stored?

 Built-in Modules: Part of Python, no extra setup needed.


 Installed Modules: Saved in the site-packages folder within your Python installation
directory.

Instagram >> @IELTS_Wordnik


Managing Modules with PIP

 Install a module:

bash
Copy code
pip install module_name

 Check version of PIP:

bash
Copy code
pip --version

 Uninstall a module:

bash
Copy code
pip uninstall module_name

Key Tips for Using Modules

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 & Objects

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.

Instagram >> @IELTS_Wordnik


Why Use Classes and Objects?

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.

Example: Creating a Student Class

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.

Here's how you can implement this:

Step 1: Define the Class

Create a class that acts as a blueprint for a student.

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.

Step 2: Create Objects

Now, use this class in another Python file to create specific students.

# File: app.py
from student import Student

Instagram >> @IELTS_Wordnik


# Create two student objects
student1 = Student("Jim", "Business", 3.1, False)
student2 = Student("Pam", "Art", 2.5, True)

# Access and print their attributes


print(student1.name) # Output: Jim
print(student1.gpa) # Output: 3.1
print(student2.name) # Output: Pam
print(student2.is_on_probation) # Output: True

Here’s what happens:

1. Student("Jim", "Business", 3.1, False) creates an object with attributes:


o name = "Jim", major = "Business", gpa = 3.1, is_on_probation = False.
2. You can access these attributes using dot notation, e.g., student1.name.

Key Concepts Recap

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.

-----------------------------------------------------------------⌨️Building a Multiple Choice Quiz

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.

Instagram >> @IELTS_Wordnik


Steps to Create the Quiz

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)

2. Design a Question Class


A class allows us to group related data and functions. For each question, we need two
attributes:
o prompt (the question text)
o answer (the correct option)

3. Store Questions in an Array


Use the Question class to create question objects, then store them in a list.
4. Run the Quiz
Create a function to loop through the questions, get the user's answers, and check them
against the correct ones. Keep track of the score and display the results at the end.

Python Code

Here’s the complete code for the quiz:

python
Copy code
# Step 1: Create a Question class
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer

# Step 2: Define question prompts and answers


question_prompts = [
"What color are apples?\n(A) Red\n(B) Purple\n(C) Orange\n",
"What color are bananas?\n(A) Teal\n(B) Magenta\n(C) Yellow\n",
"What color are strawberries?\n(A) Yellow\n(B) Red\n(C) Blue\n"
]

# Step 3: Create an array of Question objects


questions = [
Question(question_prompts[0], "A"),
Question(question_prompts[1], "C"),
Question(question_prompts[2], "B")
]

# Step 4: Define a function to run the quiz


def run_test(questions):
score = 0

Instagram >> @IELTS_Wordnik


for question in questions:
answer = input(question.prompt).strip().upper()
if answer == question.answer:
score += 1
print(f"\nYou got {score} out of {len(questions)} correct!")

# Step 5: Run the quiz


run_test(questions)

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

What color are bananas?


(A) Teal
(B) Magenta
(C) Yellow
> B

What color are strawberries?


(A) Yellow
(B) Red
(C) Blue
> B

You got 2 out of 3 correct!

Instagram >> @IELTS_Wordnik


Key Takeaways

 Classes are useful for organizing data (e.g., Question objects).


 Loops and conditionals allow for interactive and flexible code.
 Input and output handling can make the program user-friendly.

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

Instagram >> @IELTS_Wordnik


Copy code
from chef import Chef

class ChineseChef(Chef):
def make_fried_rice(self):
print("The chef makes fried rice.")

# Overriding the make_special_dish method


def make_special_dish(self):
print("The chef makes orange chicken.")

app.py
python
Copy code
from chinese_chef import ChineseChef
from chef import Chef

# Create an object of Chef


generic_chef = Chef()
print("Generic Chef:")
generic_chef.make_chicken()
generic_chef.make_special_dish()

# Create an object of ChineseChef


chinese_chef = ChineseChef()
print("\nChinese Chef:")
chinese_chef.make_chicken() # Inherited from Chef
chinese_chef.make_special_dish() # Overridden in ChineseChef
chinese_chef.make_fried_rice() # Unique to ChineseChef

Output

When running app.py, the output will be:

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

1. Inheritance: Allows ChineseChef to reuse methods (make_chicken, make_salad) from


Chef without rewriting them.
2. Method Overriding: ChineseChef redefines make_special_dish to fit its purpose.

Instagram >> @IELTS_Wordnik


3. Extending Functionality: ChineseChef adds a new method (make_fried_rice), which is
specific to it.

Advantages of Using Inheritance

 Reusability: Avoid duplicating code by reusing parent class methods.


 Scalability: Easily extend functionality in subclasses.
 Clarity: Keeps the code organized and easier to maintain.

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.

Once inside the Python interpreter, you can:

 Execute basic Python commands.


 Define variables.
 Create functions.
 Use loops, if statements, and more.

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

Instagram >> @IELTS_Wordnik


print("Hello, world!")

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)

say_hi("Mike") # Output: Hello Mike

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.

Instagram >> @IELTS_Wordnik

You might also like