0% found this document useful (0 votes)
3 views19 pages

Unit 2 - Python Programming

The document covers essential concepts in Python programming, including decision making, loops, functions, strings, and regular expressions. It explains various control statements, types of functions, and string manipulation techniques, along with the use of regex for pattern matching and validation. Each section provides examples and descriptions to facilitate understanding of these programming fundamentals.

Uploaded by

Ayush Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Unit 2 - Python Programming

The document covers essential concepts in Python programming, including decision making, loops, functions, strings, and regular expressions. It explains various control statements, types of functions, and string manipulation techniques, along with the use of regex for pattern matching and validation. Each section provides examples and descriptions to facilitate understanding of these programming fundamentals.

Uploaded by

Ayush Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Unit 2: Decision Making, Looping, Functions, Strings, Regular Expressions

1. Decision Making
➔​ What is Decision Making in Python?
Decision making in Python refers to the ability of a program to make choices and execute
different blocks of code based on certain conditions.

➡️
In simple terms:
It allows your program to "decide what to do" when a condition is True or False.

1.1 if Statements
●​ An if statement in Python is used to execute a block of code only when a specific
condition is True.
●​ If the condition is False, the block is skipped and nothing happens.
1.2 if-else Statement
●​ Allows you to execute one block of code if the condition is True, and another block else
part if the condition is False.

1.3 if-elif-else Statement


●​ Used when there are multiple conditions to check in sequence, executing the block
corresponding to the first True condition.

1.4 Nested if Statement


●​ An if statement placed inside another if, used when further decision-making depends on a
previous condition.
2. Loops in Python - For, While and Nested Loops
●​ Loops help you repeat a block of code multiple times without rewriting it. This makes
programs efficient and reduces errors.
●​ Types of Loops:
○​ For loop: Repeats code for each item in a sequence or range.
○​ While loop: Repeats code as long as a condition is true.
○​ Nested loops: A loop inside another loop, useful for complex repetitions.

2.1 For loop


●​ Use a for loop to run code repeatedly for each item in a sequence (like a list or numbers
in a range).

2.2 While loop


●​ Use a while loop to repeat a block as long as a condition remains True.
2.3 Nested Loops
●​ Nested loops are loops inside other loops. They let you repeat actions over multiple
dimensions (like rows and columns).

3. Loop Control Statements


●​ Loop control statements help you change the flow of loops — you can stop a loop early,
skip some steps, or add placeholders.
●​ Python provides three primary control statements: continue, break, and pass.

3.1 break statement


●​ The break statement is used to exit the loop prematurely (before it’s time) when a certain
condition is met.
3.2 continue statement
●​ The continue statement skips the current iteration and proceeds to the next iteration of the
loop.

3.3 pass statement


●​ The pass statement is a null operation; it does nothing when executed. It's useful as a
placeholder for code that you plan to write in the future.
4. Math and Random Functions in Python
●​ Python provides built-in modules like math and random for mathematical operations and
random number generation.
●​ Before using these functions, you need to import the modules:

4.1 Math Functions (from math module)


●​ These are used for advanced mathematical calculations like square roots, powers,
rounding, etc.

4.1.1. math.sqrt(x)
●​ Returns the square root of x.

4.1.2. math.pow(x, y)
●​ Returns x raised to the power y (i.e., x^y).

4.1.3. math.sqrt(x)
●​ Rounds a decimal number down to the nearest whole number.
4.1.4. math.ceil(x)
●​ Rounds a decimal number up to the nearest whole number.

4.2 Random Functions (from random module)


●​ These are used to generate random numbers, choices, or shuffle data — useful in games,
simulations, etc.

4.2.1. random.randint(a, b)
●​ Returns a random integer between a and b (inclusive).

4.2.2. random.choice(sequence)
●​ Returns a random element from a list or sequence.

4.2.3. random.random()
●​ Returns a random float between 0.0 and 1.0.
4.1.4. random.shuffle(list)
●​ Shuffles the items in a list randomly (in-place).

5. Python Functions
➔​ What is a Function?
◆​ A function in Python is a block of code that does a specific job.
◆​ Instead of writing the same code again and again, we write it once inside a
function and reuse it whenever needed by calling the function.
◆​ Benefits:
●​ Increases code readability
●​ Promotes code reusability
5.1 Types of Functions
Below are the different types of functions in Python:
●​ Built-in library(Predefined) function: These are Standard functions in Python that are
available to use. Example:- Predefined (e.g., len(), print())
●​ User-defined function: We can create our own functions based on our requirements.
Functions defined by the user using def

5.2 Types of Python Function Arguments


●​ Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following function argument types in Python:
○​ Default argument
○​ Keyword arguments (named arguments)
○​ Positional arguments
○​ Arbitrary arguments (variable-length arguments *args)
5.2.1 Default Arguments
●​ A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument.
●​ The following example illustrates Default arguments to write functions in Python.

5.2.2 Keyword Arguments


