Python unit 1
Python unit 1
In Python, operator precedence determines the order in which operations are evaluated in
expressions. Operators with higher precedence are evaluated before operators with lower
precedence. If operators have the same precedence, their associativity (left-to-right or right-to-
left) determines the order of evaluation.
Here is the precedence table in descending order (from highest to lowest):
1. Parentheses
• () — Grouping expressions.
• Example: (2 + 3) * 4 evaluates to 20, not 14.
2. Exponentiation
• ** — Exponentiation (right-to-left associativity).
• Example: 2 ** 3 ** 2 is 2 ** (3 ** 2) = 2 ** 9 = 512.
3. Unary Operators
• +, -, ~ — Unary plus, unary minus, bitwise NOT.
• Example: -5 + 3 evaluates to -2.
4. Multiplicative Operators
• *, /, //, % — Multiplication, division, floor division, modulus.
• Example: 10 / 5 * 2 evaluates to 4.0 (left-to-right associativity).
5. Additive Operators
• +, - — Addition and subtraction.
• Example: 5 - 2 + 3 evaluates to 6.
6. Bitwise Shift Operators
• <<, >> — Left shift, right shift.
• Example: 4 << 2 evaluates to 16.
7. Bitwise AND
• & — Bitwise AND.
• Example: 5 & 3 evaluates to 1.
8. Bitwise XOR
• ^ — Bitwise XOR.
• Example: 5 ^ 3 evaluates to 6.
9. Bitwise OR
• | — Bitwise OR.
• Example: 5 | 3 evaluates to 7.
10. Comparison Operators
• <, <=, >, >=, !=, == — Comparisons.
• Example: 5 > 3 == True evaluates to True.
11. Identity and Membership Operators
• is, is not, in, not in — Identity and membership checks.
• Example: 'a' in 'apple' evaluates to True.
12. Logical NOT
• not — Logical negation.
• Example: not True evaluates to False.
13. Logical AND
• and — Logical AND.
• Example: True and False evaluates to False.
14. Logical OR
• or — Logical OR.
• Example: True or False evaluates to True.
15. Assignment Operators
• =, +=, -=, *=, /=, //=, %= — Assignments.
• Example: x += 3 means x = x + 3.
16. Lambda Expressions
• lambda — Anonymous function definitions (lowest precedence).
• Example: lambda x: x + 2.
In Python, operator precedence determines the order in which operations are evaluated in
expressions. Operators with higher precedence are evaluated before operators with lower
precedence. If operators have the same precedence, their associativity (left-to-right or right-to-
left) determines the order of evaluation.
Here is the precedence table in descending order (from highest to lowest):
1. Parentheses
• () — Grouping expressions.
• Example: (2 + 3) * 4 evaluates to 20, not 14.
2. Exponentiation
• ** — Exponentiation (right-to-left associativity).
• Example: 2 ** 3 ** 2 is 2 ** (3 ** 2) = 2 ** 9 = 512.
3. Unary Operators
• +, -, ~ — Unary plus, unary minus, bitwise NOT.
• Example: -5 + 3 evaluates to -2.
4. Multiplicative Operators
• *, /, //, % — Multiplication, division, floor division, modulus.
• Example: 10 / 5 * 2 evaluates to 4.0 (left-to-right associativity).
5. Additive Operators
• +, - — Addition and subtraction.
• Example: 5 - 2 + 3 evaluates to 6.
6. Bitwise Shift Operators
• <<, >> — Left shift, right shift.
• Example: 4 << 2 evaluates to 16.
7. Bitwise AND
• & — Bitwise AND.
• Example: 5 & 3 evaluates to 1.
8. Bitwise XOR
• ^ — Bitwise XOR.
• Example: 5 ^ 3 evaluates to 6.
9. Bitwise OR
• | — Bitwise OR.
• Example: 5 | 3 evaluates to 7.
10. Comparison Operators
• <, <=, >, >=, !=, == — Comparisons.
• Example: 5 > 3 == True evaluates to True.
11. Identity and Membership Operators
• is, is not, in, not in — Identity and membership checks.
• Example: 'a' in 'apple' evaluates to True.
12. Logical NOT
• not — Logical negation.
• Example: not True evaluates to False.
13. Logical AND
• and — Logical AND.
• Example: True and False evaluates to False.
14. Logical OR
• or — Logical OR.
• Example: True or False evaluates to True.
15. Assignment Operators
• =, +=, -=, *=, /=, //=, %= — Assignments.
• Example: x += 3 means x = x + 3.
16. Lambda Expressions
• lambda — Anonymous function definitions (lowest precedence).
• Example: lambda x: x + 2.
Expressions in python
In Python, an expression is a combination of values, variables, operators, and function calls that
Python evaluates to produce a value. Expressions are the building blocks of any Python
program.
Here’s a detailed breakdown of expressions in Python:
1. Literals
• Basic values like numbers, strings, booleans, etc.
• Examples:
python
42 # Integer literal
3.14 # Floating-point literal
'Hello' # String literal
True # Boolean literal
2. Variables
• Names representing values.
• Examples:
python
x = 10
y = x + 5 # 'x + 5' is an expression
3. Arithmetic Expressions
• Combine numbers using arithmetic operators.
• Examples:
python
3+5 # Addition
10 - 3 # Subtraction
2*3 # Multiplication
9/2 # Division (float result)
9 // 2 # Floor division (integer result)
7%3 # Modulus (remainder)
2 ** 3 # Exponentiation
4. Comparison Expressions
• Compare values and return a boolean (True or False).
x == y # Equal to
x != y # Not equal to
x>y # Greater than
x<y # Less than
x >= y # Greater than or equal to
x <= y # Less than or equal to
5. Logical Expressions
• Combine boolean values using logical operators.
• Examples:
python
CopyEdit
not True # Negation
True and False # Logical AND
True or False # Logical OR
6. Bitwise Expressions
• Work at the bit level.
• Examples:
python
CopyEdit
5 & 3 # Bitwise AND
5 | 3 # Bitwise OR
5 ^ 3 # Bitwise XOR
5 << 1 # Left shift
5 >> 1 # Right shift
7. Membership Expressions
• Test membership in sequences (like lists, strings, etc.).
• Examples:
python
CopyEdit
'a' in 'apple' # True
5 not in [1, 2, 3] # True
8. Identity Expressions
• Compare object identity.
• Examples:
python
CopyEdit
x is y # True if x and y are the same object
x is not y # True if x and y are different objects
9. Conditional Expressions
• Use the ternary operator to evaluate conditions.
• Syntax:
python
CopyEdit
value_if_true if condition else value_if_false
• Example:
python
CopyEdit
x = 10
result = 'Positive' if x > 0 else 'Non-positive'
Evaluation of Expressions
Expressions are evaluated according to operator precedence and associativity. Use
parentheses to explicitly control the order of evaluation.
Expressions are fundamental in Python and form the basis of statements, allowing you to
perform computations, make decisions, and build logic.
1. Statements
A statement is an instruction that Python can execute. Statements perform actions like
assigning values, controlling flow, or calling functions.
Types of Statements
a. Assignment Statement
• Used to assign a value to a variable.
• Syntax:
variable_name = value
• Example:
x = 10
name = "Alice"
b. Expression Statement
• Executes an expression but doesn’t store the result.
• Example:
python
print("Hello, World!") # Calling a function
c. Control Flow Statements
• Used for decision-making and loops.
1. Conditional Statements (if, elif, else):
python
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
2. Looping Statements:
o for Loop:
python
for i in range(5):
print(i)
while Loop:
python
count = 0
while count < 5:
print(count)
count += 1
d. Import Statement
• Used to import modules.
• Example:
python
CopyEdit
import math
from datetime import datetime
e. Pass Statement
• A placeholder that does nothing.
• Example:
python
CopyEdit
def function():
pass # To be implemented later
f. Return Statement
• Used in functions to send a value back to the caller.
• Example:
python
CopyEdit
def add(a, b):
return a + b
g. Break and Continue Statements
• Control loop execution.
• Example:
python
CopyEdit
for i in range(5):
if i == 3:
break # Exit the loop
print(i)
for i in range(5):
if i == 2:
continue # Skip the current iteration
print(i)
2. Functions
A function is a block of reusable code that performs a specific task. Functions make programs
modular and easier to maintain.
Function Types
a. Built-in Functions
• Python provides a library of built-in functions.
• Examples:
python
CopyEdit
len("Hello") # Returns the length of a string
max(3, 7, 5) # Returns the maximum value
b. User-defined Functions
• Functions defined by the programmer.
• Syntax:
python
CopyEdit
def function_name(parameters):
# Function body
return value # Optional
• Example:
python
CopyEdit
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
c. Lambda Functions
• Anonymous functions defined using the lambda keyword.
• Syntax:
python
CopyEdit
lambda arguments: expression
• Example:
python
CopyEdit
square = lambda x: x ** 2
print(square(4)) # Output: 16
d. Recursive Functions
• Functions that call themselves.
• Example:
python
CopyEdit
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
Function Components
1. Function Definition: Using the def keyword.
2. Parameters: Variables in parentheses that accept input.
3. Return Statement: Sends the result back to the caller.
4. Docstring (Optional): A string that documents the function.
In Python, a string is a sequence of characters enclosed in either single quotes ('), double quotes
("), or triple quotes (''' or """"). Strings are immutable, meaning their content cannot be changed
once created.
String Basics
Creating Strings
python
CopyEdit
# Single-quoted string
string1 = 'Hello'
# Double-quoted string
string2 = "World"
# Positive indexing
print(s[0]) # 'P'
print(s[3]) # 'h'
# Negative indexing
print(s[-1]) # 'n' (last character)
print(s[-3]) # 'h'
2. Slicing
• Slicing is used to access a substring by specifying a range of indices.
• Syntax: string[start:end:step]
o start: Starting index (inclusive).
o end: Ending index (exclusive).
o step: Step size (optional).
Examples:
python
CopyEdit
s = "Python"
for char in s:
print(char)
Python provides several built-in string functions that allow you to manipulate and work with
strings efficiently. Here's a summary of commonly used string functions:
1. String Case Methods
• str.capitalize(): Capitalizes the first character of the string.
• str.lower(): Converts all characters to lowercase.
• str.upper(): Converts all characters to uppercase.
• str.title(): Converts the string to title case (first letter of each word is capitalized).
• str.swapcase(): Swaps the case of all characters in the string.
In Python, you can get user input as a string using the input() function. Here's a quick
explanation and some examples:
Basic Usage
The input() function reads a line of text entered by the user and returns it as a string.
Example Use Cases
1. Simple Input
python
CopyEdit
age = input("Enter your age: ")
print(f"You are {age} years old!")
2. Input Validation
You can validate or process the input if needed:
python
CopyEdit
number = input("Enter a number: ")
if number.isdigit():
print(f"The square of {number} is {int(number) ** 2}")
else:
print("That's not a valid number!")
3. Multiple Inputs
You can accept multiple inputs using split() or by calling input() multiple times:
python
CopyEdit
# Using split() for space-separated values
data = input("Enter your first name, last name, and age (separated by spaces): ").split()
first_name, last_name, age = data
print(f"Name: {first_name} {last_name}, Age: {age}")