0% found this document useful (0 votes)
9 views46 pages

Session1 2

Uploaded by

Neelesh Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views46 pages

Session1 2

Uploaded by

Neelesh Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Introduction to

Python
S I D D H A RT H B H A L E R A O
H E A D C O - O R D I N AT O R
C S - I O T, C Y B E R S E C U R I T Y I N C LU D I N G B LO C KC H A I N T E C H N O LO GY
GYA N G A N G A I N S T I T U T E O F T E C H N O LO GY A N D S C I E N C E S ,
JABALPUR
Introduction to Python Programing Language

• Python is a high-level, interpreted programming language.

• It is widely used for web development, data analysis, machine learning, and scientific computing.

• It is known for its simplicity, readability, and flexibility, as well as its large and active community of users and
developers.

• Python is an interpreted programming language, which means that most of its implementations execute
instructions directly, without previously compiling a program into machine-language instructions.

• It was created by Guido van Rossum a Dutch computer programmer and first released in 1991.

• Rossum named it “Python” after a famous Brititsh comedy TV series “Monty Python’s Flying Circus”.
Features of Python
• Dynamic typing: Python is a dynamically-typed language, which means that variables do not have a fixed type and can
change their type at runtime.

• Object-oriented programming: Python supports object-oriented programming, with features such as classes,
inheritance, and polymorphism.

• Standard library: Python has a large and comprehensive standard library, which includes modules for tasks such as file
I/O, networking, and data manipulation.

• Python is known for its simplicity and readability, with a syntax that is easy to understand and use.

• GUI Programming Support: Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or
Tk in python.

Python Indentation
• Python uses indentation to define blocks of code, rather than using delimiters such as curly braces.

• This means that the level of indentation in a Python program is significant, and must be consistent within a block of
code. Common indentation levels are 4 spaces or 1 tab.
CPython: Reference Implementation of Python

• CPython is the reference implementation of the Python programming language.

• It is written in C and Python, and is the most widely used implementation of Python, especially on
platforms where pre-compiled versions are not available.

• CPython is developed and maintained by the Python Software Foundation, an organization that promotes
the development and use of Python.

• It is open source and available under the Python Software Foundation License, which is a permissive free
software license.

• CPython is known for its performance and reliability, and is used in a wide range of applications, including
web development, data analysis, machine learning, and scientific computing.

• It is also used as the primary implementation for many popular Python libraries and frameworks, such as
Django and NumPy.
Alternate Implementations of Python

• There are several other implementations of the Python programming language in addition to CPython, the
reference implementation. Some of the most popular implementations include:

• PyPy: A high-performance implementation of Python that is written in Python and can be faster than
CPython for some workloads. PyPy is developed by the PyPy Project, a community-driven project that aims
to improve the performance and flexibility of Python.

• Jython: An implementation of Python that is written in Java and can be used to run Python code on the Java
Virtual Machine (JVM).

• IronPython: An implementation of Python that is written in C# and can be used to run Python code on
the .NET Common Language Runtime (CLR).

• Stackless Python: A variant of CPython that is designed to support microthreads and tasklets, which allow
for more fine-grained control over concurrency and parallelism.
How to get Python?

• Install Python directly by downloading the


latest version of Python from the official
Python website.

• https://www.python.org/downloads/windo
ws/

• This is the most straightforward way to


install Python.

• It is required to manually set up the


environment and manage updates.
How to get Python?
• By installing a pre-packaged distribution.

• There are several pre-packaged distributions


of Python that include a bundle of popular
libraries and tools.

• These distributions can be useful as they


provide ready-to-use Python environment
with a wide range of tools and libraries.

• They are often easier to install and manage


than installing Python and its dependencies
manually.

• One of the most popular Python distributions


is Anaconda.

• https://www.anaconda.com/
Integrated Development Environments (IDEs) and Editors

There are several popular integrated development environments (IDEs) for Python, each with its own set of
features and capabilities. Some popular IDEs for Python include:

• IDLE: IDLE (Integrated Development and Learning Environment) is the default IDE that comes with
Python.

