Introduction to Python
- Python is a high-level, interpreted, general-purpose programming language.
- It is a popular programming language.
- It can be used on a server to create web applications.
- It was created by Guido Van Rossum and released in 1991.
- Its design philosophy emphasizes code readability with the use of significant indentation.
- Python is dynamically-typed and garbage-collected.
- It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
- It has a simple syntax similar to the English Language.
Code Example:
print("Hello World") #Output:Hello World
Key Features:
- Easy to learn and use: Python's syntax is clear and concise, making it beginner-friendly.
- Extensive standard library: Python comes with a vast library of modules and functions, reducing development time.
- Large community support: A vibrant community contributes to Python's growth, providing resources and support.
- Versatile and can be used for various applications: From web development to data science and AI, Python is highly adaptable.
- It is used for:
* Web development (Server-Side)
* Software development
* Mathematics
* System scripting
Variables:
- In Python, variables are created when you assign a value to it.
- Variables are containers for storing data values.
Code Example:
x = str(3)
y = int(3)
z = float(3)
print(x, y, z) #Output:3 3 3.0
print(type(x)) #Output:class 'str'
print(type(y)) #Output:class 'int'
print(type(z)) #Output:class 'float'
Comments:
- It starts with a #, and Python will ignore them.
- It starts with """,ends with """ and Python will ignore them.
Code Example:
#This is single line comment
"""This is the
multi line
comment"""
Further Resources:
Datatypes in Python
Datatypes represent the type of value that a variable holds. Python has several built-in datatypes:
- Numbers: Integers (e.g., 10), Floats (e.g., 3.14), Complex numbers (e.g., 3+5j). Python supports arbitrary-precision integers.
- String: Ordered sequence of characters (e.g., "Hello"). Strings are immutable in Python.
- List: Ordered and mutable sequence of items (e.g., [1, 2, 3]). Lists can contain items of different datatypes.
- Tuple: Ordered and immutable sequence of items (e.g., (1, 2, 3)). Tuples are often used for data that shouldn't be changed.
- Set: Unordered collection of unique items (e.g., {1, 2, 3}). Sets are useful for operations like union, intersection, and difference.
- Dictionary: Unordered collection of key-value pairs (e.g., {'a': 1, 'b': 2}). Dictionaries are highly efficient for looking up values by key.
- Boolean: Represents truth values (True or False). Booleans are essential for control flow.
- NoneType: Represents the absence of a value.
Code Example:
x = 10
y = 3.14
name = "Python"
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
my_set = {7, 8, 9}
my_dict = {'key': 'value'}
is_valid = True
none_value = None
print("Type of x: " , type(x)) #Output:Type of x: class 'int'
print("Type of y: " , type(y)) #Output:Type of x: class 'float'
print("Type of name: " , type(name)) #Output:Type of x: class 'str'
print("Type of my_list: " , type(my_list)) #Output:Type of x: class 'list'
print("Type of my_tuple: " , type(my_tuple)) #Output:Type of x: class 'tuple'
print("Type of my_set: " , type(my_set)) #Output:Type of x: class 'set'
print("Type of my_dict: " , type(my_dict)) #Output:Type of x: class 'dict'
print("Type of is_valid: " , type(is_valid)) #Output:Type of x: class 'bool'
print("Type of none_value: " , type(none_value)) #Output:Type of x: class 'NoneType'
list_example = [1, "hello", 3.14]
print("Example list: " , list_example) #Output:Example list: [1, 'hello', 3.14]
tuple_example = (10, 20, 30)
print("Example tuple: " , tuple_example) #Output:Example tuple: (10, 20, 30)
dict_example = {"name": "Alice", "age": 30}
print("Example dictionary: " , dict_example) #Output:Example dictionary: {'name': 'Alice', 'age': 30}
Slicing strings:
- Slicing strings in Python allows you to extract portions of a string by specifying a range of indices.
- It's a powerful and flexible technique.
Syntax:
string[start:stop:step]
- start: The index where the slice begins (inclusive). If omitted, it defaults to 0 (the beginning of the string).
- stop: The index where the slice ends (exclusive). If omitted, it defaults to the length of the string (the end of the string).
- step: The increment between indices. If omitted, it defaults to 1.
Code Example 1:
text = "Python Programming"
substring1 = text[0:6] # or text[:6] (start defaults to 0)
print(substring1) # Output: Python
substring2 = text[7:len(text)] # or text[7:] (stop defaults to end)
print(substring2) # Output: Programming
substring3 = text[7:14]
print(substring3) # Output: Program
Code Example 2:
text = "0123456789"
# Extract every other character
substring4 = text[0:10:2] # or text[::2]
print(substring4) # Output: 02468
# Extract every third character
substring5 = text[::3]
print(substring5) # Output: 0369
Code Example 3:
text = "Hello World"
# Extract the last 5 characters
substring6 = text[-5:]
print(substring6) # Output: World
# Extract characters from the 3rd last to the 2nd character.
substring7 = text[-3:-1]
print(substring7) # Output: rl
text2 = "Python"
reversed_text = text2[::-1]
print(reversed_text) # Output: nohtyP
Further Resources:
Operators in Python
Operators are symbols that perform operations on operands. Python supports various types of operators:
- Arithmetic Operators: +, -, *, /, %, **, //. Python's division operator (/) always returns a float.
- Comparison Operators: ==, !=, >, <, >=, <=. These operators return boolean values.
- Logical Operators: and, or, not. Used to combine or negate boolean expressions.
- Assignment Operators: =, +=, -=, *=, /=, etc. Shorthand for assigning values to variables.
- Membership Operators: in, not in. Check if a value is present in a sequence.
- Identity Operators: is, is not. Check if two variables refer to the same object in memory.
- Bitwise Operators: &, |, ^, ~, <<, >>. Operate on individual bits of integers.
Code Example:
a = 10
b = 5
print("Addition: " , a + b)
print("Subtraction: " , a - b)
print("Multiplication: " , a * b)
print("Division: " , a / b)
print("Modulus: " , a % b)
print("Exponentiation: " , a ** b)
print("Floor Division: " , a // b)
print("a == b: " , a == b)
print("a > b: " , a > b)
x = True
y = False
print("x and y: " , x and y)
print("x or y: " , x or y)
print("not x: " , not x)
my_list = [1, 2, 3]
print("2 in my_list: " , 2 in my_list)
list1 = [1, 2, 3]
list2 = list1
list3 = [1, 2, 3]
print("list1 is list2: " , list1 is list2)
print("list3 is list3: " , list1 is list3) # False because they are different objects
a = 10
a += 5
print("a += 5 : " , a)
print("Bitwise AND (10 & 4): " , 10 & 4)
a=10
b=20
a=a^b
b=a^b
a=a^b
print("a=",a)
print("b=",b)
#Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Modulus: 0
Exponentiation: 100000
Floor Division: 2
a == b: False
a > b: True
x and y: False
x or y: True
not x: False
2 in my_list: True
list1 is list2: True
list3 is list3: False
a += 5 : 15
Bitwise AND (10 & 4): 0
a= 20
b= 10
Further Resources:
Conditional Statements in Python
- Conditional statements allow you to execute different blocks of code based on whether a condition is true or false.
- Python uses
if
,elif
(else if), andelse
for conditional logic. - Indentation is crucial in Python to define code blocks.
Code Example:
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
#Output: You are an adult.
score = 75
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good.")
elif score >= 60:
print("Average.")
else:
print("Needs improvement.")
#Output: Good.
number = 0
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
#Output: Zero
is_raining = True
if is_raining:
print("Take an umbrella")
else:
print("Enjoy the sunshine")
#Output: Take an umbrella
Further Resources:
Looping Statements in Python
- Looping statements allow you to repeatedly execute a block of code.
- Python provides
for
andwhile
loops. - The
for
loop is often used to iterate over sequences, while thewhile
loop continues as long as a condition is true.
Code Example:
for i in range(5):
print(i)
#Output:
0
1
2
3
4
my_list = ["apple", "banana", "cherry"]
for item in my_list:
print(item)
#Output:
apple
banana
cherry
count = 0
while count < 5:
print(count)
count += 1
#Output:
0
1
2
3
4
numbers = [1,2,3,4,5]
for number in numbers:
print(number * 2)
#Output:
2
4
6
8
10
i = 1
while i <= 5:
print(i)
i +=1
#Output:
1
2
3
4
5
Further Resources:
Nested Loops in Python
- A nested loop is a loop inside another loop.
- This is useful for iterating over multiple dimensions of data or performing operations that require multiple levels of iteration, such as processing elements in a 2D array or generating combinations.
Code Example:
for i in range(0,5):
for j in range(0,5):
print("*",end=" ")
print(" ")
#Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
for i in range(0,5):
for j in range(0,i):
print("*",end="")
print()
#Output:
*
**
***
****
for i in range(5,0,-1):
for j in range(0,i):
print("*",end="")
print()
#Output:
*****
****
***
**
*
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for row in matrix:
for element in row:
print(element,end=" ")
print()
#Output:
1 2 3
4 5 6
7 8 9
for i in range(1,4):
for j in range(1,4):
print(i*j,end=" ")
print()
#Output:
1 2 3
2 4 6
3 6 9
Further Resources:
Functions in Python
- Functions are blocks of reusable code that perform a specific task.
- They help in organizing code, making it more readable and maintainable.
- Python supports defining functions with parameters and return values.
- You can also define default parameter values and use keyword arguments.
Code Example:
#Local variable
def num():
k=80
print(k) #Output: 80
num()
#Enclosing variable
def num():
k=80
def nums():
print(k) #Output: 80
nums()
num()
#Global variable
k=80
def num():
print(k) #Output: 80
num()
#Built-In variable
from math import *
def num():
k=80
def nums():
print(k) #Output: 80
nums()
num()
Code Example:
#Without argument without return type
def sayhello():
print("Hello") #Output: Hello
sayhello()
#Without argument with return type
def sum():
a,b=10,20
return a+b
k=sum()
print(k) #Output: 30
#With argument with return type
def sum(a,b):
print(a+b) #Output: 30
sum(10,20)
#With argument with return type
def sum(a,b):
return a+b
k=sum(10,20)
print(k) #Output: 30
Code Example:
#Recursive function: A function is called repetitively by itself. A recursive can be used directly or indirectly.
def fac(n):
if n==1:
return 1
else:
return n*fac(n-1)
n=int(input("enter n:"))
k=fac(n)
print(k) #Output: enter n:5 120
def power(n,i):
if i==1:
return n
else:
return n*power(n,i-1)
n=int(input("enter n:"))
i=int(input("enter i:"))
k=power(n,i)
print(k)
#Output:
enter n:3
enter i:4
81
Further Resources:
Classes and Objects in Python
- Python is an object-oriented programming (OOP) language.
- Classes are blueprints for creating objects, and objects are instances of classes.
- OOP helps in modeling real-world entities and organizing code effectively.
- Key concepts include encapsulation, abstraction, inheritance, and polymorphism.
- It allows us to define a class that inherits all the methods and properties from another class.
- Inheritance is a powerful tool for designing and organizing object-oriented programs.
- It allows you to create more modular, reusable, and maintainable code.
- Types of Inheritance:
1, Inheritance:
a, Single Inheritance
b, Multilevel Inheritance
c, Multiple Inheritance
d, Hierachical Inheritance
Code Example:
#Single Inheritance
class Flower:
def smell(self):
print("Flower")
class Rose(Flower):
def smel(self):
print("Rose")
rr = Rose()
rr.smell()
rr.smel() #Output: Flower Rose
#Multilevel Inheritance
class Flower:
def smell(self):
print("Flower")
class Rose(Flower):
def smel(self):
print("Rose")
class Lily(Rose):
def sme(self):
print("Lily")
l = Lily()
l.smell()
l.smel()
l.sme() #Output: Flower Rose Lily
#Multiple Inheritance
class Rose:
def smell(self):
print("Rose")
class Lily:
def smel(self):
print("Lily")
class Flower(Rose, Lily):
def sme(self):
print("Flower")
f = Flower()
f.smell()
f.smel()
f.sme() #Output: Rose Lily Flower
#Hierachical Inheritance
class Flower:
def smell(self):
print("Flower")
class Rose(Flower):
def smel(self):
print("Rose")
class Lily(Flower):
def sme(self):
print("lily")
r = Lily()
rr = Rose()
rr.smell()
rr.smel()
r.sme() #Output: Flower Rose lily
- Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to respond to the same method call in a way that is specific to their type.
- In essence, it means "many forms."
- It promotes code flexibility and extensibility by allowing you to add new classes that can work with existing code without modifying it.
2, Polymorphism:
Code Example:
class Animal:
def sound(self):
print("Animal")
class Dog(Animal):
def sound(self):
print("Bow")
class Cat(Animal):
def sound(self):
print("Meow")
a = Animal()
b = Dog()
c = Cat()
for i in (a,b,c):
i.sound() #Output:Animal Bow Meow
3, Abstraction:
- It refers to the process of creating abstract classes and methods that provide a blueprint for other classes to inherit form.
Code Example:
from abc import ABC, abstractmethod
class Power(ABC):
@abstractmethod
def energy(self):
pass
class Engine(Power):
def energy(self):
print("Engine")
class Motor(Power):
def energy(self):
print("Motor")
a=Engine()
b=Motor()
for i in (a,b):
i.energy() #Output: Engine Motor
4, Encapsulation:
- Encapsulation is one of the four fundamental principles of object-oriented programming (OOP).
- It involves bundling data (attributes) and methods (functions) that operate on the data into a single unit, known as a class.
Code Example:
class base:
def _init_(self):
self.a=2
class derived(base):
def _init_(self):
base. _init_(self)
print(self.a)
self.a=3
print(self.a)
o1=derived()
o2=base()
print(o1.a)
print(o2.a) #Output: 2 3 3 2
Further Resources:
Exception Handling in Python
- When an error occurs or exceptional as we call it, Python will stop and generate an error message.
- Exception handling is the process of responding to unwanted or unexpected events that occur when a program is running.
- Python uses
try
,except
,else
, andfinally
blocks to handle exceptions. - The try block lets you test a block of code for errors.
- The except block lets you handle the error.
- The finally block lets you execute code, regardless of the result of the try and except blocks.
- The else block lets you execute code when there is no error.
Try:
Except:
Finally:
Else:
Code Example:
try:
print(x)
except:
print("An Exception occured!") #Output: An Exception occured!
try:
print(5)
except:
print("An Exception occured!")
else:
print("No error!") #Output: 5 No error!
try:
a=[1,2]
print(a[2])
except:
print("An Exception occured!")
finally:
Further Resources:
Construction and Destruction in Python
- In object-oriented programming, construction (initialization) is handled by the
init
method, which is called when an object is created. - Destruction (cleanup) is handled by the
del
method, which is called when an object is about to be destroyed. - Python's garbage collection handles most object destruction automatically, so
del
is less commonly used.
Code Example:
#Construction:
class add:
def _init_(self,a,b):
print(a+b)
a=add(5,5) #Output: 10
#Destruction:
class add:
def _del_(self):
print("5+5=10")
a=add()
del a #Output: 5+5=10
Further Resources:
Connecting Python with MySQL
- Python can interact with MySQL databases using libraries like
mysql.connector
. - This allows you to perform database operations such as querying, inserting, updating, and deleting data.
- You'll need to install the library using pip:
pip install mysql-connector-python
.
Code Example:
import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",user="root",password="pass",database="student")
if mycon.is_connected()==False:
print("error")
cursor=mycon.cursor()
cursor.execute(select * from student)
data=cursor.fetchall()
count=cursor.rowcount
for row in data:
print(row)
mycon.close()