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

Wk2_material - Python Programming (Advanced Concepts)

The document outlines advanced concepts in Python programming, covering topics such as string formatting, types of operations, conditional statements, loops, functions, and objects. It explains various programming constructs, including the use of conditional statements for decision-making, loops for iteration, and functions for code reuse. Additionally, it discusses the nature of objects in Python, their attributes and methods, and provides examples for better understanding.

Uploaded by

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

Wk2_material - Python Programming (Advanced Concepts)

The document outlines advanced concepts in Python programming, covering topics such as string formatting, types of operations, conditional statements, loops, functions, and objects. It explains various programming constructs, including the use of conditional statements for decision-making, loops for iteration, and functions for code reuse. Additionally, it discusses the nature of objects in Python, their attributes and methods, and provides examples for better understanding.

Uploaded by

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

wk2_material - Python programming (Advanced concepts)

March 30, 2025

0.1 Week 2 - Python programming (Advanced concepts)


0.1.1 Outline
• String formatting
• Types of operations in Python
• Conditional statements
• Loops (For and While)
• Functions (Built-in and User-defined)
• Objects in Python
• Additional resources

0.1.2 STRING FORMATTING


String formatting is essential for creating dynamic strings that incorporate variables or expres-
sions. Python offers several methods for string formatting:
• Using the format() Method:
name = "John"
age = 30
text = "My name is {} and I am {} years old.".format(name, age)
print(text)
• f-Strings (Formatted String Literals): Introduced in Python 3.6, f-strings offer a concise
syntax for embedding expressions inside string literals.
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
• Percent (%) Formatting: An older method, less recommended but still in use.
name = "John"
age = 30
print("My name is %s and I am %d years old." % (name, age))

0.1.3 TYPES OF OPERATIONS IN PYTHON


• Arithmetic operation
• Comparison operation
• Logical operation

1
• Assignment operation
• Membership operation
• Identity operation

Comparison (Relational) Operations These operations are used to compare the value of two
operands:
• Equal to (==): True if both operands are equal.
• Not equal to (!=): True if operands are not equal.
• Greater than (>): True if the left operand is greater than the right operand.
• Less than (<): True if the left operand is less than the right operand.
• Greater than or equal to (>=): True if the left operand is greater than or equal to the right
operand.
• Less than or equal to (<=): True if the left operand is less than or equal to the right operands.
The comparison operate compares two values and gives either TRUE or FALSE as the output.

Logical Operations These operations are used to combine conditional statements:


• And (and): True if both operands are true.
• Or (or): True if at least one of the operands is true.
• Not (not): True if the operand is false.

Assignment Operations These operations are used to assign values to variables:


• Assign (=): Assigns a value to a variable.
• Add AND (+=), Subtract AND (-=), Multiply AND (*=), etc.: Perform the operation and
assign the result to the left operand.

Membership Operations These operations test if a sequence contains a certain value:


• In (in): True if a sequence contains a certain value.
• Not in (not in): True if a sequence does not contain a certain value.

Identity Operations These operations compare the memory locations of two objects:
• Is (is): True if both operands refer to the same object.
• Is not (is not): True if operands refer to different objects.
Each type of operation enables specific manipulations and checks within Python code, making it
versatile for a wide range of programming tasks from basic arithmetic to complex conditional logic.

0.2 CONDITIONAL STATEMENTS


Conditional statements in Python are a fundamental part of controlling the flow of execution in a
program. They allow the program to execute certain blocks of code based on specific conditions,
making decisions based on the data and inputs available. These statements enable branching,
whereby different sequences of instructions can be executed depending on whether a condition is
true or false.

2
0.2.1 If Statement
The if statement is the simplest form of a conditional statement. It evaluates a condition, and if
the condition is True, the indented block of code under it is executed.
x = 10
if x > 5:
print("x is greater than 5")

0.2.2 If-Else Statement


The if-else statement extends the if statement to execute one block of code if the condition is
True, and another block of code if the condition is False.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

0.2.3 If-Elif-Else Statement


For multiple conditions that need to be evaluated, the if-elif-else structure can be used. elif
(short for else if) specifies additional conditions to check if the previous conditions were False.
x = 10
if x > 15:
print("x is greater than 15")
elif x > 10:
print("x is greater than 10 but less than or equal to 15")
else:
print("x is less than or equal to 10")

0.2.4 Nested Conditional Statements


Conditional statements can be nested within each other, allowing for complex decision-making
processes.
x = 10
y = 20
if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
else:
print("x is greater than 5 but y is not greater than 15")
else:
print("x is not greater than 5")

0.2.5 Conditional Expressions (Ternary Operator)


Python also supports a shorthand way of writing conditional statements, known as the ternary
operator or conditional expressions. It allows a simple if-else condition to be written in a single