• Visual Studio Code: Visual Studio Code is a lightweight, open-source code editor that can be used for
Python development.

• PyCharm: PyCharm is a powerful, cross-platform IDE developed by JetBrains.

• Spyder: Spyder is an open-source scientific development environment for Python.


• Jupyter Notebook: It is a powerful open-source editor for interactive computing and data visualization. It
is often used for scientific computing, data analysis, and machine learning, and supports many
programming languages, including Python.

• Google Colab: It is a free online platform that allows to run and execute Jupyter notebooks in the cloud.

• It provides access to a wide range of powerful computing resources, including GPUs and TPUs, making it
ideal for machine learning and data analysis.

• We would be using Google Colab for current session.

• https://colab.research.google.com/
Python Tokens

• In a programming language, tokens are the basic elements that make up the source code of a program.

• They are the smallest unit of meaning that can be identified and processed by the compiler or
interpreter.

• Python tokens are the basic building blocks of a Python program. They include:
• Keywords: Words that have a special meaning in Python and cannot be used as variables or function
names. Examples include "if", "else", and "for".
• Identifiers: Names used to identify variables, functions, classes, and other objects in a Python
program. Identifiers must start with a letter or an underscore, and can contain letters, underscores,
and digits, but no other characters.
• Literals: Fixed values that are written directly into the source code of a Python program. Examples
include numbers, strings, and booleans.
• Operators: Symbols that represent operations such as addition, subtraction, and comparison.
• Delimiters: Symbols that are used to mark the beginning and end of blocks of code, such as
parentheses, brackets, and curly braces.
Datatypes in Python

• 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.

• Python has several built-in datatypes that can be used to store and manipulate data.
Datatypes in Python

Numeric

Python has several built-in numeric types for storing and manipulating numbers. These include:

• int (integers): Whole numbers, such as -1, 0, and 1.

• float (floating point numbers): Numbers with a decimal point, such as 1.0, 2.5, and 3.14.

• complex (complex numbers): Numbers with a real and an imaginary component, such as 3+2j.

Boolean
• Python has a built-in Boolean type called "bool" for storing and manipulating truth values (True or False).
Datatypes in Python

Sequence

Python has several built-in sequence types for storing and manipulating collections of values. These
include:

• list: Ordered collections of items that can be of any datatype. Lists are mutable, meaning that they can
be modified after they are created.

• tuple: Like lists, but they are immutable, meaning that they cannot be modified once they are created.

• string: Python has a built-in string type for storing and manipulating text data. Strings are immutable,
meaning that they cannot be modified once they are created.
Datatypes in Python

Sets
• In Python, a set is an unordered collection of unique elements.

• Sets are mutable, meaning that they can be modified after they are created.

Dictionary
• In Python, a dictionary is a mutable data type that stores a collection of key-value pairs.

• Dictionaries are also known as associative arrays or hash maps.


Obtaining User Input

• In Python, the input() function is used to read user input from the command line or console.

• It reads the input as a string.


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

• To read an integer value from the user, the int() function is used to convert the input string to an integer.

• Similarly, float() is used to convert the input to a floating-point number or bool() to convert it to a boolean
value.

age = int(input("Enter your age: "))


