Python Module 1 Notes.docx - MODULE 1 NOTES
Python Module 1 Notes.docx - MODULE 1 NOTES
Syllabus: Python Basics: Entering Expressions into the Interactive Shell, The Integer, Floating-Point, and
String Data Types, String Concatenation and Replication, Storing Values in Variables, Your First Program,
Dissecting Your Program, Flow control: Boolean Values, Comparison Operators, Boolean Operators,Mixing
Boolean and Comparison Operators, Elements of Flow Control, Program Execution, Flow Control Statements,
Importing Modules,Ending a Program Early with sys.exit(), Functions: def Statements with Parameters, Return
Values and return Statements,The None Value, Keyword Arguments and print(), Local and Global Scope, The
global Statement, Exception Handling, A Short Program: Guess the Number
Textbook 1: Chapters 1 – 3
E
CHAPTER 1
C
1. DEFINITION : Python is a high-level, interpreted, and general-purpose programming language
N
that emphasizes simplicity and readability. It is designed to be easy to learn and use, making it an
JN
excellent choice for both beginners and experienced developers. Python supports multiple
programming paradigms, including procedural, object-oriented, and functional programming.
L,
Python is widely used in various fields such as web development, data analysis, artificial intelligence
(AI), machine learning (ML), scientific computing, automation, and more. Its extensive standard
IM
library and vast ecosystem of third-party packages make it a powerful and versatile tool for solving
diverse problems efficiently
,A
In simple terms, Python is a programming language that's like a set of instructions you give to a
M
computer to make it do something. Imagine teaching someone how to bake a cake step-by-step;
Python lets you give instructions to a computer in a similar way.
EE
Simple to Read and Write: Python uses plain English-like words, so it’s easier to understand, even
for beginners. For example: print("Hello, world!"). This simply tells the computer to display "Hello,
W
a. Build websites
b. Analyze data
LI
c. Create games
AA
Beginner-Friendly: Python takes care of many complicated details for you, so you can focus on
solving problems rather than getting stuck on complex coding rules.
Huge Community: If you ever get stuck, there are lots of tutorials, forums, and people who can help.
Python is like a friendly tool that helps you bring your ideas to life through a computer!
NOTE: Python was created by Guido van Rossum in 1991. He is often referred to as Python's
"Benevolent Dictator For Life" (BDFL) because he guided the development of Python for many
years.
The name "Python" was inspired by the British comedy series Monty Python's Flying Circus, not the
snake, reflecting van Rossum's preference for a fun and approachable language.
E
The interactive shell is a place where you can type Python code and immediately see the result. It’s
like a calculator but can do much more.
C
How to Open It?
N
JN
On Windows: Go to the Start menu, find the Python program group, and click IDLE (Python GUI).
L,
At the prompt >>>, you can type commands or math expressions. For example:
>>> 2 + 2
IM
,A
4
When you press Enter, Python calculates the result and shows 4.
M
EE
What is an Expression?
● An expression is a piece of code that Python can calculate and give back a value.
AS
If you type just a single value, like 2, Python will still recognize it as an expression. It simply
evaluates to itself:
>>> 2
Conclusion: In short: You can use the interactive shell to quickly do calculations or test Python code.
Expressions combine values and operators, and Python calculates their result for you!
There are plenty of other operators you can use in Python expressions, too. For example, Table 1-1
lists all the math operators in Python.
E
C
N
When doing math in Python, operators (like +, -, *, /) follow specific rules, just like in regular
JN
math. These rules are called the order of operations or precedence. Python uses the same rules as
you learned in school to decide what to calculate first.
L,
Order of Operations (Precedence)
2. Multiplication (*), Division (/), Floor Division (//), and Modulus (%) come next
EE
Examples: >>> 10 * 2 / 5
AS
Example: >>> 5 + 3 - 2
LI
6 # First, 5 + 3 = 8, then 8 - 2 = 6
AA
If you want to change the order Python calculates things, use parentheses. Python will always
calculate what’s inside parentheses first.
With parentheses
>>> (2 + 3) * 4
20 # First, 2 + 3 = 5, then 5 * 4 = 20
Without parentheses:
>>> 2 + 3 * 4
Python won’t be able to understand it and will display a SyntaxError error message, as shown
here:
E
C
N
JN
3. THE INTEGER, FLOATING-POINT, AND STRING DATA TYPES
L,
When you work with Python, you'll deal with values (numbers, text, etc.). Each value belongs to a
IM
specific category, which is called a data type
,A
What is a Data Type?
M
A data type defines the kind of value you’re working with. Every value in Python belongs to one
(and only one) data type.
EE
1. Integer (int)
W
Even though both 42 and 42.0 represent the same value, Python treats them differently because one
has a decimal point.
In Simple Terms
● A data type is like a label that tells Python, “Hey, this is a number” or “This is text.”
● Common data types:
○ int: Whole numbers (e.g., 5, -2).
○ float: Numbers with decimals (e.g., 3.14, 42.0).
○ str: Text (e.g., "hello", "123").
E
C
N
JN
4. STRING CONCATENATION AND REPLICATION
L,
1. The + Operator
○ For numbers: Adds them.
IM
Example: 2 + 3 → 5
,A
○ For strings: Combines (concatenates) them.
Example: 'Alice' + 'Bob' → 'AliceBob'
M
2. The * Operator
○ For numbers: Multiplies them.
W
Example: 2 * 3 → 6
○ For a string and a number: Repeat the string.
Example: 'Alice' * 5 → 'AliceAliceAliceAliceAlice'
YA
Key Points
What is a Variable?
A variable is like a labeled box in your computer’s memory where you can store a value.
spam = 42
Example:
spam = 40
eggs = 2
print(spam + eggs) # Output: 42
E
Updating Variables (Overwriting)
C
You can change the value of a variable anytime, and the old value will be forgotten.
N
JN
Example:
spam = 'Hello'
spam = 'Goodbye'
print(spam) # Output: Goodbye
L,
Rules for Variable Names IM
● Must be one word.
,A
● Can use letters, numbers, and _ (underscore).
● Cannot start with a number.
Examples:
M
1. my_var
2. age42
W
1. Opening the File Editor: The interactive shell is where you type one command at a time, but to
write full programs, you'll use the file editor.
The file editor looks like a regular text editor, but for Python code. It doesn't have the >>> prompt,
E
unlike the interactive shell.
C
2. Writing the Code:
N
Type the following code into the file editor:
# This program says hello and asks for my name.
JN
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
L,
print('It is good to meet you, ' + myName)
print('The length of your name is:') IM
print(len(myName))
print('What is your age?') # ask for their age
,A
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
M
3. Prints a greeting with your name: It is good to meet you, [Your Name]
4. Shows the length of your name: How many letters your name has.
5. Asks for your age: What is your age?
W
6. Tells you what your age will be next year: It adds 1 to your age.
YA
a. After writing the code, save your program so you don’t lose it.
LI
● If you want to reopen it later, go to File > Open, choose hello.py, and click Open. Your
program will appear again in the editor.
In Summary:
E
C
7. DISSECTING YOUR PROGRAM
N
Comments (#):
JN
● Anything after a # is a comment. Python ignores comments, so they’re just for you to make
notes or explain your code.
L,
● For example, # This program says hello is a comment, and Python doesn’t run it.
● You can also print empty lines with print() (without anything inside the parentheses).
EE
● input() asks the user to type something and then stores it.
● Example: myName = input()
W
● You can combine text and variables. For example print('It is good to meet you, ' + myName)
● If myName is 'Al', it will print: It is good to meet you, Al.
LI
● If you want to convert between different types of data (like numbers and text), you use
str() and int().
● str() turns numbers into text:
Error Handling:
● If you try to convert something that's not a number (like 'hello') using int(), Python will give
an error:
E
int('hello') # This will give an error.
C
N
Why Use str() and int():
JN
The input() function always gives you text (even if you type a number). To do math, you need to
convert it to a number with int(). When printing results, you might need to turn numbers back into text
with str() to combine them.
L,
CHAPTER 2
IM
1. BOOLEAN VALUES
,A
Boolean values in Python are a special type of data that can only be either True or False. These values
are not enclosed in quotes, and the first letter must always be capitalized (e.g., True, False).
M
For example:
EE
● When you write spam = True, the variable spam now holds the Boolean value True.
AS
● If you try to write true (with a lowercase "t"), Python will give an error because it doesn't
recognize it as the Boolean value True.
W
Additionally, True and False cannot be used as variable names. For example, if you try to assign a
value like True = 2 + 2, Python will give an error because True is a reserved word in Python.
YA
LI
AA
2. COMPARISON OPERATORS
E
C
N
JN
L,
IM
NOTE: The == operator checks if two values are equal. For example, 5 == 5 is True because both
sides are the same.
,A
The = operator is used to assign a value to a variable. For example, x = 5 means the variable x now
holds the value 5.
M
To remember:
EE
3. BOOLEAN OPERATORS
W
Boolean operators and, or, and not are used to work with Boolean values (True or False).
YA
● The and operator checks if both values are True. If both are True, the result is True; otherwise,
it’s False.
LI
For example:
○ True and True gives True
AA
E
C
N
JN
L,
IM
,A
M
You can combine comparison operators (like <, >, ==) with Boolean operators (and, or, not) in a
AA
single expression.
For example, 4 < 5 and 3 > 2 will first compare the numbers and then apply the and operator to check
if both comparisons are True.
x=4
y=7
z=3
Explanation:
E
C
result2 = (x > y) or (z > 2)
print(result2) # This will print True because one condition is true: 3 > 2
N
Explanation:
JN
● x > y checks if 4 is greater than 7, which is False.
● z > 2 checks if 3 is greater than 2, which is True.
L,
● The or operator gives True if at least one condition is True. So, the final result is True.
1. Conditions: A condition is a statement that evaluates to either True or False. For example, 4 <
EE
blocks are defined by indentation. Indentation means adding spaces or tabs at the beginning of
a line to indicate that it belongs to the same block.
○ Rule 1: A block starts when indentation increases.
W
6. PROGRAM EXECUTION
In a basic program, Python executes instructions one by one from top to bottom. However, with flow
control statements, the program can jump to different parts of the code or skip sections, depending on
conditions, altering the sequence of execution. ( It is saved as .py )
(a) if statement
An if statement checks if a condition is True. If it is, the code inside the block (called the clause) runs.
If the condition is False, the code inside the block is skipped. The statement starts with "if", followed
by the condition, a colon, and then an indented block of code.
E
C
N
JN
L,
IM
,A
M
EE
is False. It doesn’t need a condition and is used to say, "If this condition is true, run this code;
otherwise, run this code." It starts with the "else" keyword, followed by a colon and an indented block
of code.
W
YA
LI
AA
E
C
N
JN
L,
IM
,A
M
A while loop runs a block of code repeatedly as long as a condition is True. It starts with the "while"
keyword, followed by a condition, a colon, and then an indented block of code. If the condition
becomes False, the loop stops.
AS
count = 0
W
count += 1
This code will print the numbers 0 to 4. The loop continues as long as count is less than 5. After
each loop, count is increased by 1.
LI
AA
Initialization:
● The while loop checks if count < 5. Since count is 0, the condition is True.
● Inside the loop, print(count) is executed, so it prints 0 (the current value of count).
● Then, count += 1 is executed. This increases count from 0 to 1.
● The loop checks again if count < 5. Since count is now 1, the condition is still True.
● The loop checks if count < 5. Since count is now 2, the condition is still True.
E
Third Loop Iteration:
C
● print(count) prints 2.
N
● count += 1 increases count from 2 to 3.
JN
Fourth Check of the While Loop:
● The loop checks if count < 5. Since count is now 3, the condition is still True.
L,
Fourth Loop Iteration:
● print(count) prints 3.
IM
● count += 1 increases count from 3 to 4.
,A
Fifth Check of the While Loop:
M
● The loop checks if count < 5. Since count is now 4, the condition is still True.
EE
● print(count) prints 4.
AS
● The loop checks if count < 5. Since count is now 5, the condition is False.
YA
End of Loop:
● Since the condition is now False, the loop exits and the program ends.
LI
OUTPUT
AA
0
1
2
3
4
E
C
N
JN
(d) break statement
L,
The break statement is used to immediately exit from a loop (like a while or for loop) before it
naturally finishes. When the program reaches the break statement, it stops executing the loop and
IM
moves to the next part of the code.
,A
count = 0
while True: # Infinite loop
M
count += 1
print(count)
EE
if count == 5:
break # Exit the loop when count is 5
AS
Explanation:
W
OUTPUT
1
2
3
4
5
E
C
(e) for loop and range function
N
JN
A for loop is used in Python when you want to repeat a block of code a specific number of times. The
loop iterates over a sequence (like a list, string, or range) and performs an action for each item in that
sequence.
L,
The range() function: The range() function is often used in a for loop to generate a sequence of
IM
numbers. It can accept up to three arguments:
,A
1. Start (optional): The starting number (default is 0).
2. Stop: The number where the loop stops (this number is not included in the sequence).
M
3. Step (optional): The number to increment between each value (default is 1).
EE
Example
for i in range(5):
print(i)
AS
range(5) creates a sequence of numbers from 0 to 4 (it does not include 5).
W
The loop runs 5 times, and each time the variable i takes the next value in the sequence (0, 1, 2, 3, 4).
It prints each value of i one by one.
YA
OUTPUT
0
LI
1
AA
2
3
4
OUTPUT
1
3
5
7
9
E
C
N
JN
L,
(f) continue statement
IM
The continue statement in Python is used to skip the rest of the code inside the current loop iteration
,A
and move to the next iteration of the loop. It is often used when you want to avoid executing certain
code for specific conditions while continuing the loop.
M
EE
Why is it used?
Example:
W
OUTPUT
1
2
4
5
The number 3 is skipped because of the continue statement.
8. IMPORTING MODULES
In Python, a module is simply a file that contains Python code, including functions, classes, and
variables. It helps to organize your code into smaller, reusable pieces, making your program easier to
manage.
● Code Reusability: You can write a piece of code once in a module and reuse it in multiple
programs.
● Organization: It helps to break your code into smaller, manageable parts.
E
● Avoid Duplication: If you need the same function or class in multiple programs, you can
C
import the module instead of rewriting the code.
N
Examples of Python modules:
JN
1. math: Provides mathematical functions (like square root, power, etc.).
L,
import math
print(math.sqrt(16)) # Output: 4.0 IM
2. random: Helps to generate random numbers.
,A
import random
print(random.randint(1, 10)) # Output: A random number between 1 and 10
M
3. os: Interacts with the operating system (like working with files and directories).
EE
import os
print(os.getcwd()) # Output: Current working directory
AS
import time
print(time.time()) # Output: Current time in seconds since the epoch
YA
In Python, you can end a program early using sys.exit(). This is helpful when you want to stop the
program immediately if a certain condition is met, such as an error or invalid input.
AA
import sys
while True:
print("Type 'exit' to quit the program.")
user_input = input("Enter something: ")
if user_input == "exit":
print("Goodbye!")
sys.exit() # Ends the program here
print(f"You entered: {user_input}")
1. The program runs inside a loop and repeatedly asks the user to type something.
2. If the user types 'exit', the program prints "Goodbye!" and calls sys.exit(), which
stops the program immediately.
3. If the user types anything else, the program continues.
E
CHAPTER 3
C
1. def STATEMENTS WITH PARAMETERS
N
JN
In Python, functions can take parameters to make them more flexible and useful. A parameter is a
placeholder for the value (called an argument) that you pass to the function when calling it. This helps
functions perform specific tasks based on the input you provide.
L,
Key Concepts: IM
1. Defining a function with parameters:
,A
When you define a function, you can specify one or more parameters in parentheses. These
act like temporary variables within the function.
M
2. Passing arguments:
When calling the function, you provide the actual value (argument) for the parameter. The
EE
Parameters only exist inside the function. Once the function finishes, the parameter variables
are no longer available.
W
Example:
Explanation:
○ When hello('Alice') is called, the value 'Alice' is assigned to name. The function
prints 'Hello Alice'.
○ Similarly, hello('Bob') prints 'Hello Bob'.
OUTPUT
Hello Alice
Hello Bob
NOTE: If you try to use the parameter variable (name) outside the function, it will cause an error
because the parameter exists only inside the function.
E
C
hello('Alice')
N
print(name) # This will cause an error because 'name' does not exist outside the function.
JN
2. RETURN VALUESLAND RETURN STATEMENTS
In Python, a return statement is used in a function to send a value back to the code that called it. This
L,
returned value is called the return value. The return keyword is followed by the value or expression
that you want to return. IM
Key Points:
,A
1. A function with a return statement evaluates to the value specified in the return.
M
3. You can use the return value of a function in other parts of your program.
result = add(3, 5)
print(result) # Output: 8
YA
def square(num):
return num * num # Returns the square of the number
AA
print(square(4)) # Output: 16
def magic8Ball(answerNumber):
if answerNumber == 1:
return "Yes"
elif answerNumber == 2:
return "No"
else:
return "Ask again later"
response = magic8Ball(1)
print(response) # Output: Yes
E
3. THE NONE VALUE
C
In Python, None is a special value that means "no value" or "nothing." It is the only value of the
N
NoneType data type and is written with a capital N. Other programming languages may call this value
JN
null, nil, or undefined.
Key Points:
L,
1. None is not the same as 0, False, or an empty string. It specifically means "nothing."
IM
2. Functions that do not have a return statement automatically return None.
3. You can use None as a placeholder value in your code when you need to indicate "nothing" or
,A
"not yet set."
def my_function():
print("This function does something but doesn't return a value.")
AS
result = my_function() # The function prints something but doesn't return anything
print(result) # Output: None
W
Explanation:
YA
● The my_function() prints text, but it does not explicitly return a value.
LI
OUTPUT
Hello!
True
Summary:
E
● Functions without a return statement automatically return None.
C
● It is often used to indicate a placeholder or missing value.
N
4. KEYWORD WORD ARGUMENTS AND print( )
JN
When calling a function, arguments can be passed in two ways:
L,
1. Positional Arguments: Based on the order in which they are passed.
2. Keyword Arguments: By explicitly naming the parameter and assigning it a value.
IM
1. Positional Arguments
,A
import random
2. Keyword Arguments
Default behavior:
print("Hello")
print("World")
OUTPUT
Hello
World
The end parameter controls what is printed at the end of the line.
print("World")
OUTPUT
Hello World
E
5. Using the sep keyword:
C
N
The sep parameter controls how multiple arguments are separated.
JN
print("cats", "dogs", "mice", sep=",") # Use a comma instead of space
OUTPUT
L,
cats,dogs,mice IM
Why Use Keyword Arguments?
,A
● Clarity: It makes your code more readable by showing what each argument means.
EE
1. Global Scope
AS
2. Local Scope
LI
● A local scope is created when the function is called and is destroyed when the function ends.
Key Rules:
1. Global variables cannot be modified directly inside a function unless declared using the
global keyword.
2. Local variables exist only inside their function and are destroyed after the function ends.
3. Functions can access global variables, but local variables from one function cannot be
accessed in another function.
x = 10 # Global variable
def my_function():
y = 5 # Local variable
E
print("Inside function: x =", x) # Access global variable
C
N
print("Inside function: y =", y)
JN
my_function()
# print(y) # This will cause an error because y is local and not accessible here
L,
print("Outside function: x =", x) # Global variable is still accessible
IM
OUTPUT
,A
Inside function: x = 10
M
Inside function: y = 5
EE
Outside function: x = 10
AS
z = 20 # Global variable
W
def change_global():
YA
change_global()
OUTPUT
Inside function: z = 50
Outside function: z = 50
1. Global Scope
2. Local Scope
E
Why Is This Important?
C
N
● Global variables are shared by the whole program.
● Local variables exist only inside a function. This makes functions safer and easier to debug!
JN
6. EXCEPTION HANDLING
L,
What is Exception Handling?
●
IM
When your program runs into an error (called an exception), it can stop working and crash.
● Exception handling lets you catch those errors, fix them, and keep the program running
,A
smoothly instead of crashing.
M
● try block: You write the code that might cause an error.
● except block: If an error happens in the try block, Python will jump to the except block and
handle the error instead of crashing.
AS
Simple Example:
W
Let's say we want to divide a number by another number. What if the user enters 0? This will cause a
Zero Division Error, and the program will crash. We can prevent that using exception handling.
YA
def spam(divideBy):
LI
try:
return 42 / divideBy # This might cause an error
AA
except ZeroDivisionError:
return "You can't divide by zero!" # Handle the error
return 42 / divideBy
● The try block contains the division code, which may cause an error if divideBy is 0.
● The except block catches the ZeroDivisionError and returns a friendly message instead of
crashing.
● If there is no error, the division happens normally.
OUTPUT:
21.0
E
3.5
C
You can't divide by zero!
N
42.0
JN
Summary:
L,
● Use try to attempt risky code.
●
●
IM
Use except to handle any errors that happen in the try block.
This prevents your program from crashing when errors occur.
,A
7. A SHORT PROGRAM:GUESS THE NUMBER
M
In this simple game, the computer thinks of a number between 1 and 20, and you have to guess it.
After each guess, the program will tell you if your guess is too high or too low, until you get the
EE
Game Flow:
1. The computer picks a random number between 1 and 20 (you don't know it).
W
5. Once you guess it right, the program congratulates you and tells you how many guesses it
AA
took.
Example:
When you run the program, the output looks like this:
You start by guessing 10. The computer says it's too low.
E
Then, you guess 15. It's still too low.
C
Then, you guess 17. The computer says it's too high.
N
Finally, you guess 16, and the computer says "Good job! You guessed my number in 4 guesses!"
JN
How Does It Work?
L,
● The program uses a loop to let you keep guessing until you get it right.
●
IM
It compares your guess with the computer's number using if statements.
● It counts how many guesses it takes using a counter.
,A
Summary:
M
E
C
N
JN
L,
IM
,A
M
EE
AS
W
YA
LI
AA