●​ The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters.
5.2.3 Positional Arguments
●​ We used the Position argument during the function call so that the first argument (or
value) is assigned to name and the second argument (or value) is assigned to age.
●​ By changing the position, or if you forget the order of the positions, the values can be
used in the wrong places, as shown in the Case-2 example below, where 27 is assigned to
the name and Suraj is assigned to the age.

5.2.4 Arbitrary Keyword Arguments


●​ In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special symbols:
○​ *args in Python (Non-Keyword Arguments)
○​ **kwargs in Python (Keyword Arguments)
6. Strings in Python
●​ A string is a sequence of characters enclosed within single (' ') or double (" ") quotes.
●​ Strings are immutable, meaning once created, they cannot be changed.
●​ String formatting allows embedding variables inside strings in a readable way.

6.1 String Formatting Methods:


6.2 String Comparison in Python
●​ Strings can be compared using relational operators (==, !=, <, >, <=, >=).
●​ Comparison is based on lexicographical (dictionary) order and Unicode values.
●​ Note:
○​ 'A' to 'Z': 65–90
○​ 'a' to 'z': 97–122
●​ Use Case:
○​ String comparison is useful for sorting, searching, or validating user input.

6.3 String Slicing in Python


●​ Slicing extracts a substring using the format:
●​ string[start:end:step]
●​ Default values:
○​ start = 0
○​ end = length of string
○​ step = 1
●​ Important Notes:
○​ Slicing does not modify the original string.
○​ You can also use negative indices (explained below).
6.4 Negative Indices in Strings
●​ Negative indexing means counting from the end of the string.
●​ -1 refers to the last character, -2 to the second last, and so on.
●​ Usage:
○​ Helpful when you don’t know the exact length of the string.
○​ Commonly used in reverse traversals and trimming suffixes.

6.5 Splitting and Stripping Strings


●​ Splitting:
○​ split() divides a string into a list using a separator (default is space).
●​ Stripping:
○​ Removes whitespace or specified characters from both ends.
○​ strip(), lstrip(), rstrip()

6.6 String Functions in Python


Important String Functions:

Function Description Example

len(s) Returns length of the string len("hello") → 5

lower() Converts to lowercase "HELLO".lower() → 'hello'

upper() Converts to uppercase "hi".upper() → 'HI'

find(sub) Finds first index of sub "apple".find("p") → 1

replace(a,b) Replaces all a with b "abc".replace("a", "x") → 'xbc'

count(sub) Counts occurrences of substring "banana".count("a") → 3

startswith(s) Checks if string starts with s "hello".startswith("he") → True

endswith(s) Checks if string ends with s "hello".endswith("lo") → True

isalnum() True if all characters are "abc123".isalnum() → True


alphanumeric

isdigit() True if all characters are digits "123".isdigit() → True


7 Regular Expressions in Python
●​ A Regular Expression (regex) is a sequence of characters used to define a search pattern.
It is commonly used for:
○​ Pattern matching
○​ Text validation (e.g., email, phone numbers)
○​ Search and replace operations
●​ Python provides the re module to work with regular expressions.

7.1 Basic Regex Syntax and Patterns

Pattern Description Example Match

. Any character except newline a.b → matches


"acb"

^ Start of string ^abc → "abcde"

$ End of string abc$ → "xxabc"

[] Character set [a-z] → lowercase

[^ ] Negated character set [^0-9] → not


digits

* 0 or more occurrences ab* → "a", "abb"

+ 1 or more occurrences ab+ → "ab", "abb"

? 0 or 1 occurrence ab? → "a", "ab"


{n} Exactly n times a{2} → "aa"

{n,m} Between n and m times a{1,3} → "a", "aa"

\d Digit (0–9) \d → "5"

\w Word character (a–z, A–Z, 0–9, _) \w → "a", "9", "_"

\s Whitespace \s → " "

` ` OR operator

() Grouping (ab)+ → "abab"

Note: Study any 5-7 pattern

7.2 Importing re Module

7.3 Matching Patterns Using match() and fullmatch()


●​ re.match(pattern, string)
○​ Checks if the beginning of the string matches the pattern.
●​ re.fullmatch(pattern, string)
○​ Checks if entire string matches the pattern.
7.4 Searching Using search()
●​ re.search(pattern, string)
○​ Finds the first occurrence of the pattern anywhere in the string.

7.5 Finding All Matches Using findall()


●​ re.findall(pattern, string)
○​ Returns a list of all non-overlapping matches.

7.6 Search and Replace Using sub()


●​ re.sub(pattern, replace_with, string)
○​ Replaces all occurrences of the pattern.
7.7 Use Cases of Regular Expressions

Use Case Pattern Example

Validate Email \w+@\w+\.\w+

Mobile Number [6-9]\d{9}

Extract Words [a-zA-Z]+

Remove Special Char re.sub(r'[^\w\s]', '', text)

Count Digits len(re.findall(r'\d', text))

7.8 Practice Example

You might also like