Unit Two Notes
Unit Two Notes
python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Interactive mode
2. Script mode
1. Interactive mode:
Interactive Mode, as the name suggests, allows us to interact with OS.
When we type Python statement, interpreter displays the result(s) immediately.
advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small pieces of code.
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run
them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter
code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is
the words.
2. Script mode:
In script mode, we type python program in a file and then use interpreter to execute the
content of the file.
Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning
that the filename ends with .py
Save the code with filename.py and run the interpreter in script mode to execute the script.
Integrated Development Learning Environment (IDLE):
Is a graphical user interface which is completely written in Python.
It is bundled with the default implementation of the python language and also comes with
optional part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
VALUES AND TYPES
Basic Data Types
Integer (int)
Description: Represents whole numbers. They can be positive or negative, and there are no
decimal points.
Examples:
a = 10 # Positive integer
b = -5 # Negative integer
c=0 # Zero
print(a, b, c) # Output: 10 -5 0
Floating Point (float)
Description: Represents real numbers and are written with a decimal point. They can also be in
scientific notation.
Examples:
x = 3.14 # Standard float
y = -0.001 # Negative float
z = 2e3 # Scientific notation (2 * 10^3)
print(x, y, z) # Output: 3.14 -0.001 2000.0
Boolean (bool)
Description: Represents one of two values: True or False. They are often used in conditions and
control flow statements.
Examples:
is_active = True
is_complete = False
print(is_active, is_complete) # Output: True False
String (str)
Description: A sequence of characters enclosed in single, double, or triple quotes. Strings are
immutable.
Examples:
greeting = "Hello, World!"
name = 'Alice'
multi_line = """This is a string
that spans multiple lines."""
print(greeting) # Output: Hello, World!
print(multi_line) # Output: This is a string...
Collection Types
List
Description: An ordered, mutable collection of items that can be of different types.
Examples:
my_list = [1, 2, 3, 'a', 'b']
my_list.append(4) # Add an item
print(my_list) # Output: [1, 2, 3, 'a', 'b', 4]
Tuple
Description: Similar to lists but immutable. Once defined, their elements cannot be changed.
Examples:
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
Dictionary (dict)
Description: An unordered collection of key-value pairs. Keys must be unique and immutable.
Examples:
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name']) # Output: Alice
Set
Description: An unordered collection of unique items.
Examples:
my_set = {1, 2, 3, 3} # Duplicate 3 is ignored
print(my_set) # Output: {1, 2, 3}
int_value = 10
float_value = float(int_value) # Converts to 10.0
print(float_value) # Output: 10.0
From string:
str_value = "3.14"
float_value = float(str_value) # Converts to 3.14
print(float_value) # Output: 3.14
Converting to String
From integer:
int_value = 25
str_value = str(int_value) # Converts to "25"
print(str_value) # Output: "25"
From float:
float_value = 3.14159
str_value = str(float_value) # Converts to "3.14159"
print(str_value) # Output: "3.14159"
Converting to List and Tuple
From string:
str_value = "hello"
list_value = list(str_value) # Converts to ['h', 'e', 'l', 'l', 'o']
tuple_value = tuple(str_value) # Converts to ('h', 'e', 'l', 'l', 'o')
print(list_value) # Output: ['h', 'e', 'l', 'l', 'o']
print(tuple_value) # Output: ('h', 'e', 'l', 'l', 'o')
From a range:
range_value = range(5)
list_value = list(range_value) # Converts to [0, 1, 2, 3, 4]
print(list_value) # Output: [0, 1, 2, 3, 4]
Important Notes on Type Conversion
● Loss of Precision: Converting from float to int truncates the decimal part, which can lead
to loss of information.
● Invalid Conversions: Attempting to convert a string that does not represent a valid
number (like "abc") to an integer or float will raise a ValueError.
Examples of Invalid Conversions
● Invalid string conversion:
str_value = "abc"
try:
int_value = int(str_value) # Raises ValueError
except ValueError:
print("Cannot convert 'abc' to an integer.")
VARIABLES
A variable in Python is a symbolic name that references an object. It acts as a storage location for
data, which you can manipulate throughout your program. Variables allow you to label data with
a descriptive name, making your code more readable and maintainable.
Variable Naming Rules
When naming variables in Python, there are specific rules and conventions to follow:
- Valid Characters: Variable names can contain letters (both uppercase and lowercase), digits, and
underscores (`_`). However, they cannot start with a digit.
- Case Sensitivity: Variable names are case-sensitive, meaning `myVar`, `MyVar`, and `MYVAR`
are all different variables.
- Keywords: You cannot use Python reserved keywords (like `if`, `else`, `for`, `while`, etc.) as
variable names.
- Descriptive Names: While it's allowed to use short variable names (like `x` or `y`), it’s a good
practice to use descriptive names that convey the purpose of the variable.
Variable Assignment
- Syntax: Use the equals sign (`=`) to assign a value to a variable.
- Example:
age = 25 # Assigning an integer
name = "Alice" # Assigning a string
height = 5.5 # Assigning a float
is_student = True # Assigning a boolean
Dynamic Typing
Python is dynamically typed, meaning you don’t have to declare the type of a variable explicitly.
The type is inferred based on the assigned value.
- Example:
a = 10 # a is an integer
a = "Hello" # Now a is a string
print(a) # Output: Hello
Multiple Variable Assignment
You can assign values to multiple variables simultaneously using tuple unpacking.
- Example:
x, y, z = 1, 2, 3 # Assigns 1 to x, 2 to y, and 3 to z
print(x, y, z) # Output: 1 2 3
Swapping Variable Values
Python allows a convenient way to swap the values of two variables without needing a
temporary variable.
- Example:
a=5
b = 10
a, b = b, a # Swaps the values
print(a, b) # Output: 10 5
Reassigning Variables
You can change the value of a variable at any time by reassigning it.
- Example:
count = 0
count += 1 # Increments count by 1
print(count) # Output: 1
Variable Scope
The scope of a variable determines where it can be accessed in your code. Variables can be:
- Global Variables: Defined outside of any function, accessible throughout the module.
global_var = "I am global"
def my_function():
print(global_var) # Accessible here
my_function() # Output: I am global
- Local Variables: Defined within a function, only accessible inside that function.
def my_function():
local_var = "I am local"
print(local_var) # Accessible here
EXPRESSION
An expression is a combination of values, variables, operators, and calls to functions that the
Python interpreter evaluates to produce another value. Expressions can be as simple as a single
value or variable or as complex as a combination of several operations.
Types of Expressions
1. Arithmetic Expressions
- Combine numbers using arithmetic operators to perform mathematical calculations.
- Operators: `+`, `-`, `*`, `/`, `//` (floor division), `%` (modulus), `**` (exponentiation).
- Example:
x = 10
y=5
result = x + y * 2 # Evaluates to 20 (due to operator precedence)
print(result) # Output: 20
2. Relational (Comparison) Expressions
- Compare two values and return a Boolean result (`True` or `False`).
- Operators: `==`, `!=`, `<`, `>`, `<=`, `>=`.
- Example:
a = 10
b = 20
is_greater = a > b # Evaluates to False
print(is_greater) # Output: False
3. Logical Expressions
- Combine Boolean values using logical operators.
- Operators: `and`, `or`, `not`.
- Example:
x = True
y = False
result = x and y # Evaluates to False
print(result) # Output: False
4. Bitwise Expressions
- Perform operations on bits of integers.
- Operators: `&`, `|`, `^`, `~`, `<<`, `>>`.
- Example:
x = 4 # Binary: 100
y = 5 # Binary: 101
result = x & y # Bitwise AND
print(result) # Output: 4 (Binary: 100)
5. Membership Expressions
- Check for membership within a sequence (like strings, lists, or tuples).
- Operators: `in`, `not in`.
- Example:
my_list = [1, 2, 3, 4]
exists = 2 in my_list # Evaluates to True
print(exists) # Output: True
6. Identity Expressions
- Check whether two variables point to the same object in memory.
- Operators: `is`, `is not`.
- Example:
a = [1, 2, 3]
b=a
c = a.copy() # Creates a copy of the list
print(a is b) # Evaluates to True (same object)
print(a is c) # Evaluates to False (different objects)
Evaluating Expressions
When Python evaluates an expression, it follows the rules of precedence and associativity to
determine the order in which the components are processed.
Example of Expression Evaluation:
x = 10
y=5
result = x * y + 2 3 - 4 / 2
# Evaluated as follows:
# 1. 2 3 = 8 (exponentiation)
# 2. 4 / 2 = 2.0 (division)
# 3. x * y = 50 (multiplication)
# 4. Combine: 50 + 8 - 2.0 = 56.0
print(result) # Output: 56.0
Conclusion
- An expression is a combination of values, variables, operators, and functions that evaluates to a
value.
- Expressions can be arithmetic, relational, logical, bitwise, membership, or identity.
- Understanding operator precedence and associativity is crucial for correctly evaluating complex
expressions.
OPERATORS
Operators are special symbols in Python that perform operations on one or more operands
(variables, values, etc.) to produce a result. They are fundamental in building expressions and
carrying out calculations or logical operations.
Types of Operators in Python
1. Arithmetic Operators
- Used for mathematical operations.
- Operators: `+`, `-`, `*`, `/`, `//`, `%`, `**’
- Examples:
a = 10
b=3
print(a + b) # Output: 13 (Addition)
print(a - b) # Output: 7 (Subtraction)
print(a * b) # Output: 30 (Multiplication)
print(a / b) # Output: 3.333... (Division)
print(a // b) # Output: 3 (Floor Division)
print(a % b) # Output: 1 (Modulus)
print(a b) # Output: 1000 (Exponentiation)
2. Relational (Comparison) Operators
- Used to compare two values.
- Operators: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Examples:
a=5
b = 10
print(a == b) # Output: False (Equal to)
print(a != b) # Output: True (Not equal to)
print(a < b) # Output: True (Less than)
print(a > b) # Output: False (Greater than)
print(a <= b) # Output: True (Less than or equal to)
print(a >= b) # Output: False (Greater than or equal to)
3. Logical Operators
- Used to combine Boolean values.
- Operators: `and`, `or`, `not`
- Examples:
x = True
y = False
print(x and y) # Output: False (Logical AND)
print(x or y) # Output: True (Logical OR)
print(not x) # Output: False (Logical NOT)
4. Bitwise Operators
- Operate on bits of integer values.
- Operators: `&`, `|`, `^`, `~`, `<<`, `>>`
- Examples:
a = 4 # Binary: 100
b = 5 # Binary: 101
print(a & b) # Output: 4 (Bitwise AND)
print(a | b) # Output: 5 (Bitwise OR)
print(a ^ b) # Output: 1 (Bitwise XOR)
print(~a) # Output: -5 (Bitwise NOT)
print(a << 1) # Output: 8 (Left shift)
print(a >> 1) # Output: 2 (Right shift)
5. Assignment Operators
- Used to assign values to variables.
- Operators: `=`, `+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `**=`
- Examples:
a=5
a += 2 # Equivalent to a = a + 2
print(a) # Output: 7
a *= 3 # Equivalent to a = a * 3
print(a) # Output: 21
6. Identity Operators
- Used to check if two variables point to the same object.
- Operators: `is`, `is not`
- Examples:
a = [1, 2, 3]
b=a
c = a.copy() # Creates a new list
print(a is b) # Output: True (Same object)
print(a is c) # Output: False (Different objects)
7. Membership Operators
- Used to check if a value is a member of a sequence (like a list, tuple, or string).
- Operators: `in`, `not in`
- Examples:
my_list = [1, 2, 3, 4]
print(2 in my_list) # Output: True
print(5 not in my_list) # Output: True
Operator Precedence
When an expression contains multiple operators, Python follows a specific order of precedence
to determine which operation to perform first. Understanding operator precedence helps prevent
errors in calculations.
- Precedence Order:
1. Parentheses `()`
2. Exponentiation ``
3. Multiplication `*`, Division `/`, Floor Division `//`, Modulus `%`
4. Addition `+`, Subtraction `-`
5. Relational operators `<`, `<=`, `>`, `>=`, `==`, `!=`
6. Logical operators `not`, `and`, `or`
Example of Operator Precedence
result = 3 + 4 * 2 # Multiplication is performed first
print(result) # Output: 11
result = (3 + 4) * 2 # Parentheses evaluated first
print(result) # Output: 14
Operators in Python are essential for performing operations on data. Understanding the different
types of operators and their precedence is crucial for writing effective and correct code. Whether
you're performing arithmetic calculations, making comparisons, or manipulating data, operators
play a key role in the process.
COMMENTS IN PYTHON
What are Comments?
Comments are non-executable text within a program that are meant for human readers. They
help explain the code, making it easier to understand and maintain. Comments can describe what
a piece of code does, why certain decisions were made, or provide additional context.
Types of Comments
● Single-line Comments
● Multi-line Comments
1. Single-line Comments
Syntax: A single-line comment starts with the # symbol.
Usage: Typically used for brief explanations or notes.
Example:
# This is a single-line comment
x = 10 # Assign 10 to variable x
2. Multi-line Comments
Syntax: Multi-line comments can be created using triple quotes, either ''' or """. However, they
are technically string literals that are not assigned to a variable, so they don't function as
comments in the same way as #.
Usage: Useful for longer explanations or documentation.
Example:
"""
This is a multi-line comment.
It can span multiple lines.
"""
y = 20
Best Practices for Writing Comments
Be Clear and Concise: Comments should be easy to read and understand. Avoid overly
technical jargon unless necessary.
Use Comments to Explain Why, Not What: Often, the code itself is self-explanatory regarding
what it does. Focus on why certain decisions were made.
Keep Comments Up-to-Date: Always update comments when code changes. Outdated
comments can be misleading.
Avoid Redundant Comments: Do not comment on every single line or obvious piece of code.
Use comments to clarify complex logic or decisions.
Examples of Effective Comments
Good Comments
# Calculate the area of a circle
def area_of_circle(radius):
return 3.14 * radius ** 2
Poor Comments
x = 10 # Set x to 10
(Here, the comment does not add meaningful information since the code is already clear.)
Comments are an essential part of writing clear and maintainable code in Python. Using them
effectively can greatly improve the readability and understanding of your code for yourself and
others who may work on it in the future.
STATEMENTS IN PYTHON
What is a Statement?
A statement is a unit of code that performs a specific action. In Python, every line of code that
executes an instruction is considered a statement. Statements can be simple (like variable
assignments) or compound (like control flow statements).
Types of Statements
1. Expression Statements
● These evaluate an expression and optionally return a value.
● Example:
x = 10 # Assignment statement
y = x + 5 # Evaluates the expression and assigns the result to y
2. Assignment Statements
● Used to assign a value to a variable.
● Syntax: variable = value
● Example:
name = "Alice"
age = 30
3. Print Statements
● Used to output information to the console.
● Example:
print("Hello, World!")
print("The value of x is:", x)
4. Conditional Statements
● Used for decision-making in the code (if-else structures).
● Syntax:
if condition:
# execute this block
elif another_condition:
# execute this block
else:
# execute this block
● Example:
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
5. Loop Statements
● Used for iterating over a sequence (like a list, tuple, or string).
● Types:
o For Loop:
for i in range(5): # Iterates from 0 to 4
print(i)
o While Loop:
count = 0
while count < 5:
print(count)
count += 1
6. Function Definition Statements
● Define reusable blocks of code (functions).
● Syntax:
def function_name(parameters):
# function body
● Example:
def greet(name):
print(f"Hello, {name}!")
7. Return Statements
● Used to exit a function and optionally pass back a value.
● Example:
def add(a, b):
return a + b
8. Import Statements
● Used to include modules in your code.
● Syntax:
import module_name
from module_name import function_name
● Example:
import math
print(math.sqrt(16)) # Outputs: 4.0
9. Pass Statements
● A null operation; it is used when a statement is syntactically required but no action is
needed.
● Example:
if condition:
pass # Placeholder for future code
Statements are the building blocks of Python programs. They dictate the flow of execution and
how data is manipulated. Understanding different types of statements helps in writing effective
and organized code.
TUPLE ASSIGNMENT
Tuple assignment in Python is a powerful and convenient feature that allows you to assign
multiple values to multiple variables in a single statement. It’s often used for swapping variables
and unpacking values from data structures like tuples and lists.
Tuple Assignment Basics
Syntax:
python
Copy code
a, b = value1, value2
Example:
x, y = 5, 10
print("x =", x) # Output: x = 5
print("y =", y) # Output: y = 10
Key Features of Tuple Assignment
1.Multiple Assignments: You can assign values to multiple variables simultaneously.
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
2.Swapping Values: One of the most common uses of tuple assignment is to swap the values of
two variables without using a temporary variable.
a=5
b = 10
a, b = b, a # Swapping values
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5
3.Unpacking from Data Structures: You can unpack values from a tuple or list directly into
variables.
coordinates = (4, 5)
x, y = coordinates
print("x =", x) # Output: x = 4
print("y =", y) # Output: y = 5
4.Using Underscore for Unused Values: If you have more values than variables, you can use an
underscore (_) to ignore specific values.
python
Copy code
a, _, c = (1, 2, 3)
print("a =", a) # Output: a = 1
print("c =", c) # Output: c = 3
5.Variable Length Tuple Assignment: You can also unpack a variable-length tuple using the *
operator.
values = (1, 2, 3, 4, 5)
first, *middle, last = values
print("first =", first) # Output: first = 1
print("middle =", middle) # Output: middle = [2, 3, 4]
print("last =", last) # Output: last = 5
Example Program
Circulate a,b,c values such that after circulation, a holds the value of b, b holds the value of
c, and c holds the value of a.
a=1
b=2
c=3
# Circular shift
a, b, c = b, c, a
print(“a=”,a)
print(“b=”,b)
print(“c=”,c)