0% found this document useful (0 votes)
3 views43 pages

Python Training

The document provides a comprehensive overview of Python programming, covering its history, installation, variables, data types, input/output, operators, control structures, functions, classes, and inheritance. It explains key concepts such as encapsulation, method overriding, and the use of constructors in Python. Additionally, it includes examples and syntax for various programming constructs to aid in understanding Python's functionality.

Uploaded by

saranjan.h
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
3 views43 pages

Python Training

The document provides a comprehensive overview of Python programming, covering its history, installation, variables, data types, input/output, operators, control structures, functions, classes, and inheritance. It explains key concepts such as encapsulation, method overriding, and the use of constructors in Python. Additionally, it includes examples and syntax for various programming constructs to aid in understanding Python's functionality.

Uploaded by

saranjan.h
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 43

Python Basic to Advanced

Programming

www.bahwancybertek.com
© Bahwan CyberTek
History of Python and Who Invented Python?

• Python is a widely used general-purpose, high-level


programming language. It was initially designed
by Guido van Rossum in 1991 and developed by
Python Software Foundation. It was mainly
developed to emphasize code readability, and its
syntax allows programmers to express concepts in
fewer lines of code.

• In the late 1980s, history was about to be written. It


was that time when working on Python started. Soon
after that, Guido Van Rossum began doing its
application-based work in December of 1989 at
Centrum Wiskunde & Informatica (CWI) which is
situated in the Netherlands. It was started as a
hobby project because he was looking for an
interesting project to keep him occupied during
Christmas.
© Bahwan CyberTek 2
- Why Python called Python?

• The inspiration for the name came from the BBC’s


TV Show – ‘ Monty Python’s Flying Circus’ , as he
was a big fan of the TV show and also he wanted a
short, unique and slightly mysterious name for his
invention and hence he named it Python! He was the
“Benevolent dictator for life” (BDFL) until he stepped
down from the position as the leader on 12th July
2018. For quite some time he used to work for
Google, but currently, he is working at Dropbox

© Bahwan CyberTek 3
Install python on windows machine

1.Download python from

https://www.python.org/downloads/

© Bahwan CyberTek 4
Install python on windows machine continue …..

• Go to the downloaded location and double click the


file python-3.13.1-amd64

© Bahwan CyberTek 5
Click Customize installation

© Bahwan CyberTek 6
Click next
Before that Create a folder ”Python” in D
drive for python installation . Brows and select the
installation directory

© Bahwan CyberTek 7
Click install to install python in the selected folder

© Bahwan CyberTek 8
© Bahwan CyberTek 9
Verify python installation
Open command prompt and type python --version

Will get python installed version

© Bahwan CyberTek 1
0
To run python script in command prompt

type python and enter , you will get python command execution
prompt where you can type and execute your script. (type clear
to clear the screen)

© Bahwan CyberTek 1
1
Python Variable

• Python Variable is containers that store values. Python is not “statically typed”.
An Example of a Variable in Python is a representational name that serves as a
pointer to an object. Once an object is assigned to a variable, it can be referred
to by that name
Rules for Python variables
A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
The reserved words(keywords) in Python cannot be used to name the variable in
Python
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
© Bahwan CyberTek 1
2
Python Data Types

• Data types are the classification or categorization of data items. It represents


the kind of value that tells what operations can be performed on a particular
data. Since everything is an object in Python programming, data types are
classes and variables are instances (objects) of these classes.

© Bahwan CyberTek 1
3
Description of the data types

1. Numeric – Integer , float and complex


2. Dictonary - dictionaries are mutable data structures that allow you to
store key-value pairs .You can create using the dict() constructor or
curly braces’ {}. you can add, remove, or update elements using the
methods dict. update(), dict. pop()
3. Boolean – logical (true or false )
4. Set – stores collection of unique elements
5. Sequence type - It is a type that stores more than one item at a
time. Therefore, we can say that it is a collection of items. Moreover,
to access these items each item has a particular index number.
There are three types of sequence data types namely, strings, lists,
and tuples
6. List - list is a data structure in Python that is a mutable, or
changeable, ordered sequence of elements
7. tuple is a built-in data type that allows you to create immutable
sequences of values
8. strings are used for representing textual data. A string is a sequence
of characters enclosed in either single quotes ('') or double quotes
(“”). The Python language provides various built-in methods and
functionalities to work with strings efficiently
© Bahwan CyberTek 1
4
Data types example

•x = "Hello World" # string


•x = 50 # integer
•x = 60.5 # float
•x = 3j # complex
•x = ["geeks", "for", "geeks"] # list
•x = ("geeks", "for", "geeks") # tuple
•x = {"name": "Suraj", "age": 24} # dict
•x = {"geeks", "for", "geeks"} # set
•x = True # bool
•x = b"Geeks" # binary

© Bahwan CyberTek 1
5
Python Input/Output

• This function first takes the input from the user and
converts it into a string. The type of the returned
object always will be <class ‘str’>. It does not
evaluate the expression it just returns the complete
statement as String, and will print it.