3
line.
x = 5
result = "Greater than 2" if x > 2 else "Not greater than 2"
print(result)

0.2.6 Logical Operators


Logical operators and, or, and not can be used to combine conditional statements for more complex
conditions.
x = 10
if x > 5 and x < 15:
print("x is between 5 and 15")
Conditional statements are crucial for adding decision-making capabilities to Python programs.
They enable programs to react differently under varying conditions, making them more dynamic
and versatile.

0.3 LOOPS AND ITERATION


Loops in Python are a fundamental construct that allows for the execution of a block of code
repeatedly, either for a fixed number of times or until a certain condition is met. Python provides
two primary types of loops: for loops and while loops, each with its own use cases and syntax.

0.3.1 For Loops


The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set,
or string) and execute a block of code for each item in the sequence. It’s particularly useful for
tasks that require action on each element of an iterable object or when you need to repeat a block
of code a known number of times.
Syntax:
for variable in sequence:
# Block of code
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for loops can also be combined with the range() function to generate a sequence of numbers,
which provides a convenient way to repeat a block of code a specific number of times.
for i in range(5):
print(i)

0.3.2 While Loops


The while loop in Python executes a block of code as long as a specified condition is True. It’s
used when the number of iterations is not known before the loop starts. The while loop keeps
iterating until the condition becomes False.

4
Syntax:
while condition:
# Block of code
Example:
i = 0
while i < 5:
print(i)
i += 1

0.3.3 Common use cases for while loops include:


• Iterating until a certain condition is met.
• Implementing interactive user input loops.
• Creating infinite loops with a break statement when a certain condition is met.
• Implementing algorithms that require repetitive actions until a condition is satisfied, like
searching or sorting algorithms.

0.3.4 Loop Control Statements


Python also provides control statements that can alter the flow of loops:
• break: Exits the loop and skips the execution of any remaining iterations.
• continue: Skips the rest of the code inside the loop for the current iteration and moves to
the next iteration.
• else: (In loops) Executes a block of code once when the loop condition becomes False. The
else block after a while or for loop only executes if the loop completes normally without
encountering a break statement.
Loops are a powerful feature in Python, allowing for efficient repetition and iteration over data,
which is a cornerstone of many programming tasks, from data processing to automation. Under-
standing and effectively utilizing loops is essential for any Python programmer.

0.4 FUNCTIONS
Functions in Python are defined blocks of reusable code designed to perform a specific task or a set
of related tasks. They are fundamental to Python programming, enabling modular, organized, and
efficient code development. By defining functions, programmers can break down complex processes
into manageable pieces, enhance code readability, and avoid repetition.
In Python, a function consists of several parts:
1. Function Name: This is the identifier for the function, which is used to call it later in the
code. It should be descriptive of what the function does, following the naming conventions
in Python (usually lowercase with words separated by underscores).
2. Parameters (or Arguments): These are optional. Parameters are the input values that
you pass into the function. A function may have zero or more parameters. They are specified
within parentheses following the function name.

5
3. Function Body: This is the block of code that performs the specific task of the function.
It’s indented and begins after the colon following the function definition.
4. Return Statement (Optional): This is used to return a value from the function back to the
caller. Not all functions need to return a value, in which case they can omit this statement.
If present, the return statement typically comes at the end of the function body.
Here’s a simple example:
def greet(name):
return "Hello, " + name + "!"

# Function call
print(greet("Alice"))
In this example: - greet is the function name. - name is the parameter. - "Hello, " + name +
"!" is the function body. - return "Hello, " + name + "!" is the return statement.
When you call greet("Alice"), "Alice" is passed as the argument to the name parameter, and
the function returns "Hello, Alice!", which is then printed.
Additionally, you might see documentation strings (docstrings) used to describe the purpose and
usage of a function. These are optional, but they are helpful for documenting your code. They
appear as a string literal as the first statement in a function body.

0.4.1 Defining Functions


A function is defined using the def keyword, followed by a function name, parentheses () which
may include parameters, and a colon :. The body of the function contains the statements that are
executed when the function is called.
def greet(name):
print(f"Hello, {name}!")

0.4.2 Calling Functions


Once defined, a function is called by using its name followed by parentheses. If the function requires
arguments, they are placed inside the parentheses.
greet("Alice")

0.4.3 Parameters and Arguments


Functions can accept data, known as parameters, which influence their behavior. When a function
is called, the actual values passed are termed arguments.
def add(x, y):
return x + y

result = add(5, 3) # 8

6
0.4.4 Return Values
Functions can return values using the return statement. A function stops executing when it
encounters a return statement, and the value specified is returned to the caller.
def multiply(x, y):
return x * y

0.4.5 Types of Functions


