ClickCease

Python Programming

1. Python Basics

Python uses indentation for defining blocks of code rather than curly braces or keywords. This makes the language syntax clean and easy to read.

Hello, World! Program:

Python Program Structure:

  1. Statements: Lines of code that perform an action.
  2. Comments: Lines that begin with # are ignored by the interpreter.
  3. Indentation: Whitespace at the beginning of lines defines the scope and structure of code.

# This is a comment
if True:
    print("This is indented")

Basic Input and Output:

  1. Output: The print() function is used to output data to the screen.
  2. Input: The input() function reads user input as a string.

name = input("Enter your name: ")
print("Hello, " + name)

2. Data Types

Python supports various data types, which can be classified as primitive or complex types.

Primitive Data Types:

Data Type Description Example
int Integer values age = 30
float Floating-point numbers price = 19.99
str Strings, or sequences of characters name = “Python”
bool Boolean values (True, False) is_valid = True
None Represents no value or null x = None

Complex Data Types:

Data Type Description Example
list Ordered, mutable collection numbers = [1, 2, 3, 4]
tuple Ordered, immutable collection coords = (1.0, 2.0, 3.0)
set Unordered collection of unique items unique_numbers = {1, 2, 3, 4}
dict Collection of key-value pairs person = {‘name’: ‘John’, ‘age’: 30}

Type Conversion:

You can convert between different data types using built-in functions such as int(), float(), str(), and bool().


x = int("10")  # Convert string to integer
y = float("10.5")  # Convert string to float
z = str(10)   # Convert integer to string

3. Variables and Constants

Variables in Python are created the moment you assign a value to them. There is no need for explicit variable declarations.


name = "Alice"   # String variable
age = 25         # Integer variable
price = 19.99    # Float variable
is_student = True  # Boolean variable

Naming Conventions:

  1. Use descriptive names for variables.
  2. Use lowercase with underscores (snake_case) for variable names.
  3. Constants are conventionally written in uppercase (PI = 3.14159).

Constants:

Python does not have a dedicated syntax for constants, but variables written in all uppercase are typically used to denote constant values.


PI = 3.14159  # Constant value
MAX_SIZE = 100  # Constant representing maximum size

4. Operators

Python supports a variety of operators for performing operations on variables and values.

Arithmetic Operators:

Operator Description Example
+ Addition a + b
Subtraction a – b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b
** Exponentiation a ** b
// Floor division a // b

Comparison Operators:

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal a >= b
<= Less than or equal a <= b

Logical Operators:

Operator Description Example
and Logical AND a and b
or Logical OR a or b
not Logical NOT not a

Assignment Operators:

Operator Description Example
= Assign value a = 10
+= Add and assign a += 5
-= Subtract and assign a -= 5
*= Multiply and assign a *= 5
/= Divide and assign a /= 5
**= Exponent and assign a **= 2

5. Strings

Strings in Python are sequences of characters enclosed in quotes (single, double, or triple quotes).


single_quote_string = 'Hello'
double_quote_string = "World"
multi_line_string = """This is a
multi-line string."""

String Manipulation:

Operation Description Example
Concatenation Joining two strings ‘Hello’ + ‘World’ → ‘HelloWorld’
Repetition Repeating a string multiple times ‘Hello’ * 3 → ‘HelloHelloHello’
Accessing Get character by index ‘Python'[0] → ‘P’
Slicing Get a substring ‘Python'[1:4] → ‘yth’
Length Get length of string len(‘Python’) → 6

Common String Methods:

Method Description Example
upper() Convert string to uppercase ‘hello’.upper() → ‘HELLO’
lower() Convert string to lowercase ‘HELLO’.lower() → ‘hello’
strip() Remove leading/trailing spaces ‘ hello ‘.strip() → ‘hello’
replace() Replace substring with another ‘Python’.replace(‘P’, ‘J’) → ‘Jython’
find() Find the position of a substring ‘Python’.find(‘th’) → 2
split() Split string into a list based on delimiter ‘a,b,c’.split(‘,’) → [‘a’, ‘b’, ‘c’]

6. Lists

Lists are ordered, mutable collections of items. They can contain elements of different types.


numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]

List Operations:

Operation Description Example
Accessing Get item by index numbers[0] → 1
Slicing Get a sublist numbers[1:3] → [2, 3]
Length Get the number of items len(numbers) → 5
Append Add item to the end of the list numbers.append(6)
Insert Insert item at a specific index numbers.insert(1, ‘a’)
Remove Remove first occurrence of item numbers.remove(3)
Pop Remove and return last item numbers.pop() → 5
Concatenate Join two lists list1 + list2
Repetition Repeat the list list1 * 3

Iterating Over Lists:


numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

Common List Methods:

Method Description Example
append() Add item to the end of the list numbers.append(6)
extend() Add multiple items to the list numbers.extend([6, 7, 8])
insert() Insert item at a specific index numbers.insert(2, ‘new’)
remove() Remove first occurrence of item numbers.remove(3)
pop() Remove and return last item numbers.pop() → 5
reverse() Reverse the list numbers.reverse()
sort() Sort the list in ascending order numbers.sort()

