0% found this document useful (0 votes)
10 views

Python Units

Uploaded by

racaf53971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Units

Uploaded by

racaf53971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Unit 1

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

• Definition: Identifiers are names given to variables, functions, classes, etc.


• Rules:
o Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
o Must not start with a digit.
o Python is case-sensitive (myVar and myvar are different).
• Example:
python
Copy code
my_var = 10 # "my_var" is an identifier

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")

4. Statements and Expressions

• Statements: A line of code that performs an action.


• Expressions: A combination of variables, operators, and values that produce a
result.
• Example:
python
Copy code
x = 5 # Statement
y = x + 2 # Expression

5. Variables

• Definition: Containers for storing data values.


• Example:
python
Copy code
age = 25 # age is a variable

6. Operators

• Definition: Symbols that perform operations on variables and values.


• Types:
o Arithmetic: +, -, *, /, etc.
o Comparison: ==, !=, <, >, etc.
o Logical: and, or, not.
• Example:
python
Copy code
a = 5
b = 3
result = a + b # Addition (result is 8)

7. Precedence and Associativity

• 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

• Definition: Python uses indentation to define the scope of loops, functions,


classes, etc.
• Example:
python
Copy code
if x > 10:
print("x is greater than 10") # Indented block

10. Comments

• Definition: Used to add notes in code that are not executed.


• Types: Single-line comments (#), multi-line comments (triple quotes """ or ''').
• Example:
python
Copy code
# This is a single-line comment
print("Hello") # Inline comment

11. Reading Input

• Definition: Using input() to read user input.


• Example:
python
Copy code
name = input("Enter your name: ")
print("Hello, " + name)

12. Print Output

• Definition: The print() function is used to display output.


• Example:
python
Copy code
print("Hello, World!")

13. Type Conversions

• Definition: Converting between different data types.


• Example:
python
Copy code
x = int("10") # Converts string to integer
y = str(10) # Converts integer to string

14. type() function

• Definition: Returns the type of an object.


• Example:
python
Copy code
print(type(10)) # <class 'int'>

15. is operator

• Definition: Checks if two variables point to the same object (identity).


• Example:
python
Copy code
x = [1, 2, 3]
y = x
print(x is y) # True (same object)
16. Dynamic and Strongly Typed Language

• Dynamic: Python determines the type of a variable at runtime.


• Strong: Python doesn’t implicitly convert types when performing operations.
• Example:
python
Copy code
x = "5"
y = 10
# x + y # TypeError: cannot add str and int

17. Control Flow Statements

a. The if Statement

• Definition: Executes a block of code if the condition is true.


• Example:
python
Copy code
if x > 10:
print("x is greater than 10")

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

• Definition: Multiple conditions are checked in sequence.


• Example:
python
Copy code
if x > 10:
print("x is greater")
elif x == 10:
print("x is 10")
else:
print("x is smaller")

d. Nested if Statement

• Definition: if statements inside another if.


• Example:
python
Copy code
if x > 10:
if x < 20:
print("x is between 10 and 20")

e. while Loop

• Definition: Repeats a block of code as long as the condition is true.


• Example:
python
Copy code
while x < 10:
print(x)
x += 1

f. for Loop

• Definition: Iterates over a sequence (like a list or string).


• Example:
python
Copy code
for i in range(5):
print(i)

g. continue and break Statements

• continue: Skips the current iteration.


• break: Exits the loop entirely.
• Example:
python
Copy code
for i in range(5):
if i == 3:
continue # Skip 3
print(i)
Unit 2

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.

2. Commonly Used Modules

• 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

3. Function Definition and Calling the Function

• Definition: Functions allow us to group a block of code, which can be reused.


Define a function using the def keyword.
• Syntax:

python
Copy code
def function_name(parameters):
# Block of code
return value # Optional

• Example Code:

python
Copy code
def greet(name):
return "Hello, " + name

print(greet("Alice")) # Output: Hello, Alice

• Key Points:
o Functions can take parameters and return values.
o Functions can be called multiple times to avoid code repetition.

4. The return Statement and Void Function

• 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.

5. Scope and Lifetime of Variables

• 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

y = 20 # Global scope, accessible everywhere in the script

• 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

print(greet()) # Output: Hello, Guest


print(greet("Alice")) # Output: Hello, Alice

• Key Points:
o Default parameters must appear after non-default parameters.
o Great for making functions flexible and easy to use.

7. Command Line Arguments

• Definition: Arguments provided to a Python script at runtime from the command


line.
• How to Use: The sys module provides access to command line arguments through
sys.argv.
• Example Code:

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

1. Creating and Storing Strings

• Definition: Strings in Python are sequences of characters enclosed in single


quotes, double quotes, or triple quotes.
• Example Code:

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).

2. Basic String Operations

• Concatenation: Joining strings using the + operator.


• Repetition: Repeating a string using the * operator.
• Example Code:

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.

3. Accessing Characters in String by Index Number