• Example :
• # Python program show input and Output
• val = input("Enter your value: ")
• print(val)

© Bahwan CyberTek 1
6
Python Operators

In Python programming, Operators in general are used to perform


operations on values and variables. These are standard symbols used
for the purpose of logical and arithmetic operations. In this article, we
will look into different types of Python operators.
1.Arithmetic Operators
2. Logical Operators
3. Bitwise Operators
4. Assignment Operators
Python If Else
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")

© Bahwan CyberTek 1
7
Python if-elif-else ladder

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

© Bahwan CyberTek 1
8
Python For Loop and Python While Loop

• Python For loop is used for sequential traversal i.e. it is used for
iterating over an iterable like String, Tuple, List, Set, or Dictionary.
Here we will see a “for” loop in conjunction with the range() function
to generate a sequence of numbers starting from 0, up to (but not
including) 10, and with a step size of 2. For each number in the
sequence, the loop prints its value using the print() function.
# Python program to illustrate for loop

for i in range(0, 10, 2):


print(i)

# Python program to illustrate while loop


count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

© Bahwan CyberTek 1
9
Python Functions

• Python Functions is a block of statements that return the specific


task. The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the same code
again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again.

© Bahwan CyberTek 2
0
Cont…

• Note: There are mainly two types of functions in Python.


1.Built-in library function: These are Standard functions in Python
that are available to use.

2.User-defined function: We can create our own functions based on


our requirements.

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Code to call the function
evenOdd(2)
evenOdd(3)
© Bahwan CyberTek 2
1
What are Classes and Objects in Python?

Python classes and objects are the starting point in Python Programming.
A class in Python is a blueprint for an object and the object in Python is an
instance of it but with real values. They make the code more organized and
structured
Define Python Class
class ClassName:
# class definition
Ex:
class Bike:
name = ""
gear = 0
Here,
Bike - the name of the class
name/gear - variables inside the class with default values "" and 0
respectively.
Note: The variables inside a class are called attributes.

© Bahwan CyberTek 2
2
Python Objects

An object is called an instance of a class.


Suppose Bike is a class then we can create objects like bike1, bike2, etc from the
class.

Here's the syntax to create an object. objectName = ClassName()

Example :
# create class
class Bike:
name = ""
gear = 0

# create objects of class


bike1 = Bike()

Here, bike1 is the object of the class. Now, we can use this object to access the
class attributes.

© Bahwan CyberTek 2
3
Access Class Attributes Using Objects

We use the . notation to access the attributes of a class. For example,


# modify the name property
bike1.name = "Mountain Bike"
# access the gear property
bike1.gear
Here, we have used bike1.name and bike1.gear to change and access
the value of name and gear attributes, respectively.
Example :
class Bike:
name = ""
gear = 0
bike1 = Bike()
bike1.gear = 11;
bike1.name = "TVS"
print(f"Name : {bike1.name}, Gear: {bike1.gear}")

© Bahwan CyberTek 2
4
Python Constructors

we can also initialize values using the constructors. For example,


class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()
Here, __init__() is the constructor function that is called whenever a new object of
that class is instantiated.
The constructor above initializes the value of the name attribute.
We have used the self.name to refer to the name attribute of the bike1 object.
If we use a constructor to initialize values inside a class, we need to pass the
corresponding value during the object creation of the class.

bike1 = Bike("Mountain Bike")

© Bahwan CyberTek 2
5
Python Methods

# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)

# create object of Room class


study_room = Room()
# assign values to all the properties
study_room.length = 42.5
study_room.breadth = 30.8
# access method inside class
study_room.calculate_area()

© Bahwan CyberTek 2
6
Encapsulation in Python

Encapsulation refers to the bundling of data (attributes) and methods (functions)


that operate on the data into a single unit, typically a class. It also restricts direct
access to some components, which helps protect the integrity of the data and
ensures proper usage.
Public Members: By default, attributes and methods are public and can be
accessed from outside the class.
Protected Members: Use a single underscore (_) prefix to indicate that an
attribute or method is intended for internal use within the class and its
subclasses.
Private Members: Use double underscores (__) prefix to make an attribute or
method private. This leads to name mangling, making it more challenging to
access from outside the class.

© Bahwan CyberTek 2
7
Python Encapsulation -Examples

Public :

class MyClass:
def __init__(self, value):
self.value = value # Public attribute
def show_value(self): # Public method
print(self.value)
# Usage
obj = MyClass(10)
obj.show_value() # Accessing public method
print(obj.value) # Accessing public attribute

© Bahwan CyberTek 2
8
Private Access Modifier

class MyClass:
def __init__(self, value):
self.__value = value # Private attribute
def __show_value(self): # Private method
print(self.__value)
def public_method(self): # Public method
self.__show_value() # Accessing private method within the
class

# Usage
obj = MyClass(10)
# obj.__show_value() # This would raise an AttributeError
# print(obj.__value) # This would raise an AttributeError
obj.public_method() # Accesses private method through a
public method
© Bahwan CyberTek 2
9
Protected Access Modifier

