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

1.python Function

Uploaded by

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

1.python Function

Uploaded by

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

1.

Python Functions
Definition and Usage
A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity and a high degree of code reusability.
Syntax
python
def function_name(parameters):
"""docstring"""
statement(s)
return value
Example: Summing Numbers
python
def sum_of_numbers(numbers):
"""Returns the sum of a list of numbers."""
total = 0
for number in numbers:
total += number
return total
# Example usage
numbers = [1, 2, 3, 4, 5]
print(sum_of_numbers(numbers)) # Output: 15
Explanation
Function Name: sum_of_numbers
Parameters: numbers is a list of numbers.
Docstring: Describes what the function does.
Body: Initializes a total to 0, iterates over each number in the list, adds each number to the total.
Return Statement: Returns the total sum of numbers.
2. Python Sequences
Types of Sequences
Python includes several sequence types, including lists, tuples, and strings. Each type has its own
properties and use cases.
Lists
Lists are mutable sequences, typically used to store collections of homogeneous items.
python
fruits = ['apple', 'banana', 'cherry']
fruits.append('date') # Adding an element
print(fruits) # Output: ['apple', 'banana', 'cherry', 'date']
Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data.
python
coordinates = (10.0, 20.0)
print(coordinates) # Output: (10.0, 20.0)
Strings
Strings are immutable sequences of characters.
python
message = "Hello, World!"
print(message[0]) # Output: 'H'
Sequence Operations
Indexing and Slicing
Indexing: Access individual elements using square brackets.
python
print(fruits[1]) # Output: 'banana'
Slicing: Access a range of elements using the colon : operator.
python
print(fruits[1:3]) # Output: ['banana', 'cherry']
Concatenation and Repetition
Concatenation: Combine sequences using the + operator.
python
combined = fruits + ['elderberry']
print(combined) # Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']
Repetition: Repeat sequences using the * operator.
python
repeated = fruits * 2
print(repeated) # Output: ['apple', 'banana', 'cherry', 'date', 'apple', 'banana', 'cherry', 'date']
3. Iterations
For Loops
For loops are used to iterate over a sequence (like a list, tuple, or string).
python
for fruit in fruits:
print(fruit)
While Loops
While loops repeat a block of code as long as a condition is true.
python
count = 0
while count < 5:
print(count)
count += 1
List Comprehensions
List comprehensions provide a concise way to create lists.
python
squares = [x ** 2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example Function: Filtering Even Numbers
Let's build a more detailed example function that combines sequences and iterations.
Function: Filtering Even Numbers
python
def filter_even_numbers(numbers):
"""Returns a list of even numbers from the given list."""
even_numbers = [number for number in numbers if number % 2 == 0]
return even_numbers
# Example usage
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_even_numbers(numbers)) # Output: [2, 4, 6, 8, 10]
Explanation
Function Name: filter_even_numbers
Parameters: numbers is a list of integers.
Docstring: Describes what the function does.
List Comprehension: Iterates over each number in the list, includes it in the new list if it is even (number
% 2 == 0).
Return Statement: Returns the new list of even numbers.
Advanced Iterations
Using enumerate
The enumerate function adds a counter to an iterable and returns it as an enumerate object.

python
Sao chép mã
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Using zip
The zip function takes two or more sequences and returns an iterator of tuples, where the i-th tuple
contains the i-th element from each of the input sequences.

python
Sao chép mã
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
for number, letter in zip(numbers, letters):
print(f"{number}: {letter}")
Using map
The map function applies a given function to each item of an iterable (like a list) and returns a list of the
results.

python
Sao chép mã
def square(x):
return x ** 2

squared_numbers = list(map(square, numbers))


print(squared_numbers) # Output: [1, 4, 9]
Using filter
The filter function constructs an iterator from elements of an iterable for which a function returns true.

python
Sao chép mã
def is_even(x):
return x % 2 == 0

even_numbers = list(filter(is_even, numbers))


print(even_numbers) # Output: [2]
Using reduce
The reduce function from the functools module applies a rolling computation to sequential pairs of values
in a list.

python
Sao chép mã
from functools import reduce

def add(x, y):


return x + y
sum_numbers = reduce(add, numbers)
print(sum_numbers) # Output: 6
By understanding and combining these concepts, you can write efficient and concise Python code to
perform various operations on sequences and iterations. Feel free to ask if you need further elaboration on
any specific topic!

You might also like