print("You are " + str(age) + " years
old.")
Python Lists # Access elements in a list
print(numbers[0]) # 1
print(words[1]) # "banana"

# Create a list of integers # Modify elements in a list


numbers = [1, 2, 3, 4, 5] numbers[0] = 10
words[1] = "orange"
# Create a list of strings
words = ["apple", "banana", # Add elements to a list
"cherry"] numbers.append(6)
words.extend(["date", “pear"])
# Create a list of mixed data types
mixed = [1, "cat", 3.14, [4, 5]] # Remove elements from a list
del numbers[1]
words.remove("date")

# Find the length of a list


print(len(numbers)) # 5
print(len(words)) # 4
List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuple Methods # Create a tuple
t = (1, 2, 3, 4, 5)
Python has two built-in methods that
can be used on tuples. # Find the length of a tuple
print(len(t)) # 5

• count() # Check if an element is in a tuple


• index() print(3 in t) # True
print(6 in t) # False

# Count the number of occurrences of an


element in a tuple
print(t.count(3)) # 1
print(t.count(6)) # 0

# Find the index of an element in a tuple


print(t.index(3)) # 2

# Try to modify an element in a tuple (this


will raise a TypeError)
t[0] = 10
Python Sets

# Create a set with curly braces # Add an element to a set


fruits = {'apple', 'banana', 'orange'} fruits.add('mango')

# Create a set with the set() function # Remove an element from a set
numbers = set([1, 2, 3, 3, 4]) fruits.remove('banana')

# Create an empty set # Find the intersection of two sets


empty_set = set() vegetables = {'carrot', 'lettuce',
'spinach','tomato'}
fruits.add('tomato')

healthy_foods = fruits & vegetables


print(healthy_foods)

print(fruits.intersection((vegetables)))

# Find the union of two sets


all_foods = fruits | vegetables
print(all_foods) # prints {'apple', 'carrot',
'lettuce', 'mango', 'orange', 'spinach'}
print(vegetables.union(fruits))
Set Methods

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable
Python Dictionaries

# create an empty dictionary


my_dict = {}

# add some key-value pairs to the


dictionary
my_dict['a'] = 1
my_dict['b'] = 2
my_dict['c'] = 3

# print the dictionary


print(my_dict)

# access the value for a key


value = my_dict['a']
print(value)
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Strings in Python

# Using single quotes


string1 = 'Hello, World!'

# Using double quotes


string2 = "Hello, World!"

# Using triple quotes (single or double)


string3 = '''Hello, World!'''
string4 = """Hello, World!"""
String Methods

Method Description
len(string) Returns the length of the
strip() Returns a copy of the string with leading and trailing whitespace removed.
lower() Returns a copy of the string in lowercase.
upper() Returns a copy of the string in uppercase.
replace(old, new) Returns a copy of the string with all occurrences of the substring old replaced
with the substring new.
split(separator) Returns a list of substrings in the string, using the specified separator as the
delimiter.
join(iterable) Returns a string in which the string elements of the iterable have been joined by
the
startswith(prefix) Returns True if the string starts with the specified prefix, and False otherwise.
endswith(suffix) Returns True if the string ends with the specified suffix, and False otherwise.
Strings in Python
string = " This is a sample string. "

# Strip leading and trailing whitespace


stripped_string = string.strip()
print(stripped_string) # Output: "This is a sample string."

# Convert to uppercase
uppercase_string = string.upper()
print(uppercase_string) # Output: " THIS IS A SAMPLE STRING. "

# Replace a substring
replaced_string = string.replace("sample", "test")
print(replaced_string) # Output: " This is a test string. "

# Split the string into a list of substrings


split_string = string.split(" ")
print(split_string) # Output: ['', '', '', 'This', 'is', 'a', 'sample', 'string.',
'', '', '']
String Formatting Python

• In Python, we can use string formatting to construct strings from variables and other values.

• There are several ways to format strings in Python.

• The % operator, also known as the "old-style" string formatting method.

• The str.format() method, which is a more powerful and flexible way to format strings.

• "f-strings", also known as formatted string literals, which are a concise and convenient way to format
strings introduced in Python 3.6.
Operators in Python
• In Python, operators are symbols that represent operations such as addition, subtraction, and
comparison.

• Python has several built-in operators that can be used to manipulate data and control the flow of a
program.

Source: https://www.techvidya.education/
Arithmetic Operators

Python has the following arithmetic operators:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
// Integer division
% Modulus (remainder)
** Exponentiation
Assignment Operators

Python has the following assignment operators:

Operator Description
= Simple assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
//= Integer division assignment
%= Modulus assignment
**= Exponentiation assignment
Comparison Operators

• In Python, comparison operators are used to compare the values of two variables or expressions.

• These operators return a boolean value, either True or False, depending on the evaluation of the
comparison.

Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical Operators

• In Python, logical operators are used to perform logical operations on boolean values (True and False).

