The if-else statement is a fundamental control structure in Python used for decision-making.
x = 10
if x > 5:
print("x is greater than 5")
x = 10
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
x = 10
if x > 0:
if x % 2 == 0:
print("x is positive and even")
else:
print("x is positive but odd")
else:
print("x is not positive")
Loops are used in Python to execute a block of code repeatedly. There are two main types of loops: for loop and while loop.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Example:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
i = 0
while i < 5:
print(i)
i += 1
Break Statement:
Example:
for num in range(1, 10):
if num == 5:
break
print(num) # Output: 1, 2, 3, 4
Continue Statement:
Example:
for num in range(1, 6):
if num == 3:
continue
print(num) # Output: 1, 2, 4, 5
Usage Considerations:
Example 1:
# Function to add two numbers
def add_numbers(a, b):
#This function takes two numbers as input and returns their sum.
return a + b
# Function to check if a number is even
def is_even(number):
#This function checks if the given number is even.
#Returns True if the number is even, False otherwise.
if number % 2 == 0:
return True
else:
return False
# Function to greet the user
def greet(name):
#This function takes a name as input and prints a greeting message.
print(f"Hello, {name}!")
# Testing the functions
num1 = 10
num2 = 5
print(f"The sum of {num1} and {num2} is: {add_numbers(num1, num2)}")
test_number = 7
if is_even(test_number):
print(f"{test_number} is an even number.")
else:
print(f"{test_number} is not an even number.")
greet("Alice")
Output:
The sum of 10 and 5 is: 15
7 is not an even number.
Hello, Alice!
In Python, variable scopes determine the visibility and accessibility of variables in different parts of a program. There are three main scopes: local, global, and nonlocal. Understanding these scopes helps in organizing code and preventing naming conflicts.
Local Scope:
def my_function():
x = 10 # Local variable
print(x) # Accessible within the function
my_function()
Global Scope:
x = 10 # Global variable
def my_function():
print(x) # Accessible within the function
my_function()
Nonlocal Scope:
def outer_function():
x = 10 # Enclosing scope
def inner_function():
nonlocal x # Access the x from the enclosing scope
x += 5
print(x)
inner_function()
outer_function()
Pass-by-value:
Example:
def increment(num):
num += 1
return num
x = 5
result = increment(x)
print(x) # Output: 5 (original object is unchanged)
print(result) # Output: 6 (modified object returned from the function)
Pass-by-Reference:
Example:
def append_item(lst):
lst.append(4)
my_list = [1, 2, 3]
append_item(my_list)
print(my_list) # Output: [1, 2, 3, 4] (original list modified inside the function)
Comparison with C++:
Keyword arguments in Python allow you to specify the name of the parameter you are assigning a value to in the function call. This provides flexibility in the order of arguments and enhances the readability of your code.
def greet(name, greeting="Hello", punctuation="!"):
print(f"{greeting}, {name}{punctuation}")
# Positional arguments
greet("Alice") # Output: Hello, Alice!
greet("Bob", "Hi") # Output: Hi, Bob!
greet("Charlie", "Hey", "?") # Output: Hey, Charlie?
# Keyword arguments (passed by name)
greet(name="David", greeting="Greetings", punctuation=".") # Output: Greetings, David.
greet(greeting="Hi", name="Eve", punctuation="!!") # Output: Hi, Eve!!
greet(punctuation="?", name="Frank", greeting="Hey") # Output: Hey, Frank?
# Mixing positional and keyword arguments
greet("Grace", punctuation="!!") # Output: Hello, Grace!!
greet("Hannah", greeting="Hi") # Output: Hi, Hannah!
Explanation
Key Points
In Python, you can return multiple integer values from a function by using a tuple.
Here's an example of returning multiple integer values:
def calculate_numbers(a, b):
sum_result = a + b
product_result = a * b
return sum_result, product_result
# Calling the function and capturing each returned value separately
sum_value = calculate_numbers(5, 3)
product_value = calculate_numbers(5, 3)
print(f"Sum: {sum_value}, Product: {product_value}")
In this code, the function `calculate_numbers` calculates the sum and product of two integers `a` and `b`. Each value is returned using a separate return statement. When calling the function, each returned value is captured separately.
Advanced functions in programming are those that offer specialized capabilities or allow for more concise and efficient coding techniques. One such function type is the lambda function, also known as an anonymous function.
lambda arguments: expression
. For example,
lambda x: x + 1
defines a lambda function that takes an argument x and
returns x + 1.
Usage:
filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
uses a lambda function
to filter even numbers from the list.
Benefits:
square = lambda x: x * x
print("Square of 4 is =", square(4))
sum = lambda x, y: x + y
print("Sum of 4 and 5 is =", sum(4, 5))
largest = lambda x, y: x if x > y else y
print("Largest between 4 and 5 is =", largest(4, 5))
Example: Program using the filter function to filter out only even numbers from the given list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
newlist = list(filter(lambda x: x % 2 == 0, mylist))
print(newlist)
Program using the filter function to print the items greater than 4
mylist = [2, 8, 9, 7, 6, 4, 5, 0]
result = filter(lambda x: x > 4, mylist)
print(list(result))
Program using the map function to double all the items in the list
mylist = [1, 2, 3, 5, 6, 7, 8]
doublelist = list(map(lambda x: 2 * x, mylist))
print(doublelist)
Program to separate the letters of the word "hello" and add the letters as items of the list using the map function
result = list(map(lambda x: x, "hello"))
print(result)
Program to find the sum of numbers in the list using reduce:
from functools import reduce
mylist = [1, 2, 3, 4, 5, 6, 7]
# Using reduce with a lambda function to add numbers in the list
sum = reduce(lambda x, y: x + y, mylist)
print(sum) # Output: 28 (1 + 2 + 3 + 4 + 5 + 6 + 7 = 28)
In this example, the reduce function combines the elements of the list by adding them together using the lambda function (x + y). It starts with the first two elements, adds them, then adds the result with the next element, and so on until all elements are combined into a single sum.
# mymodule.py file
variable_of_mymodule = 99
def areaOfSquare(side):
#Calculate the area of a square
return side * side
def calculator(a, b, op):
#Perform basic arithmetic operations
if op == 1:
print("Addition is =", a + b)
elif op == 2:
print("Subtraction is =", a - b)
elif op == 3:
print("Multiplication is =", a * b)
elif op == 4:
if b == 0:
print("Division cannot be performed")
return
print("Division is =", a / b)
else:
print("Enter a correct operation")
Now import it in a separate file and use the functions:
# newfile.py
import mymodule
# Usage example
side_length = 5
print("Area of square with side length", side_length, "is", mymodule.areaOfSquare(side_length))
num1 = 10
num2 = 5
operation = 3 # Multiplication
mymodule.calculator(num1, num2, operation)
# Using the variable_of_mymodule
print("Value of variable_of_mymodule in newfile.py:", mymodule.variable_of_mymodule)
If we want to use only one function, we can import it directly:
from mymodule import calculator
This imports only the "calculator" function from the "mymodule" module.
If we want to give an alias name to the imported function:
from mymodule import calculator as calc
This imports the "calculator" function from the "mymodule" module and gives it an alias "calc". We can then use "calc" instead of "calculator" in our code.
Libraries are collections of pre-written code, modules are individual Python files containing code, and packages are directories with related modules. Libraries like NumPy and Pandas offer domain-specific functionality, modules organize code into reusable units, and packages allow better organization in larger projects.
To open a file in Python, use the following syntax:
file_obj = open("filename", "mode")
The seek() function in Python is used to change the current file position within an open file. It is particularly useful when working with files that support random access, such as binary files.
offset
: The number of bytes to move the file pointer. A positive offset
moves the pointer forward, while a negative offset moves it backward.whence
: Specifies the reference position for the offset. It can take one of
three values:
The seek() function is commonly used in conjunction with reading or writing operations to navigate to a specific position within a file before performing file operations.
Example:
# Open a file in read mode
file = open("example.txt", "r")
# Move the file pointer to the 5th byte from the beginning
file.seek(5)
# Read and print the content from the current file position
print(file.read())
# Close the file
file.close()
Example:
# Example of using the "x" mode to create a new file
f1 = open("file_1.txt", "x")
# Now we can use other modes like "w" or "a" to write or append to the file
Example:
# Open the file in "r" mode
f1 = open("file_1.txt", "r")
# f1 = open("file_1.txt") # this will also work
# Read the content of the file
data = f1.read()
# Print the read data
print(data)
# Close the file
f1.close()
Example:
# Open the file in "w" mode
f1 = open("file_2.txt", "w") # This file doesn't exist, so a new file will be created; if it exists, its content will be erased.
# Write content to the file
f1.write("Welcome to Jenny's lectures") # Write the specified content to the file
# Close the file
f1.close()
# You can check the file to see that the content has been written
Example:
# Open the file in "r+" mode
f1 = open("file_2.txt", "r+")
# First, read from the file (make sure there is content written in the file)
data = f1.read()
# Now, write to the file
f1.write("This is Python lecture")
# Close the file
f1.close()
# You can check the file to see the updated content
Finding the cursor position:
# Use the tell() method to find the cursor position
cursor_position = f1.tell()
print("Cursor position:", cursor_position)
If you want to place the cursor at a specific position, you can use the seek() method:
# Set the cursor position to a specific location (e.g., position 0)
f1.seek(0)
Example:
# Open the file in "w+" mode
f1 = open("file_4.txt", "w+")
# Write content to the file
f1.write("This is a test file for w+ mode")
# Move the cursor to the beginning of the file
f1.seek(0)
# Read the content from the file
data = f1.read()
# Close the file
f1.close()
# Print the read data to verify
print("Read data:", data)
Example:
# Open the file in "a" mode
f1 = open("file_5.txt", "a")
# Write content to the file (appends to the end)
f1.write("This is appended content")
# Close the file
f1.close()
# You can check the file to see the appended content
Example:
# Open the file in "a+" mode
f1 = open("file_5.txt", "a+")
# Append content to the file
f1.write("This is appended content\n")
# Move the cursor to the beginning of the file
f1.seek(0)
# Read and print the file's content
print(f1.read())
# Close the file
f1.close()
write() method
Example:
f1 = open("f1.txt", "w")
f1.write("Hi, this is the line that I'm writing\n")
Example:
num = 123
f1.write(str(num))
Example:
# Open a file in write mode
f2 = open("f2.txt", "w")
# List of strings to write to the file
str_list = ["Hi", "Hello"]
# Write the list of strings to the file using writelines()
f2.writelines(str_list)
# Close the file after writing
f2.close()
read() Method:
Example:
f1 = open("abc.txt", "r") #make sure this file exists and there is data inside it.
# Reading the entire file
content = f1.read()
print("Content of the file:")
print(content)
# Resetting the file pointer to the beginning
f1.seek(0)
# Reading the first 10 characters
content = f1.read(10)
print("\nFirst 10 characters of the file:")
print(content)
Explanation:
readline() Method:
Example:
f2 = open("myfile.txt", "r")
line = f2.readline() # Reads one line from the file
print(line) # Output: First line of myfile.txt
Explanation:
readlines() Method:
Example:
f2 = open("myfile.txt", "r")
lines = f2.readlines() # Reads all lines from the file
print(lines) # Output: List of lines from myfile.txt
Explanation:
Example code:
with open('example.txt', 'r') as file:
data = file.read()
# Perform operations on the file
# File automatically closed outside the "with" block
Reference