python ppt
python ppt
• Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van
Rossum at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
• The initial version was published at the alt.sources newsgroup in 1991, and version 1.0 was released
in 1994.
• Python 2.0 was released in 2000, and the 2.x versions were the prevalent releases until December
2008. At that time, the development team made the decision to release version 3.0.
• Python is still maintained by a core development team at the Institute, and Guido is still in charge,
having been given the title of BDFL (Benevolent Dictator For Life) by the Python community.
• The name Python, by the way, derives not from the snake, but from the British comedy troupe
Monty Python’s Flying Circus, of which Guido was, and presumably still is, a fan.
Features in Python
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, objects encapsulation, etc.
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in
python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember
the system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and
also we can compile that code in C/C++ language.
Feature cont.
8. Python is Integrated language:
Python is also an Integrated language because we can easily integrated python with other
languages like c, c++, etc.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like
other languages C, C++, Java, etc. there is no need to compile python code this makes it easier to
debug our code. The source code of python is converted into an immediate form called bytecode.
Feature cont.
Python variables
Rohit
puja Soham
How I
store
Data??
Rahul
student
Rohit
0X2258
Python Data Types
Python data types are divided in two categories, mutable data types and immutable data
types.
# Integer number
num = 100
print(num)
print("Data Type of variable num is", type(num))
Output
Float – Values with decimal points are the float values, there is no need to specify the data type in
Python. It is automatically inferred based on the value we are assigning to a variable. For example
here fnum is a float data type.
# float number
fnum = 34.45
print(fnum)
print("Data Type of variable fnum is", type(fnum))
Output:
Complex Number – Numbers with real and imaginary parts are known as complex numbers. Unlike
other programming language such as Java, Python is able to identify these complex numbers with the
values. In the following example when we print the type of the variable cnum, it prints as complex
number.
# complex number
cnum = 3 + 4j
print(cnum)
print("Data Type of variable cnum is", type(cnum))
Output:
Complex Numbers Data Types
• Complex numbers have a real and imaginary part, a + bc, where a is the real part and b is the
imaginary part
• Complex numbers are specified as <real part>+<imaginary part>j. .
(Example – 5 + 10j).
For example:
(2+3j)
type(2+3j)
Output:
complex
Boolean Data Types
• These values can be used for assigning and comparison.
• boolean values True and False.
• Booleans are a subtype of plain integers.
Example 1 Boolean Data Type: Example 3 Boolean Data Type :
A=True; var1 = 0
B=False; print(bool(var1))
print(A&B) ;
print(A|B); var2 = 1
Output: print(bool(var2))
False
True Output:
Example 2 Boolean Data Type : False
True
print(True+False+True)
Output:
2
Note: Python treats a True value as 1 and a False value as 0. So the above example returns 2(1+0+1).
Binary, Octal and Hexadecimal numbers
In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
prefixes.
0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number
0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number
0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number
Output:
# integer equivalent of binary number 101
num = 0b101
print(num)
Logical Operators
operator
Bitwise Operator
Assignment Operator
Identity Operator
Membership Operator
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like
addition, subtraction, multiplication, and division.
/
Division (float): divides the first operand by x/y
the second
//
Division (floor): divides the first operand by x // y
the second
%
Modulus: returns the remainder when the x%y
first operand is divided by the second
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
Output
mul = a * b 13
# Division(float) of number
5
div1 = a / b 36
# Division(floor) of number
2.25
div2 = a // b 2
# Modulo of both number
1
mod = a % b 6561
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Comparison operators:
Comparison operators are used to compare values. It returns either True or False according to the condition.
< Less than: True if the left operand is less than the x<y
right
<= Less than or equal to True if the left operand is less x <= y
than or equal to the right
# Examples of Relational Operators
a = 13
b = 33
# a > b is False
print(a > b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT (and, or,
not )operations. It is used to combine conditional statements.
and Logical AND: True if both the operands are true x and y
| Bitwise OR x|y
~ Bitwise NOT ~x
+= Add AND: Add right-side operand with left side operand and then assign to left operand a+=b a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b a=a*b
/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b
%= Modulus AND: Takes modulus using left and right operands and assign the result to left operand a%=b a=a%b
//=
Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left a//=b a=a//b
operand
**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b a=a**b
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left operand a <<= b a= a << b
# Examples of Assignment Operators
a = 10
# Assign value
b=a
print(b)
a = 10
b = 20
Output
c=a
True
True
print(a is not b)
print(a is c)
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a sequence.
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Python Token:
A token is the smallest individual meaningful component in a python program
1. Keywords: Keywords are words that have some special meaning or significance
in a programming language. They can’t be used as variable names, function names,
or any other random purpose.
2. Identifiers: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language and it has some
rules and regulations to name an identifier.
Rules
Integer Literal:
Float Literal:
List: Complex Literal:
Tuple:
Dictionary:
Set:
Python string:
• Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
• Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters.
‘’’ I am going to
‘Hello world’ “Hello world”
School ’’’
#Using single quotes
str1 = 'Hello Python' Output:
print(str1) Hello Python
#Using double quotes Hello Python
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index does
n't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
The slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given
string. Consider the following example.
# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1. The second rightmost index indicates -2, and so on.
Consider the following image.
[:] It is known as range slice operator. It is used to access the characters from
the specified range.
not in It is also a membership operator and does the exact reverse of in. It returns
true if a particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where
we need to print the actual meaning of escape characters such as
"C://python". To define any string as a raw string, the character r or R is
followed by the string.
Example
The following example shows the usage of upper()
method.
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string
Example
print(x) print(x)
output 21 output
8
print(txt.find("q"))
print(txt.index("q"))
output -1
lower() method
Syntax
string.lower()
Example
x = txt.lower()
print(x)
capitalize() Method
Example
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)
output
Syntax
Parameter Description
value Required. A String. The string to value to search for
start Optional. An Integer. The position to start the search. Default is 0
end Optional. An Integer. The position to end the search. Default is the end of the string
Example
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
Example
Search from position 10 to 24:
print(x)
String join() Method
Python String join() method is a string method and returns a string in which the elements of
the sequence have been joined by the str separator.
Syntax:
string_name.join(iterable)
Parameters:
The join() method takes iterable – objects capable of returning their
members one at a time. Some examples are List, Tuple, String,
Dictionary, and Set
Return Value:
The join() method returns a string concatenated with the elements
of iterable.
list1 = ['1','2','3','4']
s = "-"
s = s.join(list1)
print(s)
Output
1-2-3-4
len()
len() Syntax
The syntax of len() is: len(s)
len() Parameters
The len() function takes a single argument s, which can be
testString = 'Python'
print('Length of', testString, 'is', len(testString))
Output:
Length of is 0
Length of Python is 6
isalnum()
It checks if all the characters are alphanumeric then returns True
Syntax:
str_name.isalnum() name = "M234onica"
print(name.isalnum())
# contains whitespace
Output:
name = "M3onica Gell22er "
True
print(name.isalnum())
False
True
name = "Mo3nicaGell22er"
True
print(name.isalnum())
name = "133"
print(name.isalnum())
Working of isalnum()
name = "M0n1caG3ll3r"
if name.isalnum() == True:
print("All characters of string (name) are alphanumeric.")
else:
print("All characters are not alphanumeric.")
isalpha()
It checks if all the characters are alphabet (a-z) then returns True
# contains whitespace
name = "Monica Geller"
print(name.isalpha())
# contains number
name = "Mo3nicaGell22er"
print(name.isalpha())
Output:
True
False
False
name = "MonicaGeller"
if name.isalpha() == True:
print("All characters are alphabets")
else:
print("All characters are not alphabets.")
Output:
All characters are alphabets
isdigit() method
The isdigit() method returns True if all characters in a string are digits. If not, it returns False.
str2 = 'python'
print(str2.isdigit()) s = '23455'
print(s.isdigit())
# Output: True
# False #s = '²3455'
# subscript is a digit
s = '\u00B23455'
print(s.isdigit())
# s = '½'
# fraction is not a digit
s = '\u00BD'
print(s.isdigit())
True
True
False
islower() islower() is a built-in method used for string handling. The islower() method returns True if
all characters in the string are lowercase, otherwise, returns “False”.
Syntax :
string.islower() string = 'geeksforgeeks'
print(string.islower())
string = 'GeeksforGeeks'
print(string.islower())
Output:
True
False
isupper() In Python, isupper() is a built-in method used for string handling. This
method returns True if all characters in the string are uppercase,
otherwise, returns “False”.
Syntax : Examples:
string = 'GeeksforGeeks'
print(string.isupper())
Output:
True
False
isnumeric()
Definition and Usage
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
"-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be
numeric, and the - and the . are not.
Syntax
string.isnumeric()
str = "javatpoint12345"
str = "12345"
# Calling function
str2 = str.isnumeric()
str2 = str.isnumeric()
# Displaying result
print(str2)
print(str2)
x = txt.isspace()
print(x)
Output: True
Python String split()
The split() method breaks up a string at the specified
separator and returns a list of strings.
Syntax of String split() text = 'Python is a fun programming language'
The syntax of split() is:
# split the text from space
str.split(separator, maxsplit) print(text.split(' '))
split() Parameters
The split() method takes a maximum of 2 parameters:
word = 'CatBatSatFatOr'
# Splitting at t
print(word.split('t'))
For example,
name = input("Give me your name: ")
print("Your name is " + name)
Example 1 of Integer Python User Input Example 2 of Integer Python User Input
a = int(input()) a = input('Please Enter the first number = ')
b = int(input()) b = input('Enter the second number = ')
s=a+b c = int(a) + int(b)
print(s) print("Summation of a + b = %s + %s = %s" % ( a, b, c ))
Output Output:
Syntax :
input().split(separator, maxsplit)
Example
a, b = input("Enter two of your lucky number: ").split()
print("First lucky number is: ", a)
print("Second lucky number is: ", b)
Output
Enter two of your lucky number: 7,9
First lucky number is: 7
Second lucky number is: 9
input ()
You can take multiple inputs in one single line by using the raw_input function several times as
shown below.
Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
Example:
Output:
num_int = 123 Data type of num_int: <class 'int'>
num_str = "456" Data type of num_str before Type Casting: <class 'str'>
print("Data type of num_int:",type(num_int)) Data type of num_str after Type Casting: <class 'int'>
print("Data type of num_str before Type Sum of num_int and num_str: 579
Casting:",type(num_str)) Data type of the sum: <class 'int'>
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
Python if Statement Syntax Python if...else Statement
if test expression: Syntax of if...else
statement(s) if test expression:
Body of if
else:
Body of else
Example:
num = 3
Example:
if num > 0:
num = 3
print(num, "is a positive number.")
if num >= 0:
print("This is always printed.")
print("Positive or Zero")
num = -1
else:
if num > 0:
print("Negative number")
print(num, "is a positive number.")
print("This is also always printed.")
Output:
3 is a positive number Output:
This is always printed Positive or Zero
This is also always printed.
Python if...elif...else Statement
num = 3.4
Syntax of if...elif...else
# Try these two variations as well:
if test expression:
# num = 0
Body of if
# num = -4.5
elif test expression:
Body of elif
if num > 0:
else:
print("Positive number")
Body of else
elif num == 0:
print("Zero")
else:
print("Negative number")
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block
of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block.
if True: and
print('Hello')
a=5 if True: print('Hello'); a = 5
Syntax
range(start, stop, step)
Example
Create a sequence of numbers from 3 to 5, and
print each item in the sequence:
x = range(3, 6) Example
for n in x: Create a sequence of numbers from 3 to 19, but
print(n) increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for
loop exhausts.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output:
0
1
5
No items left.
Python break and continue
a="pineapple"
for val in a:
if val == "i":
continue
print(val)
print("The end")
What is a function in Python?
In Python, a function is a group of related statements that performs a specific task.
Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is given below.
Syntax:
def my_function(parameters):
function_block
return expression
1
2
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
List
Python List
• A list in Python is used to store the sequence of various types
of data.
• Python lists are mutable type its mean we can modify its
element after it created.
# list of integers
my_list = [1, 2, 3]
# empty list
my_list = []
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Access List Elements
There are various ways in which we can access the elements of a list.
List Index
• We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list
having 5 elements will have an index from 0 to 4.
• Trying to access indexes other than these will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result in TypeError.
my_list = ['p', 'r', 'o', 'b', 'e']
# third item p
print(my_list[2]) # o o
e
# fifth item a
print(my_list[4]) # e 5
Traceback (most recent call last):
# Nested List File "<string>", line 21, in <module>
n_list = ["Happy", [2, 0, 1, 5]] TypeError: list indices must be integers or slices, not float
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
# last item e
print(my_list[-1]) p
my_list = ['p','r','o','g','r','a','m','i','z']
Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example, my_list[2: 5] returns a list with elements at
index 2, 3 and 4, but not 5.
Add/Change List Elements
• Lists are mutable, meaning their elements can be changed unlike string
• Weor can
tuple.
use the assignment operator = to change an item or a
range of items.
print(odd) [1, 4, 6, 8]
[1, 3, 5, 7]
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
print(odd)
1. append()
We can append values to the end of the list. We use the append() method for
this. You can use this to append single values to the list – value, list, tuple.
nums=[1,2,3]
nums.append(4)
nums.append([5,6])
nums.append((7,8))
print (nums)
Output:
[1, 2, 3, 4, [5, 6], (7, 8)]
2. insert()
You can insert values in a list with the insert() method. Here, you specify a
value to insert at a specific position.
nums=[1,2,3]
nums.insert(2,4)
print (nums)
Output:
[1, 2, 4, 3]
3. extend()
extend() can add multiple items to a list.
Learn by example:
nums=[1,2,3]
nums.extend([[4,5,6],(7,8),9])
Print(nums)
Output:
[1, 2, 3, [4, 5, 6], (7, 8), 9]
Deleting Elements in Python Lists
Lists have methods for deleting elements. They are remove() and pop() and are
slightly different from each other.
odd.remove(1)
print(odd)
Output:
[9,4,8,1]
Looping on Lists in Python
Since lists are collections of elements, we can use them in for-loops. You can do
this if you want to do something for every value in a list.
Code:
for num in [1,2,3,4,5,6]: nums=[10,45,89,4]
print(num) for index in range(len(nums)):
print(nums[index])
Output:
1 Output: Nums[0]
2 [10,45,89,4] Nums[1]
3 Nums[2]
4 Nums[3]
5
6
Methods Descriptions
odd=[10,50]
[[10,50],[10,50]
print( [odd] * 2)