Python for Linux Administration, Cloud, DevOps, and OpenShift (Chapter 2)
Chapter 2: Advanced Python Concepts
2.1 Functions:
Functions in Python are used to group related code into blocks that perform specific tasks.
Functions are defined using the 'def' keyword.
Example:
def greet(name):
print(f"Hello, {name}!")
greet('World')
2.2 Classes and Objects:
Python is an object-oriented language, meaning it supports the concept of classes and objects.
A class is a blueprint for creating objects, and an object is an instance of a class.
Example:
class Car:
def __init__(self, make, model):
[Link] = make
[Link] = model
def display_info(self):
print(f"Car make: {[Link]}, Model: {[Link]}")
my_car = Car('Toyota', 'Corolla')
my_car.display_info()
2.3 File Handling:
File handling in Python is done using built-in functions to read from and write to files.
Example:
with open('[Link]', 'w') as file:
[Link]("Hello, this is a sample file.")
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
2.4 Lambda Functions:
Lambda functions are small, anonymous functions that can have any number of arguments but only
one expression.
Example:
add = lambda x, y: x + y
print(add(5, 3))
2.5 List Comprehensions:
List comprehensions provide a concise way to create lists based on existing lists.
Example:
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print(squared)
2.6 Exception Handling:
Exceptions are errors that occur during the execution of a program. Python provides a mechanism
to handle exceptions using try, except, else, and finally.
Example:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input, please enter a valid number.")