BSC CS - Python - Chapter 1
BSC CS - Python - Chapter 1
E
the CPU. application then you can use it as an extension
or command language for that application.
EG
2. Python is a free and open source language
Open-source software is computer software 8. Python is object oriented
that is released under a license in which the i. Python supports the object oriented
LL
copyright holder grants users the rights to use, programming concept.
study, change, and distribute the software and
its source code to anyone and for any purpose. ii. Object-oriented programming is a
O
programming paradigm based on the concept
C
3. Python is simple of objects, which can contain data and code:
i. There is no need of declaring variables in the data in the form of fields, and code in the form
python. of procedures.
EE
ii. In a single statement the user can express iii. In OOP, computer programs are designed
the complex operations. by making them out of objects that interact
R
1
2. Using an Integrated Development
Environment (IDE)
PyCharm:
E
hello.py:
Right-click on the file in the project explorer
EG
print("Hello, World!") and select Run 'filename', or use the Run
button at the top.
iii. To execute this script, save the file as
LL
hello.py. VS Code:
O
1. Using the Command Line (Terminal)
II. Open Your Project Folder.
C
Windows: III. Open Your Python File.
IV. Run the Script:
EE
I. Open Command Prompt:
Press Ctrl + Shift + P to open the command
Press Win + R, type cmd, and hit Enter. palette, type Run Python File, and select it.
Alternatively, use the play button in the top
R
Use the python or python3 command followed Press Shift + Enter or click the Run button in
IG
2
implementation of reference implementation of the programming, most
Python, written in C. Python language. Known for its commonly used for
stability and extensive support. development.
IronPython An implementation of
Python that targets the Fully integrated with .NET, Development of .NET
E
.NET Framework and allowing for the use of .NET applications or
Mono. libraries.Can be used to develop integration with .NET
EG
.NET applications using Python. libraries.
LL
PyPy An alternative Uses a Just-In-Time (JIT) Performance-critical
implementation of compiler to improve applications, where
Python which focuses performance. Compatible with execution speed is
O
on speed and existing Python code (though important.
C
efficiency. some C extensions might not
work).
EE
MicroPython A lean and efficient Small footprint, suitable for
implementation of microcontrollers. Supports a Embedded systems, IoT
R
Syntax Tree).
SH
Here’s a breakdown of the key components: c. Code Generator: Converts the AST into
bytecode instructions.
1. Source Code
Written in C: CPython is primarily written in ii. Bytecode: An intermediate representation
the C programming language. of the source code, which is
platform-independent and executed by the
Open Source: The source code is freely Python virtual machine (PVM).
available, allowing developers to study and
modify it. 3. Python Virtual Machine (PVM)
Execution Engine: The PVM executes the
2. Interpreter Components bytecode instructions. It’s a stack-based virtual
3
machine where each instruction is executed Try-Except Blocks: Python uses try-except
one at a time. blocks for error handling, which allows
programs to handle runtime errors gracefully.
Main Loop: The PVM has a main loop that
fetches the next bytecode instruction, decodes Exception Hierarchy: Python has a built-in
it, and executes it. hierarchy of exceptions, providing a structured
way to handle different types of errors.
4. Memory Management
Object Model: Everything in Python is an Overview of Execution Flow
object, including data types and functions. The 1. Write Code: You write Python source code
object model manages the creation, in a .py file.
manipulation, and deletion of objects.
E
2. Compile to Bytecode: The Python
EG
Garbage Collection: Python uses reference compiler translates the source code into
counting and a cyclic garbage collector to bytecode, stored in .pyc files.
manage memory. When an object’s reference
count drops to zero, it is deallocated. 3. Execute Bytecode: The PVM executes the
LL
bytecode, interacting with the operating
6. Exception Handling system and hardware as necessary.
O
C
EE
R
EG
Example:
ii. They are ignored by the Python interpreter,
.M
Docstrings:
Everything after the # on that line is ignored
SH
4
This function greets the person whose i. The second mode of IDLE is script mode. In
name is passed as a parameter. this mode you can write, edit, load and save
your Python program like a word processor.
Parameters:
ii. You can also perform cut, copy, paste
name (str): The name of the person to
operation.
greet.
iii. To open the window in script mode:
Returns:
None a. Click on file menu on the interactive
""" window.
print(f"Hello, {name}!") b. Click on new file.
E
# Accessing the docstring
EG
print(greet.__doc__)
LL
IDLE:
O
Interface (GUI) Integrated Development
C
Environment called IDLE.
i. In the interactive mode the user will tell the Represents whole numbers without a decimal
Python what to do and Python will do it point.
.D
immediately. Syntax: x = 5
iii. The open window is known as "Python print(type(x)) # Output: <class 'float'>
Shell". >>> is known as the command prompt.
SH
5
x = True 1. Write a program that creates and prints
print(type(x)) # Output: <class 'bool'> integer and float variables.
Represents an ordered collection of items. 3. Write a program that creates and prints
Syntax: x = [1, 2, 3] boolean variables.
x = [1, 2, 3]
print(type(x)) # Output: <class 'list'> 4. Write a program that creates and prints a
list.
6. Tuple (tuple):
E
5. Write a program that creates and prints a
tuple.
EG
Represents an ordered collection of items that
cannot be modified (immutable). 6. Write a program that creates and prints a
Syntax: x = (1, 2, 3) dictionary.
LL
x = (1, 2, 3)
print(type(x)) # Output: <class 'tuple'> 7. Write a program that creates and prints a set.
O
8. Write a program that creates a variable with
7. Dictionary (dict): `None` value and prints it.
C
Represents a collection of key-value pairs. 9. Write a program that creates and prints a
EE
Syntax: x = {"key": "value"} complex number.
x = {"name": "John", "age": 30}
print(type(x)) # Output: <class 'dict'> 10. Write a program that creates a list
R
items.
letter (a-z, A-Z) or underscore (_)
Syntax: x = {1, 2, 3}
.M
print(type(x)) # Output: <class 'NoneType'> assert, async, await, break, class, continue, def,
del, elif, else, except, finally, for, from, global,
10.Complex (complex): if, import, in, is, lambda, nonlocal, not, or,
pass, raise, return, try, while, with, yield.
Represents complex numbers with real and
imaginary parts. Input Function:
Syntax: x = 1 + 2j
Syntax:
x = 1 + 2j
print(type(x)) # Output: <class 'complex'>
variable = input(prompt)
Home Work Exercise - 1
prompt: A string, representing a message to
6
display to the user. This parameter is optional. ii. The first element of this list is the name of
the script itself.
Example:
import sys
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Print all command line arguments
print("count of numbers:", len(sys.argv))
Output Statement: print("Numbers:", sys.argv)
Syntax:
# Access individual arguments
if len(sys.argv) > 1:
E
print(*objects, sep=' ', end='\n', print("First Number:", sys.argv[1])
EG
file=sys.stdout, flush=False)
print("Addition total: ", sys.argv[1] +
● objects: The values to be printed. sys.argv[2])
LL
Multiple values can be separated by
commas.
O
● sep: String inserted between values,
default is a space.
C
● end: String appended after the last
value, default is a newline.
EE
● file: An object with a write method,
default is sys.stdout.
● flush: Whether to forcibly flush the
R
stream.
EG
Example:
print("Hello, World!")
.M
# Custom separator and end
IG
Using argparse:
print("apple", "banana", "cherry", sep=", ",
end=". ") The argparse module provides a more flexible
R
7
parser.add_argument('name', type=str, operator.
help='Your name')
parser.add_argument('age', type=int, - It subtracts right hand operand
from the left hand operand.
help='Your age')
* It multiplies values on either side
# Parse the arguments of the operator.
args = parser.parse_args()
/ It divides left hand operand by
right hand operand.
# Use the arguments
print(f"Hello, {args.name}! You are % It divides left hand operand by
E
{args.age} years old.") right hand operand and returns
remainder.
EG
Save this script as script.py, and you can run it
** It performs exponential (power)
from the command line like this: calculation on operators.
LL
python script.py Alice 30 // Floor division - The division of
operands where the result is the
O
quotient in which the digits after
Output:
C
the decimal point are removed.
But if one of the operands are
negative, the result is floored, i.e.,
EE
Hello, Alice! You are 30 years old.
rounded away from zero (towards
negative infinity)
R
Operators in Python:
i. Operators are special symbols that represent
EG
Example:
calculation like addition and subtraction.
a = 34
ii. The values which operator uses are called b = 23
.D
operands. c = 0
c = a + b
For example: >>>2+3
.M
operator. c = a - b
print("2. Subtraction result", c) #2.
IG
8
c = a // b < If value of the left operand is less
print("6. Floor division result", c) #Floor than the value of right operand,
division result 4 then condition becomes true.
E
length and width. true.
EG
3. Write a program to concatenate two strings
and print the result. Example:
4. Write a program to convert a given
LL
a = 10
temperature from Celsius to Fahrenheit and
b = 5
vice versa.
c = a == b
O
5. Write a program to swap two variables and
print(c) #False
print their values before and after swapping.
C
c = a != b
print(c) #True
Homework Exercise - 2
EE
c = a > b
1. Write a program to find the average of three
print(c) #True
numbers entered by the user.
c = a < b
R
5. Write a program to calculate the sum of the = It is used to assign the values of
digits of a given integer. right side operand to the left side
.P
operand.
IG
Operator Description
SH
== If the values of two operands are -= The right operand gets subtracted
equal, then the condition becomes from the left operand and the
true. result is assigned to the left
operand.
!= If the values of two operands are
not equal, then condition becomes *= The right operand get multiplied
true. with the left operand and the
result is assigned to the left
> If value of the left operand is operand.
greater than the value of right
operand, then condition becomes /= The left operand is divided by the
true. right operand and the result is
9
assigned to the left operand. given by the right operand.
Example: Example:
a = 20 print(bin(60)) #0b111097
b = 15 print(bin(13)) #0b1101
c = 0 print(60 & 13, bin(60 & 13)) #12 0b1100
c = a + b print(60 | 13, bin(60 | 13)) #61 0b111101
print(c) #35 print(60 ^ 13, bin(60 ^ 13)) #49 0b110001
c += a print(60 << 2, bin(60 << 2)) #240
print(c) # 55 0b11110000
E
c *= a print(60 >> 3, bin(60 >> 2)) #7 0b1111
EG
print(c) #11.00
c /= a 5. Logical Operators:
print(c) #55.0
LL
c = 2 Operator Description
c %= a
And Logical AND - If both the
O
print(c) #2 operands are true then condition
C
c **= a becomes true.
print(c) #1048576
Or Logical OR - If any of the two
EE
c //= a
print(c) #52428 operands are non-zero then
condition becomes true.
R
10
*, /, //, %, +, -, <<, >>, &, ^, |,==, !=, >, >=, <,
Operator Description
<=, is, is not, in, not in, and, or
is Evaluates to true if the variables
on either side of the operator Right-associative operators (evaluated from
point to the same object and false right to left):
otherwise.
**, =, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=,
Is not Evaluates to false if the variables >>=, <<=, not
on either side of the operator
point to the same object and true
Example:
otherwise.
# Addition and subtraction are
E
Example: left-associative
EG
result = 10 - 2 + 3
a = 30 # Evaluation: (10 - 2) + 3
b = 30 # Result: 8 + 3 = 11
LL
print(a is b) #True
print(a is not b) #False # Multiplication and division are
O
left-associative
Precedence of Operators: result = 20 / 4 * 2
C
# Evaluation: (20 / 4) * 2
# Result: 5 * 2 = 10
EE
Level Category Operators
7 (high) exponent **
R
# Exponentiation is right-associative
6 multiplication *,/,//,% result = 2 ** 3 ** 2
EG
# Evaluation: 2 ** (3 ** 2)
5 additional +,- # Result: 2 ** 9 = 512
.D
3 logical not
Exponentiation (**) has the highest
.P
2 logical and
precedence: 2 ** 2 evaluates to 4
IG
1 (low) logical or
Multiplication and Division (*, /): 5 * 4
evaluates to 20, 8 / 4 evaluates to 2.
R
11
exponentiation, floor division) and print the 1. The if Statement
results. i. The if statement evaluates a condition.
2. Write a program to compare two numbers
using comparison operators (==, !=, >, <, >=, ii. If the condition is true, the code block
<=) and print whether the conditions are True inside the if statement is executed.
or False.
3. Write a program to demonstrate the use of iii. It allows the program to make decisions
logical operators (and, or, not) with boolean and execute different actions based on the
values and print the results. condition.
4. Write a program to perform bitwise
operations (AND, OR, XOR, NOT, shift left, Syntax:
E
shift right) on two integer values and print the
EG
results. if condition:
5. Write a program to demonstrate the use of # code to execute if condition is true
assignment operators (+=, -=, *=, /=, //=, %=,
LL
=, &=, |=, ^=, >>=, <<=) and print the results Example:
after each operation.
O
number = 5
C
if number > 0:
Homework Exercise - 3 print("The number is positive.")
EE
1. Write a program to show the precedence of
operators by evaluating and printing the result
of a complex expression involving multiple 2. The if … else Statement
R
the result.
iv. This provides a way to handle alternative
4. Write a program to use the in and not in
actions.
IG
12
else: while condition:
print("The number is non-positive.") # code to execute while condition is true
E
inside the else statement is executed. 5. Loop Statement - for loop
EG
iii. This allows for more complex i. The for loop iterates over a sequence (like a
decision-making. list, tuple, or range) and executes a block of
LL
code for each item in the sequence.
Syntax:
ii. It is useful for iterating a known number of
O
times or over a known sequence of elements.
if condition1:
C
# code to execute if condition1 is true Syntax:
elif condition2:
EE
# code to execute if condition2 is true
for variable in sequence:
else:
# code to execute for each item in the
R
Example:
Example:
.D
4. Loop Statement - while loop ii. Such loops must be controlled or terminated
SH
manually.
i. The while loop repeatedly executes a block
of code as long as the specified condition iii. They are useful in scenarios where the loop
remains true. must run until an external condition is met or a
break statement is encountered.
ii. It is useful for situations where the number
of iterations is not known beforehand and Syntax:
depends on dynamic conditions.
while True:
Syntax:
# code to execute indefinitely
13
Example: for i in range(3):
print(i)
while True: else:
print("This will run forever unless print("Loop is done.")
stopped manually.")
9. break statement
7. Nested loop
i. The break statement is used to exit a loop
i. A nested loop is a loop inside another loop. prematurely when a specified condition is met.
The inner loop completes all its iterations for
each single iteration of the outer loop. ii. This allows for immediate termination of
E
the loop, skipping the remaining iterations.
EG
ii. This is useful for working with
multi-dimensional data structures, such as Syntax:
matrices.
LL
for variable in sequence:
Syntax: if condition:
O
break
for outer_variable in outer_sequence: # more code
C
for inner_variable in inner_sequence:
# code to execute for each combination
EE
Example:
of outer and inner variables
for i in range(5):
R
Example: if i == 3:
EG
break
for i in range(1, 4): print(i)
for j in range(1, 4):
.D
print(i, j)
10. continue statement
i. The continue statement skips the current
.M
completes all its iterations normally (i.e., not ii. It is useful for skipping over certain
terminated by a break statement). conditions within a loop without terminating
the entire loop.
R
Syntax:
for variable in sequence:
for variable in sequence: if condition:
# code to execute for each item in the continue
sequence # more code
else:
# code to execute after the loop finishes Example:
14
if i == 2: 13. return statement
continue i. The return statement is used to exit a
print(i) function and optionally pass a value back to
the caller.
11. pass statement
ii. It allows functions to produce outputs and
i. The pass statement is a null operation; it end their execution at any point, returning
does nothing when executed. control to the point where the function was
called.
ii. It is used as a placeholder in situations
where a statement is syntactically required but Syntax:
E
no action is needed, such as in stubs or during
EG
code development. def function_name(parameters):
# code
Syntax:
return value
LL
if condition:
Example:
O
pass
# more code
C
def add(a, b):
return a + b
EE
Example:
result = add(3, 4)
print(result)
for i in range(5):
R
if i == 3:
EG
Classwork Exercise - 3
12. assert statement 1. Write a program that takes an integer input
i. The assert statement is used for debugging from the user and prints "Even" if the number
.M
purposes. is even.
2. Write a program that takes an integer input
.P
ii. It tests a condition and triggers an from the user and prints "Positive" if the
IG
AssertionError if the condition is false, number is greater than zero, otherwise prints
optionally displaying an error message. "Non-positive".
3. Write a program that takes an integer input
R
iii. It helps to catch and diagnose bugs early in from the user and prints "Positive", "Zero", or
the development process.
SH
15
2. Write a program that prints a multiplication
table from 1 to 3 using nested loops.
3. Write a program that iterates through a list
of numbers and prints each number. After the
loop ends, print "Loop completed" using the
else suite.
4. Write a program that iterates through
numbers from 1 to 10 and prints each number.
If the number is 5, break the loop.
5. Write a program that iterates through
numbers from 1 to 5 and prints each number,
E
but skips the number 3.
EG
LL
O
C
EE
R
EG
.D
.M
.P
IG
R
SH
16