• 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.

4. String Slicing and Joining

• Slicing: Extract a portion of a string using [start:stop:step] syntax.


• Joining: Combine elements of a list into a string using join().
• Example Code:

python
Copy code
word = "Python"
print(word[1:4]) # Output: yth (slice from index 1 to 3)

words = ["Hello", "World"]


print(" ".join(words)) # Output: "Hello World"

• Key Points:
o Slicing allows you to extract substrings.
o join() method efficiently joins list elements into a single string.

5. String Methods

• Definition: Python provides a variety of built-in string methods for manipulation.


• Common Methods:
o upper(): Converts string to uppercase.
o lower(): Converts string to lowercase.
o strip(): Removes leading and trailing whitespace.
o replace(): Replaces a substring with another string.
o find(): Returns the index of a substring.
• Example Code:

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:

• Functions: Functions provide reusable blocks of code. Python supports built-in


functions, custom functions, and provides flexible function parameters (default
parameters). Understanding scope and lifetime of variables is key when working
with functions.
• Strings: Python strings are sequences of characters, supporting various operations
like indexing, slicing, and methods for modification. Understanding immutability
and mastering string manipulation methods is crucial for working with text in
Python.

Unit 3

Lists

1. Creating Lists

• Definition: A list is a collection of ordered, mutable items in Python. Lists are


defined by square brackets [].
• Example:
python
Copy code
my_list = [1, 2, 3, "apple", 4.5]
empty_list = []

• Key Points:
o Lists can contain elements of different data types.
o Lists are mutable (can be changed).

2. Basic List Operations

• Concatenation: Lists can be combined using +.


• Repetition: Lists can be repeated using *.
• Membership: Use in to check if an item is in the list.
• Length: Use len() to find the number of items.
• Example:
python
Copy code
my_list = [1, 2, 3]
new_list = my_list + [4, 5] # Concatenation
print(new_list) # Output: [1, 2, 3, 4, 5]

repeated_list = my_list * 2 # Repetition


print(repeated_list) # Output: [1, 2, 3, 1, 2, 3]

print(2 in my_list) # Output: True (Membership)


print(len(my_list)) # Output: 3 (Length)

3. Indexing and Slicing in Lists

• 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)

sliced_list = my_list[1:4] # Slicing from index 1 to 3


print(sliced_list) # Output: [2, 3, 4]

4. Built-In Functions Used on Lists

• 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]

6. The del Statement

• 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]

del my_list # Deletes the entire list

Dictionaries

1. Creating Dictionaries

• Definition: A dictionary is a collection of key-value pairs, where each key is unique.


Dictionaries are defined by curly braces {}.
• Example:

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.

2. Accessing and Modifying Key-Value Pairs

• Accessing: Use keys to access values.


• Modifying: Assign new values to existing keys.
• Example:
python
Copy code
print(my_dict["name"]) # Output: Alice

my_dict["age"] = 26 # Modifying the value of 'age'


print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New
York'}

3. Built-In Functions Used on Dictionaries

• 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'}

5. The del Statement

• Definition: Deletes a key-value pair or the entire dictionary.


• Example:
python
Copy code
del my_dict["age"] # Deletes the key 'age'
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}

del my_dict # Deletes the entire dictionary

Tuples and Sets

Tuples

1. Creating Tuples

•Definition: A tuple is an immutable, ordered collection of elements, defined by


parentheses ().
• Example:
python
Copy code
my_tuple = (1, 2, 3, "apple")
single_element_tuple = (1,)

2. Basic Tuple Operations

• Concatenation: Combine tuples using +.


• Repetition: Repeat tuples using *.
• Example:
python
Copy code
new_tuple = (1, 2) + (3, 4) # Output: (1, 2, 3, 4)
repeated_tuple = (1, 2) * 2 # Output: (1, 2, 1, 2)

3. Indexing and Slicing in Tuples

• Indexing: Access elements by index, starting from 0.


• Slicing: Extract a portion using [start:stop:step].
• Example:
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1]) # Output: 2
print(my_tuple[1:4]) # Output: (2, 3, 4)

4. Built-In Functions Used on 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

5. Relations between Tuples and Lists

• Similarities: Both are ordered and can contain elements of any type.
• Difference: Lists are mutable, while tuples are immutable.

6. Relations between Tuples and Dictionaries

• 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

8. Using zip() Function

• Definition: Combines multiple sequences into tuples.


• Example:
python
Copy code
names = ["Alice", "Bob"]
ages = [25, 30]
zipped = list(zip(names, ages)) # Output: [('Alice', 25), ('Bob',
30)]

Sets

1. Creating Sets

•Definition: A set is an unordered collection of unique elements, defined by curly


braces {}.
• Example:
python
Copy code
my_set = {1, 2, 3, 4}
empty_set = set()

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

• Definition: A frozen set is an immutable set.


• Example:
python
Copy code
frozen_set = frozenset([1, 2, 3])
print(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

You might also like