Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python unit 1

The document provides an overview of Python's operator precedence, detailing the order of evaluation for various operators and expressions. It explains the types of expressions in Python, including literals, variables, arithmetic, comparison, logical, and more, along with examples. Additionally, it covers statements, functions, comments, and string manipulation techniques, emphasizing the importance of expressions and their evaluation in Python programming.

Uploaded by

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

Python unit 1

The document provides an overview of Python's operator precedence, detailing the order of evaluation for various operators and expressions. It explains the types of expressions in Python, including literals, variables, arithmetic, comparison, logical, and more, along with examples. Additionally, it covers statements, functions, comments, and string manipulation techniques, emphasizing the importance of expressions and their evaluation in Python programming.

Uploaded by

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

Unit 1 :Python

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'

10. Function Call Expressions


• Call functions to return values.
• Examples:
python
CopyEdit
max(3, 5) #5
len("hello") # 5

11. Generator Expressions


• Create iterators in a concise way.
• Example:
python
CopyEdit
sum(x**2 for x in range(5)) # Sum of squares

12. Lambda Expressions


• Define anonymous functions.
• Syntax:
python
CopyEdit
lambda arguments: expression
• Example:
python
CopyEdit
square = lambda x: x ** 2
print(square(3)) # 9

Evaluation of Expressions
Expressions are evaluated according to operator precedence and associativity. Use
parentheses to explicitly control the order of evaluation.

Example: Mixed Expressions


python
CopyEdit
x = 10
y=5
result = (x + y) * 2 > 25 and x != 0
print(result) # True

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)

print(factorial(5)) # Output: 120

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.

Types of Comments in Python


1. Single-Line Comments
• Begin with a hash symbol (#).
• Everything after the # on the same line is treated as a comment.
• Example:
python
CopyEdit
# This is a single-line comment
x = 10 # This assigns 10 to x
2. Multi-Line Comments
• Python does not have a specific syntax for multi-line comments. However, you can use:
1. Multiple Single-Line Comments:
python
CopyEdit
# This is a multi-line comment
# that spans across multiple lines.
x = 10
2. String Literals (Triple Quotes):
▪ Use triple quotes (''' or """) as a block comment.
▪ These are technically string literals, but if not assigned to a variable or used
as documentation, they are ignored by the interpreter.
▪ Example:
python
CopyEdit
"""
This is a multi-line comment.
It uses triple quotes to span multiple lines.
"""
x = 10

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"

# Triple-quoted string (for multi-line strings)


string3 = '''This
is
a
multi-line string.'''

Accessing Values in Strings


1. Indexing
• Strings can be indexed to access individual characters.
• Indexing starts at 0 for the first character and goes negative for indexing from the end.
Examples:
python
CopyEdit
s = "Python"

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

# Slice from index 0 to 3 (exclusive)


print(s[0:3]) # 'Pyt'

# Slice from index 2 to the end


print(s[2:]) # 'thon'

# Slice from the beginning to index 4 (exclusive)


print(s[:4]) # 'Pyth'

# Slice with a step of 2


print(s[0:6:2]) # 'Pto'

# Reverse the string using slicing


print(s[::-1]) # 'nohtyP'

3. Accessing Characters in a Loop


You can iterate through a string using a loop.
python
CopyEdit
s = "Python"

for char in s:
print(char)

Key Points About Strings


1. Strings are immutable:
o You cannot modify a string directly.
o Instead, create a new string if changes are needed.
python
CopyEdit
s = "Hello"
# s[0] = 'h' # Error: Strings are immutable
s = "hello" # Create a new string
2. Strings are iterable:
o You can use loops and comprehensions to process strings.
3. Strings support rich methods:
o Examples include len(), upper(), lower(), find(), etc.

Examples Combining Access Methods


python
CopyEdit
s = "Programming"

# Access the first and last character


first_char = s[0] # 'P'
last_char = s[-1] # 'g'

# Slice the first 4 characters


first_four = s[:4] # 'Prog'

# Get every second character


every_second = s[::2] # 'Pormig'

# Reverse the string


reversed_str = s[::-1] # 'gnimmargorP'

# Loop through the string


for char in s:
print(char, end=" ") # 'P r o g r a m m i n g'
By mastering indexing, slicing, and iteration, you can effectively manipulate and extract data
from strings in Python!
In Python, escape characters are special sequences used to include characters in a string that
would otherwise cause errors or have a different meaning. Escape characters begin with a
backslash (\), followed by a specific character to represent the desired literal or formatting.

Common Escape Characters in Python


Escape
Description Example Result
Sequence
"This is a backslash:
\\ Backslash (\) This is a backslash: \
\\\\"
\' Single quote (') 'It\'s Python!' It's Python!
\" Double quote (") "He said, \"Hi!\"" He said, "Hi!"
Hello
\n Newline "Hello\nWorld"
World
\t Horizontal tab "Name:\tJohn" Name: John
World (overwrites
\r Carriage return "Hello\rWorld"
Hello)
\b Backspace "Helloo\b" Hello
\f Form feed "Line1\fLine2" Line1 (page break)
\v Vertical tab "Column1\vColumn2" Column alignment
\ooo Octal value (e.g., \141) "\141\142\143" abc
Hexadecimal value (e.g.,
\xhh "\x61\x62\x63" abc
\x61)
\uXXXX Unicode character (16-bit) "\u00A9" ©
\UXXXXXXXX Unicode character (32-bit) "\U0001F600" (Unicode emoji)

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

# Multiple input calls


first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
print(f"Full Name: {first_name} {last_name}")
4. Numeric Input
Convert the string to an integer or float if numerical input is expected:
python
CopyEdit
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"The sum is: {num1 + num2}")

You might also like