• Built-in Functions: Python includes a set of built-in functions. Examples are print(),
len(), and max(), int(), str(), float(), type(), dict() etc.
• User-defined Functions: Functions that are defined by the programmer to perform custom
tasks.
• Anonymous Functions (Lambda Functions): Defined using the lambda keyword, these
are small, unnamed functions that can have any number of arguments but only one expression.
square = lambda x: x * x

0.5 OBJECTS IN PYTHON


Everything in Python is an object. Even values of basic primitive types (integer, string, float..)
are objects. Lists are objects, tuples, dictionaries, everything. Objects have attributes and methods
that can be accessed using the dot syntax.
For example, try defining a new variable of type int : age = 8 age now has access to the properties
and methods defined for all int objects. This includes, for example, access to the real and imaginary
part of that number:
A variable holding a list value has access to a different set of methods:
items = [1, 2]
items.append(3)
items.pop()
print(age.real) # 8
print(age.imag) # 0
print(age.bit_length()) #4
# the bit_length() method returns the number of bits
67

0.6 Attributes and Methods


• Attributes: Think of attributes as characteristics or properties of an object. They
describe the object’s state or features. For example, if you have a car object, its attributes
might include things like color, make, model, and year.
• Methods: Methods are functions that are associated with an object. They represent actions
or behaviors that the object can perform. Continuing with the car example, methods might
include start(), stop(), accelerate(), and brake().
In simpler terms: - Attributes tell you about an object. - Methods tell you what an object can
do.

7
0.7 Attributes and Methods for the various Data Types in Python
0.7.1 Integer (int)
• bit_length: Returns the number of bits necessary to represent the integer in binary, exclud-
ing the sign and leading zeros.

0.7.2 Float (float)


• real: Returns the real part of the floating-point number.
• imag: Returns the imaginary part of the floating-point number.

0.7.3 Complex (complex)


• real: Returns the real part of the complex number.
• imag: Returns the imaginary part of the complex number.

0.7.4 String (str)


• capitalize(): Returns a copy of the string with the first character capitalized and the rest
lowercased.
• upper(): Returns a copy of the string with all characters converted to uppercase.
• lower(): Returns a copy of the string with all characters converted to lowercase.
• strip(): Returns a copy of the string with leading and trailing whitespace removed.
• startswith(prefix): Returns True if the string starts with the specified prefix; otherwise,
returns False.
• endswith(suffix): Returns True if the string ends with the specified suffix; otherwise,
returns False.
• split(separator): Returns a list of substrings separated by the specified separator.
• join(iterable): Concatenates the strings in the iterable with the string as a separator.

0.7.5 List (list)


• append(x): Appends an element to the end of the list.
• extend(iterable): Extends the list by appending elements from the iterable.
• insert(i, x): Inserts an element at the specified index.
• pop([i]): Removes and returns the element at the specified index. If no index is specified,
removes and returns the last element.
• remove(x): Removes the first occurrence of the specified value from the list.
• index(x): Returns the index of the first occurrence of the specified value.
• count(x): Returns the number of occurrences of the specified value in the list.

0.7.6 Tuple (tuple)


• count(x): Returns the number of occurrences of the specified value in the tuple.
• index(x): Returns the index of the first occurrence of the specified value.

0.7.7 Dictionary (dict)


• keys(): Returns a view of the dictionary’s keys.
• values(): Returns a view of the dictionary’s values.

8
• items(): Returns a view of the dictionary’s key-value pairs.
• get(key[, default]): Returns the value for the specified key. If the key is not found,
returns the default value or None if not specified.
• pop(key[, default]): Removes and returns the value for the specified key. If the key is not
found and a default value is provided, returns the default value; otherwise, raises a KeyError.
• popitem(): Removes and returns an arbitrary key-value pair from the dictionary.

0.7.8 Set (set)


• set.union(other_set): Returns a new set containing all unique elements from both sets.
• set.intersection(other_set): Returns a new set containing elements that are common to
both sets.
• set.difference(other_set): Returns a new set containing elements that are present in the
first set but not in the second set.
• set.symmetric_difference(other_set): Returns a new set containing elements that are
present in either the first set or the second set, but not in both.
• set.issubset(other_set): Returns True if all elements of the set are present in the other
set; otherwise, returns False.
• set.issuperset(other_set): Returns True if all elements of the other set are present in
the set; otherwise, returns False.
• set.isdisjoint(other_set): Returns True if the set has no elements in common with the
other set; otherwise, returns False.
• set.copy(): Returns a shallow copy of the set.
These are just some of the many attributes available for each data type in Python, but they cover
some of the most commonly used ones.

0.7.9 ADDITIONAL RESOURCES


Useful resources that you can go through
• String Formatting
• Conditional statements
• Functions in Python
• Python Built-in functions list
• Loops and Iterations
• Else clauses on Loops

You might also like