ClickCease
Search
Close this search box.

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 TypeDescriptionExample
intInteger valuesage = 30
floatFloating-point numbersprice = 19.99
strStrings, or sequences of charactersname = “Python”
boolBoolean values (True, False)is_valid = True
NoneRepresents no value or nullx = None

Complex Data Types:

Data TypeDescriptionExample
listOrdered, mutable collectionnumbers = [1, 2, 3, 4]
tupleOrdered, immutable collectioncoords = (1.0, 2.0, 3.0)
setUnordered collection of unique itemsunique_numbers = {1, 2, 3, 4}
dictCollection of key-value pairsperson = {‘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:

OperatorDescriptionExample
+Additiona + b
Subtractiona – b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b
**Exponentiationa ** b
//Floor divisiona // b

Comparison Operators:

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equala >= b
<=Less than or equala <= b

Logical Operators:

OperatorDescriptionExample
andLogical ANDa and b
orLogical ORa or b
notLogical NOTnot a

Assignment Operators:

OperatorDescriptionExample
=Assign valuea = 10
+=Add and assigna += 5
-=Subtract and assigna -= 5
*=Multiply and assigna *= 5
/=Divide and assigna /= 5
**=Exponent and assigna **= 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:

OperationDescriptionExample
ConcatenationJoining two strings‘Hello’ + ‘World’ → ‘HelloWorld’
RepetitionRepeating a string multiple times‘Hello’ * 3 → ‘HelloHelloHello’
AccessingGet character by index‘Python'[0] → ‘P’
SlicingGet a substring‘Python'[1:4] → ‘yth’
LengthGet length of stringlen(‘Python’) → 6

Common String Methods:

MethodDescriptionExample
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:

OperationDescriptionExample
AccessingGet item by indexnumbers[0] → 1
SlicingGet a sublistnumbers[1:3] → [2, 3]
LengthGet the number of itemslen(numbers) → 5
AppendAdd item to the end of the listnumbers.append(6)
InsertInsert item at a specific indexnumbers.insert(1, ‘a’)
RemoveRemove first occurrence of itemnumbers.remove(3)
PopRemove and return last itemnumbers.pop() → 5
ConcatenateJoin two listslist1 + list2
RepetitionRepeat the listlist1 * 3

Iterating Over Lists:

numbers = [1, 2, 3, 4, 5]

for num in numbers:

    print(num)

Common List Methods:

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

 

7. Tuples

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

Tuple Operations:

OperationDescriptionExample
AccessingGet item by indexcoords[0] → 1.0
SlicingGet a sub-tuplecoords[0:2] → (1.0, 2.0)
LengthGet the number of items in the tuplelen(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:

OperationDescriptionExample
AddAdd an item to the setunique_numbers.add(5)
RemoveRemove an item from the setunique_numbers.remove(2)
UnionCombine two sets`set1
IntersectionGet common items in both setsset1 & set2
DifferenceGet items in one set but not the otherset1 – set2
Symmetric Diff.Get items in either set, but not bothset1 ^ set2

Common Set Methods:

MethodDescriptionExample
add()Add item to the setunique_numbers.add(6)
remove()Remove item from the setunique_numbers.remove(1)
union()Return the union of two setsset1.union(set2)
intersection()Return the intersection of two setsset1.intersection(set2)
difference()Return the difference between setsset1.difference(set2)
symmetric_difference()Return symmetric difference of setsset1.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:

OperationDescriptionExample
Accessing ValueGet value by keyperson[‘name’] → ‘John’
Adding ItemAdd or update key-value pairperson[‘city’] = ‘New York’
Removing ItemRemove key-value pairdel person[‘age’]
KeysGet all keysperson.keys() → [‘name’, ‘age’]
ValuesGet all valuesperson.values() → [‘John’, 30]
ItemsGet all key-value pairsperson.items() → [(‘name’, ‘John’), (‘age’, 30)]

Iterating Over Dictionaries:

for key, value in person.items():

print(f"{key}: {value}")

Common Dictionary Methods:

MethodDescriptionExample
get()Return value for a key, or defaultperson.get(‘name’, ‘Unknown’)
pop()Remove and return value by keyperson.pop(‘age’)
update()Update the dictionary with another dictionaryperson.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: myenv\Scripts\activate

  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!

Facebook
X
LinkedIn
Pinterest
WhatsApp