• Logical operators in Python:

Operator Description
and Logical AND
or Logical OR
not Logical NOT
Bitwise Operators
• In Python, bitwise operators are used to perform bit-level operations on integers.

• Bitwise operators in Python:

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Bitwise left shift
>> Bitwise right shift
Identity Operators
• In Python, the identity operator is used to check if two variables refer to the same object in memory.

• The identity operator is is, and it returns a boolean value indicating whether the two operands are the
same object or not.

Operator Description
is Check if two variables refer to the same object

Membership Operators
• The membership operator is used to check if an element is a member of a
sequence (such as a string, list, tuple, or set).
• The membership operator is in, and it returns a boolean value indicating whether
the element is a member of the sequence or not.

Operator Description
in Check if an element is a member of a sequence
Control Statements
If Statement

• The if statement is used to execute a block of code if a certain condition is true.


• The basic syntax for an if statement:
if condition:
# code to be executed if condition is
True
# code statements
# rest of the code
• Example

x = 10
if x > 0:
print("x is positive")
print("Hello")
If-else Statement
• The if-else statement is used to execute one block of code if a condition is true,
and another block of code if the condition is false.
• The basic syntax for an if-else statement:

if condition:
# code to be executed if condition is
True
else:
• # code to be executed if condition is
Example
False

x = 10
if x > 0:
print("x is positive")
else:
print("x is not positive")
If-elif Statement
• The if-elif statement is used to execute one of several blocks of code based on
multiple conditions.

• It is used when multiple conditions are there and requires execution of different
block of code for each condition.

• The basic syntax for an if-elif statement:


if condition1:
# code to be executed if condition1 is True
elif condition2:
# code to be executed if condition1 is False and condition2 is True
elif condition3:
# code to be executed if condition1 and condition2 are False and
condition3 is True
...
else:
# code to be executed if none of the conditions are True
If-elif Statement
• Example
# Determine a student's grade based on their marks

marks = 87

if marks >= 90:


grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"

print(f"The student's grade is: {grade}")


Loops in Python

• Loops are used to execute a block of code multiple times. There are two types of loops in Python: for loops and while
loops.

• A for loop is used to iterate over a sequence of elements, such as a list or a string.

• In this example, a for loop iterates over a list of numbers and prints each one to the console.

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

for number in numbers:


print(number)
• A while loop is used to repeat a block of code as long as a certain condition is true.

• In loops, break statement can be used to exit a loop prematurely, and the continue statement to skip the
rest of the current iteration and move on to the next one.

count = 10

while count > 0:


print(count)
count -= 1
User Defined Functions in Python

• A function is a block of code that can be defined once and called multiple times in a program.

• Functions are used to modularize and reuse code, making it easier to write, read, and maintain.

def calculate_area(length, width):


area = length * width
return area

area = calculate_area(5, 10)


print(area)
• We can define default values for function parameters, which means that the parameter is optional and can
be omitted when the function is called.

• If a default value is not provided, the parameter is considered required and must be specified when the
function is called.

def calculate_area(length, width=1):


area = length * width
return area

area = calculate_area(5)
print(area)
area = calculate_area(5, 10)
print(area)
Introduction to Python Classes

• Classes are a fundamental part of object-oriented programming (OOP).

• They allow the definition of custom data types that can contain both data and behavior.

• Classes are defined using the class keyword, and they can be used to create objects (also known as
instances).

• To define a class in Python, use the class keyword followed by the name of the class.

• The class definition should include a __init__ method, which is a special method that is called when an
object is created.

• This method is used to initialize the object's attributes.


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

person = Person("John", 30)

print(person.name,person.age)
# setting value
person.age = 35
print(person.name,person.age)

• In addition to attributes, classes can also have methods.

• Methods are functions that are defined within the class and can operate on the object's data.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def sayHello(self):
print("Hello, my name is " +
self.name)

• To call a method on an object, the dot notation is followed by the method name and any required
arguments.

person = Person("Simar", 30)


person.sayHello()
Click icon to add picture

Thank You

You might also like