Python

Python is a popular high-level programming language known for its simplicity and readability. It is widely used for various purposes, including web development, data analysis, artificial intelligence, scientific computing, and automation. Python's clean and intuitive syntax allows developers to write code that is easy to understand and maintain. It offers a vast standard library and a rich ecosystem of third-party packages, providing solutions for a wide range of tasks.

Module 1: Python Basics

Introduction to Python

Python is a high-level, interpreted programming language known for its readability and simplicity. It's widely used in various fields such as web development, data science, machine learning, AI, and more. Python was created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability with its notable use of significant whitespace.

Installing Python

To start using Python, you must install it on your machine. This process varies depending on your operating system. You can download the official Python distribution from the Python website. After installation, you can verify it by opening your terminal and typing 'python --version'. This should display the installed version of Python.

Hello, World!

In every programming language, the 'Hello, World!' program is the traditional first program. In Python, it's very simple. Open your text editor, type 'print('Hello, World!')', and save it as hello_world.py. Then, run this file from the terminal with 'python hello_world.py'. You should see 'Hello, World!' printed to the console.

print('Hello, World!')

Variables and Types

Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Python supports various types of variables, including int (integer), float (floating point number), str (string), list, tuple, dict (dictionary), and bool (boolean).

x = 5
y = 'Hello'
print(type(x))
print(type(y))

Module 2: Python Control Structures

Conditional Statements

Conditional statements in Python allows the code to make decisions. This involves using keywords such as 'if', 'elif' (else if), and 'else'.

x = 20
if x > 10:
	print('x is greater than 10')
elif x == 10:
	print('x is exactly 10')
else:
	print('x is less than 10')

Loops

Loops are used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or perform an action multiple times. Python provides 'for' loops and 'while' loops.

for i in range(5):
	print(i)

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

Break and Continue

In Python, 'break' and 'continue' statements can alter the flow of a normal loop. 'break' ends the current loop and resumes execution at the next statement. 'continue' skips the current iteration of the loop and moves on to the next.

for i in range(5):
	if i == 3:
		break
	print(i)

for i in range(5):
	if i == 3:
		continue
	print(i)

Pass Statement

In Python, 'pass' is a null statement. It results into no operation (NOP). The 'pass' statement can be used when a statement is required syntactically, but you do not want any command or code to execute.

for i in range(5):
	if i == 3:
		pass
	print(i)

Module 3: Python Data Structures

Lists

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element inside a list is called an item. Lists are defined by having values between square brackets []

my_list = [1, 2, 3, 'Hello', True, [5, 6]]
print(my_list)

Tuples

A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. Tuples are defined by having values between parentheses ()

my_tuple = (1, 2, 3, 'Hello', True)
print(my_tuple)

Dictionaries

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets {}, and they have keys and values.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict)

Sets

A set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python set class represents the mathematical notion of a set. Sets are written with curly brackets {}.

my_set = {1, 2, 3, 4, 5, 5, 5}
print(my_set)

Module 4: Python Functions and Modules

Defining Functions

Functions in Python are blocks of reusable code that perform a specific task. You define functions using the 'def' keyword.

def greet(name):
	return f'Hello, {name}!'

print(greet('John'))

Lambda Functions

A lambda function is a small anonymous function. It can take any number of arguments, but can only have one expression. Lambda functions are defined using the 'lambda' keyword.

multiply = lambda x, y: x * y
print(multiply(5, 3))

Modules and Imports

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. We can use any Python source file as a module by executing an import statement in some other Python source file.

import math
print(math.sqrt(16))

Built-in Modules

Python comes with a library of standard modules. Some modules are built into the Python interpreter, these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls.

import os
print(os.getcwd())

import random
print(random.randint(1, 10))

Module 5: Exception Handling

Python Exceptions

An exception is an error that happens during the execution of a program. Exceptions are known to non-programmers as instances that do not conform to a general rule.

x = 10
try:
	print(x / 0)
except ZeroDivisionError as e:
	print('You can't divide by zero!')
finally:
	print('This code will run no matter what.')

Creating Custom Exceptions

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived form this class.

class MyCustomError(Exception):
	pass

try:
	raise MyCustomError('This is a custom exception')
except MyCustomError as e:
	print(e)

Module 6: Python Object-Oriented Programming

Creating Classes and Objects

Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a 'blueprint' for creating objects.

class MyClass:
	x = 5

p1 = MyClass()
print(p1.x)

Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

class Person:
	def __init__(self, name, age):
		self.name = name
		self.age = age

class Employee(Person):
	def __init__(self, name, age, salary):
		super().__init__(name, age)
		self.salary = salary

emp = Employee('John', 30, 70000)
print(emp.name)
print(emp.age)
print(emp.salary)

Polymorphism

Polymorphism is an object-oriented programming concept that refers to the ability of a variable, function or object to take on multiple forms. In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class.

class Bird:
	def intro(self):
		print('There are many types of birds.')
	def flight(self):
		print('Most of the birds can fly but some cannot.')

class sparrow(Bird):
	def flight(self):
		print('Sparrows can fly.')

class ostrich(Bird):
	def flight(self):
		print('Ostriches cannot fly.')

bird = Bird()
spr = sparrow()
ost = ostrich()

bird.intro()
bird.flight()

spr.intro()
spr.flight()

ost.intro()
ost.flight()