Python Units
Python Units
Python Interpreter/Shell
• Definition: The Python interpreter is the program that reads and executes Python
code. The shell (or REPL - Read-Eval-Print Loop) is an interactive environment where
you can execute Python commands line by line.
• Code:
python
Copy code
>>> print("Hello, Python!") # Executes directly in the Python shell
Hello, Python!
• Key Points:
o Allows real-time execution and feedback.
o Useful for testing small pieces of code quickly.
2. Identifiers
3. Keywords
• Definition: Reserved words in Python that have predefined meanings and cannot be
used as identifiers.
• Examples: if, else, while, for, def, class, etc.
• Code:
python
Copy code
if x == 10:
print("x is 10")
5. Variables
6. Operators
• Definition: Precedence determines the order in which operators are evaluated, and
associativity determines the direction of evaluation when two operators have the
same precedence.
• Example:
python
Copy code
result = 5 + 2 * 3 # Multiplication (*) has higher precedence than
addition (+)
8. Data Types
• Definition: Categories of data that tell the interpreter how the programmer intends
to use the data.
• Common Data Types:
o int, float, str, list, tuple, dict, bool
• Example:
python
Copy code
x = 10 # int
y = 10.5 # float
z = "Hello" # str
9. Indentation
10. Comments
15. is operator
a. The if Statement
b. if-else Statement
• Definition: Executes one block if the condition is true, otherwise executes the else
block.
• Example:
python
Copy code
if x > 10:
print("x is greater")
else:
print("x is smaller")
c. if-elif-else Statement
d. Nested if Statement
e. while Loop
f. for Loop
Functions
1. Built-In Functions
• Definition: Python provides several built-in functions that perform common tasks
without needing to import any module.
• Examples: print(), len(), input(), type(), int(), str(), etc.
• Example Code:
python
Copy code
print(len("Hello")) # Output: 5
print(type(10)) # Output: <class 'int'>
• Key Points:
o Available globally in Python.
o No need to define or import; they come with Python by default.
• Definition: Python has many standard library modules that provide additional
functionality. You can import these modules using the import statement.
• Common Modules:
o math: Provides mathematical functions.
o random: Generates random numbers.
o datetime: Manages date and time.
o os: Interacts with the operating system.
• Example Code:
python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
import random
print(random.randint(1, 10)) # Random number between 1 and 10
python
Copy code
def function_name(parameters):
# Block of code
return value # Optional
• Example Code:
python
Copy code
def greet(name):
return "Hello, " + name
• Key Points:
o Functions can take parameters and return values.
o Functions can be called multiple times to avoid code repetition.
• Definition: The return statement is used to send back a result from a function to
the caller. A function that doesn’t return a value is called a void function.
• Example Code:
python
Copy code
def add(a, b):
return a + b
def print_message():
print("This is a void function") # No return value
• Key Points:
o Non-void functions return values, while void functions return None.
• Definition:
o Scope: Refers to the region where a variable is accessible (e.g., local or
global).
o Lifetime: Refers to how long a variable exists in memory.
• Example Code:
python
Copy code
def my_func():
x = 10 # Local scope, only accessible within the function
• Key Points:
o Local variables exist within a function and are deleted after the function
execution.
o Global variables exist throughout the entire program.
6. Default Parameters
• Definition: Parameters in a function can have default values, which are used if no
argument is passed during the function call.
• Example Code:
python
Copy code
def greet(name="Guest"):
return "Hello, " + name
• Key Points:
o Default parameters must appear after non-default parameters.
o Great for making functions flexible and easy to use.
python
Copy code
import sys
print(sys.argv) # sys.argv[0] is the script name, sys.argv[1:] are
the passed arguments
• Key Points:
o Useful for making programs accept input when they are run.
Strings
python
Copy code
my_string = "Hello, World"
multiline_string = '''This
is a
multiline string'''
• Key Points:
o Strings are immutable (cannot be changed after creation).
python
Copy code
name = "Alice"
greeting = "Hello, " + name # Concatenation
print(greeting * 3) # Repetition: "Hello, AliceHello, AliceHello,
Alice"
• Key Points:
o Strings can be combined and repeated easily.
o Strings are zero-indexed.
• Definition: You can access individual characters in a string using indexing (starting
from 0).
• Example Code:
python
Copy code
word = "Python"
print(word[0]) # Output: P
print(word[-1]) # Output: n (negative indexing)
• Key Points:
o Use positive indices to count from the start, and negative indices to count
from the end.
python
Copy code
word = "Python"
print(word[1:4]) # Output: yth (slice from index 1 to 3)
• Key Points:
o Slicing allows you to extract substrings.
o join() method efficiently joins list elements into a single string.
5. String Methods
python
Copy code
text = " Hello, World "
print(text.strip()) # Output: "Hello, World"
print(text.upper()) # Output: " HELLO, WORLD "
print(text.replace("World", "Python")) # Output: " Hello, Python "
• Key Points:
o String methods do not modify the original string (strings are immutable).
o Methods return a new string with the applied change.
Summary:
Unit 3
Lists
1. Creating Lists
• Key Points:
o Lists can contain elements of different data types.
o Lists are mutable (can be changed).
• Indexing: Access elements using indices (starting at 0). Negative indices access
elements from the end.
• Slicing: Extract a portion of the list using [start:stop:step].
• Example:
python
Copy code
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1 (First element)
print(my_list[-1]) # Output: 5 (Last element)
• Common Functions:
o len(): Returns the number of elements.
o max(), min(): Returns the maximum and minimum elements.
o sum(): Returns the sum of elements (if all are numeric).
• Example:
python
Copy code
my_list = [1, 2, 3, 4]
print(len(my_list)) # Output: 4
print(max(my_list)) # Output: 4
print(sum(my_list)) # Output: 10
5. List Methods
• Common Methods:
o append(): Adds an element at the end.
o insert(): Inserts an element at a specific position.
o remove(): Removes the first occurrence of a value.
o pop(): Removes and returns the element at the given index (last element by
default).
o sort(): Sorts the list in ascending order.
• Example:
python
Copy code
my_list = [3, 1, 4, 2]
my_list.append(5)
print(my_list) # Output: [3, 1, 4, 2, 5]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4, 5]
• Definition: Deletes elements from a list at a specified index or the entire list.
• Example:
python
Copy code
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Deletes element at index 2
print(my_list) # Output: [1, 2, 4, 5]
Dictionaries
1. Creating Dictionaries
python
Copy code
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
empty_dict = {}
• Key Points:
o Keys must be immutable (strings, numbers, or tuples).
o Dictionaries are unordered and mutable.
• Common Functions:
o len(): Returns the number of key-value pairs.
o keys(): Returns a view object of dictionary keys.
o values(): Returns a view object of dictionary values.
o items(): Returns a view object of dictionary key-value pairs.
• Example:
python
Copy code
print(len(my_dict)) # Output: 3
print(list(my_dict.keys())) # Output: ['name', 'age', 'city']
print(list(my_dict.values())) # Output: ['Alice', 26, 'New York']
4. Dictionary Methods
• Common Methods:
o get(): Returns the value for a given key, or None if the key doesn’t exist.
o update(): Updates the dictionary with key-value pairs from another
dictionary.
o pop(): Removes a key-value pair by key.
• Example:
python
Copy code
my_dict = {"name": "Alice", "age": 25}
print(my_dict.get("name")) # Output: Alice
my_dict.update({"city": "New York"})
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New
York'}
Tuples
1. Creating Tuples
•Common Functions:
o len(): Returns the length of the tuple.
o max(), min(): Returns the maximum or minimum element (if numeric).
o sum(): Returns the sum of elements.
• Example:
python
Copy code
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3
print(sum(my_tuple)) # Output: 6
• Similarities: Both are ordered and can contain elements of any type.
• Difference: Lists are mutable, while tuples are immutable.
• Similarities: Tuples can be used as dictionary keys because they are immutable.
• Difference: Dictionaries are key-value pairs, whereas tuples are simple ordered
collections.
7. Tuple Methods
•Common Methods:
o count(): Returns the number of occurrences of a value.
o index(): Returns the index of a value.
• Example:
python
Copy code
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # Output: 2
print(my_tuple.index(3)) # Output: 3
Sets
1. Creating Sets
2. Set Methods
•Common Methods:
o add(): Adds an element to the set.
o remove(): Removes an element from the set.
o union(): Returns the union of two sets.
o intersection(): Returns the intersection of two sets.
• Example:
python
Copy code
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}
3. Frozen Set
Summary:
• Lists: Mutable, ordered collections that allow for indexing, slicing, and various built-
in functions.
• Dictionaries: Unordered, mutable collections of key-value pairs with powerful
methods.
• Tuples: Immutable, ordered collections, often used for fixed data sets.
• Sets: Unordered collections of unique elements, with efficient membership testing
and set operations. Frozen sets provide immutable sets