class BaseClass:
def __init__(self, value):
self._value = value # Protected attribute
def _show_value(self): # Protected method
print(self._value)
class SubClass(BaseClass):
def display(self):
self._show_value() # Accessing protected method from the
subclass
# Usage
obj = SubClass(10)
obj.display() # Accessing protected method via public method
in subclass
print(obj._value) # Accessing protected attribute directly (not
recommended)
© Bahwan CyberTek 3
0
Python Inheritance

Being an object-oriented language, Python supports class inheritance. It allows


us to create a new class from an existing one.
The newly created class is known as the subclass (child or derived class).
The existing class from which the child class inherits is known as the superclass
(parent or base class).
Python Inheritance Syntax
# define a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class

we are inheriting the sub_class from the super_class

© Bahwan CyberTek 3
1
Inheritance Example
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", self.name)
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
labrador.name = "Rohu"
labrador.eat()
# call subclass method
labrador.display()

© Bahwan CyberTek 3
2
Method Overriding in Python Inheritance

what if the same method is present in both the superclass and


subclass?
n this case, the method in the subclass overrides the method in the superclass.
This concept is known as method overriding in Python.
class Animal:
# attributes and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# override eat() method
def eat(self):
print("I like to eat bones")
# create an object of the subclass
labrador = Dog()
# call the eat() method on the labrador object
labrador.eat()
© Bahwan CyberTek 3
3
The super() Function in Inheritance

same method (function) in the subclass overrides the method in the superclass.
if we need to access the superclass method from the subclass, we use the
super() function
class Animal:
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# override eat() method
def eat(self):
# call the eat() method of the superclass using super()
super().eat()
print("I like to eat bones")
# create an object of the subclass
labrador = Dog()
labrador.eat()

© Bahwan CyberTek 3
4
Abstract Classes in Python

In Python, an abstract class is a class that cannot be instantiated on its own and
is designed to be a blueprint for other classes. Abstract classes allow us to define
methods that must be implemented by subclasses, ensuring a consistent
interface while still allowing the subclasses to provide specific implementations.
Example :
# Define an abstract class
class Animal(ABC):
@abstractmethod
def sound(self):
pass # This is an abstract method, no implementation here.
# Concrete subclass of Animal
class Dog(Animal):
def sound(self):
return "Bark" # Providing the implementation of the abstract method
# Create an instance of Dog
dog = Dog()
print(dog.sound()) # Output: Bark

© Bahwan CyberTek 3
5
Defining REST

REST is an acronym for “REpresentational State Transfer” which is simply an


architectural style originally written about by Roy Fielding in his doctoral
dissertation
Rest enabling communication between client and server applications over the
internet using HTTP requests
the caller (or client):Makes an HTTP request to a URL…
Using one of the standard HTTP methods (GET, PUT, POST, PATCH, DELETE, etc.)

With some content (usually JSON) in the body…And waits for a response, which:
Indicates status via an HTTP response code and usually has more JSON in the
body.

© Bahwan CyberTek 3
6
HTTP response status codes

© Bahwan CyberTek 3
7
To work with Rest API we need Request package
installed on client machine .Follow the below steps to
install the package

© Bahwan CyberTek 3
8
POST Example & Get Request

Post Example :
import requests
api_url = "http://localhost:8080/api/tutorials"
tutorials= {'title': 'H2 DB Complete Guide', 'description': 'Python
Example program'}
response = requests.post(api_url, json=tutorials)
print(response.json())
print(response.status_code)

Get Example:

import requests
api_url = "http://localhost:8080/api/tutorials"
response = requests.get(api_url)
#response.json()
print(response.json())
© Bahwan CyberTek 3
9
PUT and DELETE Request
import requests
api_url = "http://localhost:8080/api/tutorials/6352"
tutorials= {'id': 6352, 'title': 'Python Complete Complete Guide',
'description': 'Python Example program', 'published': True}
response = requests.put(api_url, json=tutorials)
print(response.json())
print(response.status_code)
print("****************************
*********");
print("**************************** calll get request to see the test
reqult *********");
api_url = "http://localhost:8080/api/tutorials"
response = requests.get(api_url)
#response.json()
print(response.json())
print(response.status_code)

© Bahwan CyberTek 4
0
Delete Request

import requests
api_url = "http://localhost:8080/api/tutorials/6352"
response = requests.delete(api_url)
print(response.status_code)

© Bahwan CyberTek 4
1
PATCH Request

import requests
api_url = "http://localhost:8080/api/tutorials/6352"
tutorials= {'title': 'Mastering Python Program '}
response = requests.patch(api_url, json=tutorials)
print(response.json())
print(response.status_code)
print("**************************** *********");
print("**************************** calll get request to see the test
reqult *********");
api_url = "http://localhost:8080/api/tutorials"
response = requests.get(api_url)
#response.json()
print(response.json())
print(response.status_code)

© Bahwan CyberTek 4
2
© Bahwan CyberTek 4
3

You might also like