MIDTERM- PL101
MIDTERM- PL101
What is Python?
o Open IDLE to launch the
● Cross-platform language: Runs on interactive shell.
Windows, macOS, Linux, and is ported o Create a new file, save with .py
to Java/.NET virtual machines. extension (e.g., hello.py).
● Free and open-source. o Write code and run via Run >
Run Module or press F5.
● Pre-installed on Linux and macOS, but
may require updates to the latest Your First Python Program
version.
● Example: "Hello, World!"
Running Python
1. The Easiest Way: Using Thonny IDE Code: print("Hello, world!")
● Comes bundled with the latest Python Save as hello_world.py and run to see:t
version.
Output: Hello, world!
● Steps:
1. Download and install Thonny. Keywords and Identifiers
2. Go to: File > New, save the file
with .py extension (e.g.,
Keywords
hello.py).
3. Write your Python code.
4. To run, go to: Run > Run current ● Reserved words that define Python's
script or press F5. syntax and structure.
● Case-sensitive.
2. Immediate Mode
● Cannot be used as identifiers.
● Type python to start the Python False | await | else | import | pass |
| None | break | except | in | raise |
interpreter.
| True | class | finally | is | return |
● Type code (e.g., 1 + 1) and press Enter | and | continue | for | lambda | try |
for instant results. | as | def | from | nonlocal | while |
● Use quit() to exit. | assert| del | global | not | with |
| async | elif | if | or | yield |
3. Using an IDE
Identifiers
● IDEs provide features like:
o Code hinting ● Names for variables, functions, classes,
o Syntax highlighting
etc.
o File explorers
● Rules for Naming Identifiers: ●
o Can include letters, digits, and
underscores (_), e.g., myClass, Example:
var_1. for i in range(1, 6):
o Cannot start with a digit (e.g., print(i)
1variable is invalid). if i == 3:
o Cannot use keywords (e.g., break
global = 1 is invalid).
o No special characters (e.g., a@
Inconsistent indentation causes
= 0 is invalid).
IndentationError.
o Can be of any length.
Things to Remember
3. Boolean Literals
Values: True, False:
Constants x = (1 == True) # True
y = (1 == False) # False
Convention: Use ALL CAPS (e.g., PI = 3.14).
a = True + 4 #5
Example:
# In constant.py 4. Special Literals
GRAVITY = 9.8 None: Indicates the absence of a
# In main.py value:
import constant food = None
print(constant.GRAVITY) print(food) # None
Rules for Naming Variables and Constants
5. Literal Collections
Types: List, Tuple, Dictionary,
1. Use letters (a-z, A-Z), digits (0-9), or
underscores _. Set:
2. Cannot start with a digit (e.g., 1var is fruits = ["apple", "orange"] # List
invalid). numbers = (1, 2, 3) # Tuple
3. Avoid special characters (!, @, #, etc.). alphabets = {'a': 'apple'} #
4. Follow naming conventions like Dictionary
snake_case or MACRO_CASE. vowels = {'a', 'e', 'i'} # Set
Literals
Module 8
● Definition: Fixed values assigned to
variables/constants. Data Types in Python
Python is a dynamically typed language where
1. Numeric Literals the type of a variable is determined at runtime.
Below is a detailed breakdown of various data
Types: Integer, Float, Complex types and their uses.
a = 0b1010 # Binary
s = "Hello, World!"
print(s[4]) # Output: o
1. Python NumbersPython supports three main print(s[7:12]) # Output: World
types of numbers: Immutability:
s[0] = 'h' # Throws TypeError
● Integer (int): Whole numbers of
unlimited size.
3. Type Conversion
● Floating Point (float): Numbers with a
Python supports:
decimal point, precise up to 15 decimal
places.
1. Implicit Type Conversion: Python
● Complex (complex): Numbers with a automatically converts lower to higher
real and imaginary part, represented as types (e.g., int to float).
x + yj. 2. Explicit Type Conversion: Done
manually using functions like int(),
Examples: float(), and str().
Example:
5. Python Imports
Modules allow you to reuse code. Use import to a = 7
b = 2
include modules:
print('Sum:', a + b)
import math print('Subtraction:', a - b)
print('Multiplication:', a * b)
print(math.pi) # Output: 3.141592653589793 print('Division:', a / b)
You can also import specific components: print('Modulo:', a % b)
print('Power:', a ** b)
from math import sqrt
print(sqrt(16)) # Output: 4.0
2. Assignment Operators
Custom Modules: Python searches for modules
in the directories listed in sys.path. You can add
● Assign values or perform operations
custom paths to it.
while assigning.
Module 9 ● Operators and Their Usage:
Reviewer: Python Operators
Overview Opera Operatio Exam
tor n ple
1. Arithmetic Operators
Assignme
= a=7
nt
● Perform basic mathematical operations.
a += 1
Add and
Operators and Their Usage: += (a =
assign
a+1)
Operat Examp
Operation Subtract a -= 3
or le
-= and (a = a-
5+2 assign 3)
+ Addition
=7
Multiply a *= 4
4-2= *= and (a =
- Subtraction
2 assign a*4)
2*3= Divide a /= 3
* Multiplication
6 /= and (a =
4/2= assign a/3)
/ Division
2 Power
5%2 **= and a **= 2
% Modulo assign
=1
Power/ 4 ** 2
**
Exponent = 16
Example:
a = 10 print('a < b:', a < b)
b = 5 print('a >= b:', a >= b)
a += b # a = a + b print('a <= b:', a <= b)
print(a) # Output: 15
4. Logical Operators
3. Comparison Operators
● Combine conditional statements.
● Compare two values and return a
● Operators and Their Usage:
boolean (True or False).
● Operators and Their Usage:
Opera Descripti Exam
tor on ple
Opera Examp
Meaning Returns (a >
tor le
True if b) and
and
both are (b >
== Equal to 3 == 5 False True 0)
Returns (a >
True if b) or
Not or
!= 3 != 5 True one is (b <
equal to
True 0)
Greater Inverts
> 3 > 5 False the not(a
than not
boolean > b)
value
< Less than 3 < 5 True
Greater
5. Special Topic: Rounding Numbers
>= than or 3 >= 5 False
equal to
● Round decimals to a specific number of
Less than places:
<= or equal 3 <= 5 True
a = 3.4536
to print('Using %: %.2f' % a)
# 2 decimal places
print('Using format():
{:.3f}'.format(a)) # 3 decimal
places
Example: print('Using round():', round(a, 2))
# 2 decimal places
a = 5 Notes
b = 2
print('a == b:', a == b)
print('a != b:', a != b)
print('a > b:', a > b)
1. These operators are essential for
mathematical, conditional, and logical
operations in Python.
2. Experiment with examples to
understand their behavior.