7. Tuples

Tuples are similar to lists, but they are immutable (i.e., they cannot be changed after creation).

Tuple Operations:

Operation Description Example
Accessing Get item by index coords[0] → 1.0
Slicing Get a sub-tuple coords[0:2] → (1.0, 2.0)
Length Get the number of items in the tuple len(coords) → 3

Packing and Unpacking Tuples:


# Packing a tuple
person = ("John", 30, "Engineer")
# Unpacking a tuple
name, age, profession = person
print(name)  # Outputs: John

8. Sets

Sets are unordered collections of unique elements. They do not allow duplicate values.


unique_numbers = {1, 2, 3, 4}

Set Operations:

Operation Description Example
Add Add an item to the set unique_numbers.add(5)
Remove Remove an item from the set unique_numbers.remove(2)
Union Combine two sets `set1
Intersection Get common items in both sets set1 & set2
Difference Get items in one set but not the other set1 – set2
Symmetric Diff. Get items in either set, but not both set1 ^ set2

Common Set Methods:

Method Description Example
add() Add item to the set unique_numbers.add(6)
remove() Remove item from the set unique_numbers.remove(1)
union() Return the union of two sets set1.union(set2)
intersection() Return the intersection of two sets set1.intersection(set2)
difference() Return the difference between sets set1.difference(set2)
symmetric_difference() Return symmetric difference of sets set1.symmetric_difference(set2)

9. Dictionaries

Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable (strings, numbers, or tuples), while values can be of any type.


person = {"name": "John", "age": 30, "profession": "Engineer"}

Dictionary Operations:

Operation Description Example
Accessing Value Get value by key person[‘name’] → ‘John’
Adding Item Add or update key-value pair person[‘city’] = ‘New York’
Removing Item Remove key-value pair del person[‘age’]
Keys Get all keys person.keys() → [‘name’, ‘age’]
Values Get all values person.values() → [‘John’, 30]
Items Get all key-value pairs person.items() → [(‘name’, ‘John’), (‘age’, 30)]

Iterating Over Dictionaries:


for key, value in person.items():
print(f"{key}: {value}")

Common Dictionary Methods:

Method Description Example
get() Return value for a key, or default person.get(‘name’, ‘Unknown’)
pop() Remove and return value by key person.pop(‘age’)
update() Update the dictionary with another dictionary person.update({‘city’: ‘NYC’})

10. Control Structures

Python provides various control structures to manage the flow of execution in a program, including conditionals, loops, and exceptions.

If-Else Statements:


age = 20
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")

Ternary Operator:


is_adult = True if age >= 18 else False

For Loop:


numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

While Loop:


i = 0
while i < 5:
print(i)
i += 1

Break and Continue:

  1. break: Exits the loop immediately.
  2. continue: Skips the current iteration and moves to the next one.

for i in range(10):
if i == 5:
break  # Exit loop when i is 5
if i % 2 == 0:
continue  # Skip even numbers
print(i)

11. Functions

Functions in Python are defined using the def keyword, and they can return values using the return statement.

Defining and Calling Functions:


def greet(name):
return f"Hello, {name}!"
print(greet("John"))  # Outputs: Hello, John!

Default Parameters:


def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice"))            # Outputs: Hello, Alice!
print(greet("Bob", "Good morning"))  # Outputs: Good morning, Bob!

Keyword Arguments:


def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet(name="Alice", greeting="Hi"))  # Outputs: Hi, Alice!

Variable-Length Arguments:


# Positional variable-length arguments
def add(*numbers):
return sum(numbers)
print(add(1, 2, 3))  # Outputs: 6
# Keyword variable-length arguments
def show_person(**details):
for key, value in details.items():
print(f"{key}: {value}")
show_person(name="John", age=30, city="New York")

12. Lambda Functions

Lambda functions are small anonymous functions defined using the lambda keyword. They are often used for short operations.


add = lambda x, y: x + y
print(add(5, 3))  # Outputs: 8

Using Lambda with Built-in Functions:

  1. map(): Applies a function to all elements in an iterable.
  2. filter(): Filters elements based on a condition.
  3. reduce(): Reduces a list to a single value (requires functools).

# Using map to square all numbers in a list
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares)  # Outputs: [1, 4, 9, 16]
# Using filter to get only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # Outputs: [2, 4]

13. Object-Oriented Programming (OOP)

Python supports Object-Oriented Programming (OOP) with classes, objects, and the main OOP principles: encapsulation, inheritance, and polymorphism.

Classes and Objects:


class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
# Creating an object
my_dog = Dog("Buddy", 3)
print(my_dog.bark())  # Outputs: Buddy says woof!

Inheritance:


class Animal:
def eat(self):
return "This animal is eating"
class Dog(Animal):
def bark(self):
return "Woof!"
dog = Dog()
print(dog.eat())  # Outputs: This animal is eating
print(dog.bark())  # Outputs: Woof!

Encapsulation:


class Person:
def __init__(self, name, age):
self.__name = name   # Private attribute
self.__age = age     # Private attribute
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
person = Person("John", 30)
print(person.get_name())  # Outputs: John

Polymorphism:


class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound())  # Outputs: Woof! Meow!

14. File Handling

Python makes it easy to read from and write to files using built-in functions such as open(), read(), and write().

Opening Files:


# 'r' for reading, 'w' for writing, 'a' for appending, 'b' for binary mode
file = open('filename.txt', 'r')
content = file.read()
print(content)
file.close()

Using with Statement:

The with statement is used for proper resource management, automatically closing the file after the block is executed.


with open('filename.txt', 'r') as file:
content = file.read()
print(content)  # File is automatically closed afterward

Writing to a File:


with open('filename.txt', 'w') as file:
file.write("Hello, World!")

15. Exception Handling

Python provides a way to handle runtime errors using try, except, finally, and else blocks.

Try-Except Block:


try:
result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("You cannot divide by zero!")

Finally Block:

The finally block is always executed, regardless of whether an exception was raised or not.


try:
result = 10 / 2
finally:
print("This will always execute")

Custom Exceptions:

You can create custom exceptions by defining new exception classes.


class MyCustomError(Exception):
pass
try:
raise MyCustomError("An error occurred")
except MyCustomError as e:
print(e)

16. Modules and Packages

A module is a Python file containing definitions and statements. A package is a collection of modules organized in a directory hierarchy.

Importing Modules:


import math
print(math.sqrt(16))  # Outputs: 4.0

Creating and Using Your Own Module:


# In my_module.py
def greet(name):
return f"Hello, {name}!"
# In your main script
import my_module
print(my_module.greet("John"))

Using Packages:


# Create a package directory structure:
# my_package/
#     __init__.py
#     module1.py
# In your main script
from my_package import module1

17. Standard Libraries

Python includes many standard libraries for tasks like string manipulation, file handling, and mathematical operations.

  1. math: Mathematical functions (sqrt(), sin(), cos())
  2. random: Random number generation (random(), randint())
  3. datetime: Date and time operations (datetime.now())
  4. os: Interacting with the operating system (os.listdir(), os.remove())
  5. sys: System-specific parameters and functions (sys.argv, sys.exit())

Example: Using the random Module:


import random
print(random.randint(1, 10))  # Outputs a random integer between 1 and 10

18. List Comprehensions

List comprehensions provide a concise way to create lists in a single line.


numbers = [x**2 for x in range(10)]
print(numbers)  # Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Conditional List Comprehensions:


numbers = [x**2 for x in range(10)]
print(numbers)  # Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

19. Iterators and Generators

An iterator is an object that can be iterated over, while a generator is a function that returns an iterator.

Creating Generators with yield:


def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num)  # Outputs numbers from 1 to 5

20. Decorators

Decorators are functions that modify the behavior of other functions or methods. They are often used for logging, timing, or access control.

Defining a Decorator:


def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()

21. Context Managers

Context managers allow you to allocate and release resources efficiently. The most common example is file handling.

Using a Context Manager:


with open('file.txt', 'r') as file:
content = file.read()
print(content)  # File is automatically closed

Custom Context Manager:

You can create your own context managers using the __enter__() and __exit__() methods.


class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting the context")
with MyContextManager() as cm:
print("Inside the context")

22. Python Best Practices

  1. Follow PEP 8 Guidelines:

PEP 8 is the style guide for Python code. It promotes readable and consistent code.

  1. Use 4 spaces per indentation level.
  2. Keep lines under 79 characters.
  3. Use meaningful variable and function names.

2. Use Virtual Environments:

Use virtual environments to manage project dependencies and avoid conflicts between packages.

# Create a virtual environment


python -m venv myenv
# Activate the virtual environment
source myenv/bin/activate  # On Windows: myenvScriptsactivate
  1. Write Unit Tests:

Test your code using Python’s built-in unittest module to ensure correctness.

  1. Use List Comprehensions Efficiently:

List comprehensions are more concise and generally faster than traditional loops for creating lists.

  1. Handle Exceptions Gracefully:

Use try-except blocks to catch and handle exceptions, ensuring that your program doesn’t crash unexpectedly.

  1. Use with for File Handling:

Always use the with statement for file operations to ensure files are properly closed.

23. Conclusion

Python is a versatile language with a wide range of applications, from web development to data science and artificial intelligence. This covers key Python concepts, including variables, data types, control structures, functions, object-oriented programming, file handling, and much more.
As you continue developing your skills in Python, it’s important to adhere to best practices such as writing clean, readable code, handling exceptions properly, and taking advantage of Python’s powerful standard libraries and tools.
By mastering these concepts, you will be able to write efficient, maintainable, and scalable Python programs for any domain. Happy coding!

Download Elysium Spark Note

Facebook
X
LinkedIn
Pinterest
WhatsApp