SlideShare a Scribd company logo
Introduction to Python
Introduction to Python
Basics of Python programming, Python interpreter - interactive and script mode, the
structure of a program, indentation, identifiers, keywords, constants, variables, types of
operators, precedence of operators, data types, mutable and immutable data types,
statements, expressions, evaluation and comments, input and output statements, data type
conversion, debugging.
Control Statements: if-else, for loop
Lists: list operations - creating, initializing, traversing and manipulating lists, list methods
and built-in functions.
Dictionary: concept of key-value pair, creating, initializing, traversing, updating and
deleting elements, dictionary methods and built-in functions.
3
Tokens: Smallest unit in Python 1
Keywords of Python 2
Identifiers
Identifiers are names used to identify a variable, function, or other
entities in a program. The rules for naming an identifier in Python
are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore
(_)sign. This may be followed by any combination of characters a–z, A–Z, 0–9 or
underscore (_).
• An identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word.
• It cannot contain special symbols like !, @, #, $, %, etc.
3
For example, to find the average of marks obtained by a student in three
subjects, we can choose the identifiers as marks1, marks2, marks3 and avg
rather than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3
Similarly, to calculate the area of a rectangle, we can use identifier names,
such as area, length, breadth instead of single alphabets as identifiers for
clarity and more readability.
area = length * breadth
Identifiers
Identifiers should have a informative name.
4
Variables
A variable is an identifier whose value can change. Variable in Python refers
to an object — an item or element that is stored in the memory.
Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’),
numeric (e.g., 345) or any combination of alphanumeric characters (CD67).
In Python we can use an assignment statement to create new variables and
assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
5
Comments
Comments are used to explain the programming code. Python ignores
comments, and so will not execute code.
Single line comment
# This is the single line comment in Python
Inline comment
print(“Hello World”) # This prints on the screen
Multiple lines comment:
Comments spanning multiple lines have “ “ “ or ‘ ‘ ‘ on either side.
This is the same as a multiline string, but they can be used as comments.
“ “ “
This type of comment spans multiple lines.
These are mostly used for documentation
“ “ “
6
Everything as an object
Python treats every value or data item whether numeric, string, or other type as an object in
the sense that it can be assigned to some variable or can be passed to a function as an
argument.
Every object in Python is assigned a unique identity (ID) which remains the same for the
lifetime of that object.
This ID is the to the memory address of the object. The function id() returns the identity of
an object.
>>> num1 = 20
>>> id(num1)
1433920576 #identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 #identity of num2 and num1are same as both refers to object 20
7
Data Type: It identifies the type of data values a variable can
hold and the operations that can be performed on that data.
8
Number: Number data type stores numerical values only. It is
further classified into three different types.
Type/class Description Examples
int Integer numbers -12, -3, 0, 125, 2
bool Boolean
It is the subtype of integer. True
value is non-zero.
False is value zero.
True, False
float Real of floating point numbers -2.04, 4.0, 14.23
complex Complex numbers 3+4j, 2-2j
9
Number data type and built in function type()
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool’>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(type(float2))
<class 'float'>
>>> var2 = -3+7.2j
>>> print(type(var2))
<class 'complex'>
10
Sequence: A Python sequence is an ordered collection of items,
where each item is indexed by an integer. Examples are string, list
and tuple.
Strings is a group of characters. These characters may be alphabets,
digits or special characters including spaces. String values are enclosed
either in single quotation marks (for example ‘Hello’) or in double
quotation marks (for example “Hello”). The quotes are not a part of the
string, they are used to mark the beginning and end of the string for the
interpreter. For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string
contains a numeric value. For example str2 is a numeric string.
String
11
S = “Hello World”
H e l l o W o r l d
S[0] S[1] S[2] S[3] S[4] S[5] S[6] S[7] S[8] S[9] S[10]
S = “Hello World”
H e l l o W o r l d
S[-11] S[-10] S[-9] S[-8] S[-7] S[-6] S[-5] S[-4] S[-3] S[-2] S[-1]
12
List
 List is a sequence of items
separated by commas and the
items are enclosed in square
brackets [ ].
 List is Mutable.
#To create a list
>>> list1 = [5, 3.4, "New Delhi",
"20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
Tuple
 Tuple is a sequence of items
separated by commas and items are
enclosed in parenthesis ( ).
 Tuple is Immutable. Once created, it
cannot be changed.
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
13
S = [5, 3.4, "New Delhi", "20C", 45] or S = (5, 3.4, "New Delhi", "20C", 45)
1
5 3.4 “New Delhi” “20C” 45
S[0] S[1] S[2] S[3] S[4]
S = [5, 3.4, "New Delhi", "20C", 45] or S = (5, 3.4, "New Delhi", "20C", 45)
5 3.4 “New Delhi” “20C” 45
S[-5] S[-4] S[-3] S[-2] S[-1]
14
Mapping: Mapping is an unordered data type in Python. Currently,
there is only one standard mapping data type in Python called dictionary.
 Dictionary in Python holds data items in key-value pairs, separated
by colon(:) and enclosed in curly brackets { }.
 Dictionaries permit faster access to data.
 The key : value pairs of a dictionary can be accessed using the key.
 The keys can be immutable data type.
>>> dict1 = {'Fruit':'Apple’, 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold’, 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
15
Mutable and Immutable Data Type
Variables whose values can
be changed after they are
created and assigned are
called mutable.
Examples are List, Dictionary
Data Type
Mutable Immutable
Variables whose values cannot be changed
after they are created and assigned are called
immutable.
When an attempt is made to update the value
of an immutable variable, the old variable is
destroyed and a new variable is created by
the same name in memory.
Examples are Integers, Float, Boolean, Complex,
Strings, Tuples, Sets
16
Operators
Operators
Arithmetic Relational Assignment Logical Identity Membership
+
-
*
/
//
**
%
<
>
<=
>=
==
!=
=
+=
-=
*=
/=
//=
**=
%=
and
or
not
is
is not
in
not in
17
Arithmetic Operators: Let A = 24, B = 5, str = “Hello”
Operator Examples
+ (Addition,
Concatenation)
print(A + B) # 29
print(str + “World”) # HelloWorld
- (Subtraction) print(A - B) # 19
* (Multiplication) print(A * B) # 120
print(str * 2) # HelloHello
/ (Division) print(A / B) # 4.8
// (Floor Division) print(A // B) # 4
** (Exponent) print(A ** B) # 7962624
% (Modulus) print(A % B) # 4
18
Arithmetic Operators: Let A = 24.8 B = 5, str = “Hello”
Operator Examples
+ (Addition) print(A + B) # 29.8
- (Subtraction) print(A - B) # 19.8
* (Multiplication) print(A * B) # 124.0
/ (Division) print(A / B) # 4.96
// (Floor Division) print(A // B) # 4.0
** (Exponent) print(A ** B) # 9381200.19968
% (Modulus) print(A % B) # 4.8
19
Arithmetic Operators Precedence
Order Operator Description
1 ** The exponent operation is performed first.
2 *, /, %, // These operators have equal priority. Solve the
expression from left to right, whichever
appears first will be solved first.
3 +, - These operators have equal priority. Solve the
expression from left to right, whichever
appears first will be solved first.
20
Arithmetic Operators Precedence Example
X = 2, Y = 3 and Z = 5
21
Relational Operators: Let A = 10, B = 5, C = 10, s1 = “Hello”, s2 = “Good”
Operator Examples
== (Equals to) print(A == B) # False
print(s1 == s2) # False
!= (Not equal to) print(A != B) # True
print(s1 != s2) # True
> (Greater than) print(A > B) # True
print(s1 > s2) # True
< (Less than) print(A < B) # False
print(s1 < s2) # False
<= (Less than or equal to) print(A <= C) # True
print(s1 <= s2) # False
>= (Greater than or equal to) print(A >= C) #True
print(s1 >= s2) # True
22
Logical Operators: and, or, not
num1 = 10, num2 = -20, num3 = 0
Operator Examples
and : if both the operands are
True, it is True otherwise False
>>> True and True
True
>>> num1 and num2
True
>>> True and False
False
>>> num1 and num3
False
>>> False and False
False
or : If any of the operands is
True, it is True otherwise False
>>> True or True
True
>>> True or False
True
>>> num1 or num3
True
>>> False or False
False
not: It is used to reverse the
logical status of the operand.
>>> num1 = 10 >>> not (num1)
False
23
Assignment Operators
Operator Examples
= A = 5; B = A
print(B) # 5
A = B = C = 0 # A, B and C equals 0
A, B = 10, 8 # A = 10, B = 8
A, B, C = 5, 3, 2 # A = 5, B = 3, C = 2
+=, -=, %=, /=, //=, **=,
*=
A = 5; A += 2 # A = A + 2 output 7
A = 5; A - = 2 # A = A – 2 output 3
A = 5; A *= 2 # A = A * 2 output 10
A = 5; A / = 2 # A = A / 2 output 2.5
A = 5; A **= 2 # A = A ** 2 output 25
A = 5; A // = 2 # A = A // 2 output 2
A = 5; A % = 2 # A = A % 2 output 1
24
Identity Operators
Operator Examples
is
Evaluates True if the variables on either
side of the operator point towards the same
memory location, otherwise False otherwise.
>>>num1 = 10
>>> type(num1) is int
True
>>> num2 = num1
>>> id(num1)
1433920576
>>> id(num2)
1433920576
>>> num1 is num2
True
is not
Evaluates to True if the variables on
either side of the operator point to different memory
address, otherwise False
>>> num1 = 10
>>> num2 = 20
>>> num1 is not num2
True
25
Membership Operators
Operator Examples
in
Returns True if the variable/value
is found in the specified
sequence, otherwise False.
>>> a = [1,2,3]
>>> 2 in a
True
>>> '1' in a
False
not in
Returns True if the variable/value
is not found in the specified
sequence, otherwise False.
>>> a = [1,2,3]
>>> 10 not in a
True
>>> 1 not in a
False
26
Expression
An expression is defined as a combination of constants, variables, and
operators. An expression always evaluates to a value. A value or a
standalone variable is also considered as an expression but a standalone
operator is not an expression. Some examples of valid expressions are
given below.
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"
27
Precedence of operators
Order of
precedence
Operators Description
1 ** Exponent
2 +, - unary plus and minus
3 *, /, %, // multiply, divide, modulo, floor
division
4 +, - addition and subtraction
5 <, >, <=, >= relational operator
6 ==, != equality operators
7 =, %=, /=, //=, -=, +=, *=, **= assignment operators
8 is, is not identity operators
9 in, not in membership operators
10 not, and ,or logical operators
28
Input statement
The input() function for taking the user input. It prompts the user to
enter data. It accepts the input as string.
The syntax for input() is:
A = input ([Prompt])
Prompt is the string which you would like to display on the screen
prior to take the input, and it is optional.
The user enters the data and press the Enter key. It then assigns it to
the variable on left-hand side of the assignment operator (=).
29
Input statement Example
>>> fname = input("Enter your first
name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<class 'str'>
The variable fname will get the string
‘Arnab’, entered by the user. Similarly,
the variable age will get the string ‘19’.
>>> age = int( input("Enter your
age:"))
Enter your age: 19
>>> type(age)
<class 'int’>
We can typecast or change the
datatype of the string data accepted
from user to an appropriate numeric
value.
float() change the data type to float.
eval() change the data type to int or
float depending on the input.
30
Print statement
The print() function to output data on the screen. It evaluates the expression
before displaying it on the screen.
The print() outputs a complete line and then moves to the next line
for subsequent output. The syntax for print() is:
print(value [, ..., sep = ' ', end = 'n'])
sep: The optional parameter sep is a separator between the output values.
We can use a character, integer or a string as a separator. The default
separator is space.
end: This is also optional and it allows us to specify any string to be
appended after the last value. The default is a new line.
31
Print statement 32
Print statement
print("Hello") #Hello
print(10*2.5) #25.0
print("I" + "love" + "my" + "country") #Ilovemycountry
print("I'm", 16, "years old") #I'm 16 years old
The third print function use + (plus) between two strings to concatenate them.
does not add any space between the two strings.
The fourth print function use comma to display output. It inserts a space
between two strings in a print statement.
33
Data type
conversion
Explicit Implicit
Data type conversion done
by the programmer.
Data type conversion done
by the python interpreter.
34
Explicit conversion
The general form of an explicit data type conversion is:
new_data_type(expression)
int(x) Converts x to an integer
float(x) Converts x to a float
str(x) Converts x to a string
chr(x) Converts x to a character
unichr(x) Converts x to a Unicode character
ord(x) Converts x to ascii value
eval(x) Converts x to given data type
35
Implicit Conversion
#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2
print(sum1)
print(type(sum1))
Output:
30.0
<class 'float’>
In the above example, an integer value stored in variable num1 is added to a float value
stored in variable num2, and the result was automatically converted to a float value stored in
variable sum1 without explicitly telling the interpreter.
36
L-value and R-value
A left value or L-value is an object identifier on the left side of the assignment
statement.
A right value or R-value is any object identifier / expression / value that results
in a value that appear on the right side of the assignment.
Examples
A = 5
B = 10
C = A*5 + B+ 2
print(C)
B = A
A = B + 5
10 = A # Wrong
B * 10 = A # Wrong
37
L-value and R-value
A = 5
B = 10
C = A*5 + B+ 2
print(C)
A, B = 5, 10
C = A*5 + B+ 2
print(C)
A = 5 ; B = 10
C = A*5 + B+ 2
print(C)
Wrong statements
A, B, C = 10
A, B = 1, 2, 3
A, B, C = “XY”
A,B,C = “XYZW”
A = 1, 2, 3
print(A)
A = B = C = 10
print(A)
A, B, C = “XYZ”
print(A, B, C)
38
Assignment in Python
39
/, //, % operators
The / operator always gives the answer in decimal.
The // operator gives the floor value of the division always less than
the result.
The % operator gives the remainder.
40
/, //, % operators
The % operator gives the remainder.
output = dividend – (divisor * dividend // divisor)
-10 – (3 * (-4)) = -10 – (-12) = -10 + 12 = 2
-34 – (4 * (-9)) = -34 – (-36) = 2
21%2 = 1
32 – (-6 * (-6)) = 32 – 36 = -4
41
Control
Structures
Conditional
if
Loop
for while
42
if statement
if
statement
if if…else if…elif…else
43
Relational Operator
A relational operator forms a condition and it results in
either true or false.
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
44
Logical Operator
A logical operator is a combination of more than one
relational expression and it results in either true or false.
Operator Meaning
and It is true, if all the relational expressions
are true. Otherwise it is false.
or It is true, if any one of the relational
expression is true. Otherwise it is false.
not It is true, if relational expression is false.
It is false, if relational expression is true.
45
if Statement
if expression:
statement1
statement2
statementN
 If the expression evaluates to true, it executes
Statement1, Statement2 and then
StatementN.
 If the expression evaluates to false, it executes
StatementN.
When you press the enter after colon : sign, the cursor
in the next line is indented by four space. You can
change the indentation spaces. This actually starts a
block. All the statements to be executed when the
condition is true should start from the same
indentation i.e. after four spaces.
46
if Statement Code 1
47
Write a Python script to display the absolute value of a
given number. Code 2
48
if…else statement
if expression:
statement1
statement2
else:
statement3
statement4
statementN
 If the condition evaluates to true, it executes statement1,
statement2 and then statementN.
 If the condition evaluates to false, it executes statement3,
statement4 and then statementN.
49
if…else Example
Enter your age 13
You cannot apply for scholarship
Thank You
Code 3
50
Write a Python script to find whether the given number is an even
or odd number
Code 4
51
Write a Python script to find whether the given year is a leap year
or not.
Code 5
52
if...elif…else Statement
if expression1:
statement(s) 40
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
statementN
 It keeps on executing expression1, expression2,….so on.
 If any of the expression evaluates to true, it executes the
corresponding Statement Block and get out of the if statement.
 If none of the expression evaluates to true, it executes Statement after
else and get out of the if statement.
53
if...elif…else Statement
Code 6
54
Write a Python script to enter total marks in five subjects, each out of 100.
Calculate percentage and assign grade according to the following:
Percentage Grade
>= 90 A
>= 80 and < 90 B
>= 70 and < 80 C
>= 60 and < 70 D
<60 E
If percentage >= 90: grade = “A”
elif percentage >= 80: grade = “B”
elif percentage >= 70: grade = “C”
elif percentage >= 60: grade = “D”
elif :grade = “F”
Code 7
55
Write a program to input the month name as 3 chars and display the
number of days in a given month.
Code 8 56
Nesting of if...else Statement
Code 9
57
Loops
Repetition of a statement or set of statements, finite or infinite number of times
is known as loop.
We can use the term terminating loop for the loop, which allow the statement(s)
to execute finite number of times and non-terminating loop, which allows a
statement(s) to execute infinite number of times.
The two types of loops used in Python are:
• for
• while
58
range() function
The range() function has the following format:
range (start, end, increment)
The start, end and increment should be of
type integer.
It produced a sequence of number from start
to end-1 (the end number is not included in
the sequence).
If the third argument (increment) is not
specified, by default it is 1.
range (1, 10, 2)
1, 3, 5, 7, 9
range (1, 5)
1, 2, 3, 4
range(3, 20, 4)
3, 7, 11, 15, 19
59
range() function
Examples Output
for i in range(1, 10):
print(i, end = ‘ ’)
1 2 3 4 5 6 7 8 9
for i in range(1, 10, 2):
print(i, end = ‘ ’)
1 3 5 7 9
for i in range(-20, 5, 7):
print(i, end = ‘ ’)
-20 -13 -6 1
for i in range(11):
print(i, end = ‘ ’)
0 1 2 3 4 5 6 7 8 9 10
for i in range( -10, -15, -3):
print(i, end = ‘ ’)
-10 -13
60
Using list, tuple, dictionary, string
Examples Output
L = [‘amit’, 12, 342]
for i in L:
print(i, end = ‘ ’)
amit 12 342
T = (‘yellow’, ‘orange’, ‘blue’)
for i in T:
print(i, end = ‘ ’)
yellow orange blue
D = {1: ‘John’, 2: ‘Annie’}
for i in D:
print(i, end = ‘ ’)
1 2
for i in ‘Python’:
print(i, end = ‘ ’)
P y t h o n
61
Write a Python script to input lower and higher limit of numbers
and display the numbers in this range.
Code 10
62
Write a Python script to display even/odd numbers in the range 1 to
100.
# even numbers in the range 1 to 100
for i in range(2, 101, 2):
print(i, end = ' ')
# odd numbers in the range 1 to 100
for i in range(1, 100, 2):
print(i, end = ' ')
Code 11
63
Write a Python script to display the table of given number.
# print table of any number
n = int(input("Enter a number whose table you want "))
for i in range(1, 11):
print(n, "x", i, "=", n * i, end = 'n')
Code 12
64
Write a Python script to display the sum of 100 natural number.
# print sum of first 100 natural number
s = 0
for i in range(1, 101):
s = s + i # s += i
print ("The sum of 100 natural numbers is ", s)
Code 12
65
Write a Python script to display the factorial of given number.
# print factorial of any number
n = int(input("Enter a number whose factorial you want "))
s = 1
for i in range(1, n+1):
s = s * i # s *= i
print ("The factorial of a number", n, "is", s)
Code 13
66
Write a Python script to display the first N number of Even
numbers.
# print first N number of Even numbers
n = int(input("Enter a number"))
for I in range (N):
print(2 * (I + 1))
Code 14
67
Write a Python script to display the series 1, 4, 7…. Upto N
numbers.
# print series 1, 4, 7 upto N numbers
n = int(input("Enter a number"))
for I in range (1, N+1, 3):
print(I)
Code 15
68
Write a Python script to display the pattern.
# print pattern1
n = int(input("Enter a number"))
for I in range (n):
print( “*” * (I + 1))
Code 16
69
Write a Python script to display the pattern.
# print pattern1
n = int(input("Enter a number"))
for I in range (n):
print( “*” * (5 - I))
Code 17
70
Write a Python script to find and print all the factors of N.
# To find and print all the factors of N
n = int(input("Enter a number"))
for I in range (1, n+1):
if n%I == 0:
print(I, end = “, “)
Code 18
71
Code 19
Write a Python script to find and print all the factors of N.
# To find and first N terms of Fibonacci series
F, S = 0, 1
N = int(input("Enter a number"))
For I in range (N):
print(F, end = “’”)
F, S = S, F+S
72
Write a program to display the input number is a prime number or not.
Code 20N = int(input(“Enter a number”))
Half = N //2
flag = 0
for I in range(2, Half):
if N % I == 0:
print(“Not prime”)
flag = 1
break
If flag == 0: print(“prime number”)
73
Python

More Related Content

What's hot

Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Syed Zaid Irshad
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Saravanan T.M
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
St. Petersburg College
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
Siddique Ibrahim
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
RaginiJain21
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
AkshayAggarwal79
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
QA TrainingHub
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ayshwarya Baburam
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
Samir Mohanty
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
Python : Data Types
Python : Data TypesPython : Data Types

What's hot (20)

Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python ppt
Python pptPython ppt
Python ppt
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 

Similar to Python

1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx
KUSHSHARMA630049
 
Token and operators
Token and operatorsToken and operators
Token and operators
Samsil Arefin
 
Python PPT2
Python PPT2Python PPT2
Python PPT2
Selvakanmani S
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Chapter-2 is for tokens in C programming
Chapter-2 is for tokens in C programmingChapter-2 is for tokens in C programming
Chapter-2 is for tokens in C programming
z9819898203
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
YashwanthMalviya
 
Python basics
Python basicsPython basics
Python basics
Manisha Gholve
 
Variables & Data Types in R
Variables & Data Types in RVariables & Data Types in R
Variables & Data Types in R
Rsquared Academy
 
IMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptxIMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptx
lemonchoos
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
Jasleen Kaur (Chandigarh University)
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
Koteswari Kasireddy
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
HarishParthasarathy4
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
AnirudhaGaikwad4
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III TermAndrew Raj
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
Raajendra M
 

Similar to Python (20)

1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx1691912901477_Python_Basics and list,tuple,string.pptx
1691912901477_Python_Basics and list,tuple,string.pptx
 
Token and operators
Token and operatorsToken and operators
Token and operators
 
Python PPT2
Python PPT2Python PPT2
Python PPT2
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Chapter-2 is for tokens in C programming
Chapter-2 is for tokens in C programmingChapter-2 is for tokens in C programming
Chapter-2 is for tokens in C programming
 
lecture2.ppt
lecture2.pptlecture2.ppt
lecture2.ppt
 
Python basics
Python basicsPython basics
Python basics
 
Variables & Data Types in R
Variables & Data Types in RVariables & Data Types in R
Variables & Data Types in R
 
IMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptxIMP PPT- Python programming fundamentals.pptx
IMP PPT- Python programming fundamentals.pptx
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
C language
C languageC language
C language
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Pointers
PointersPointers
Pointers
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 

Recently uploaded

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 

Recently uploaded (20)

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 

Python

  • 2. Introduction to Python Basics of Python programming, Python interpreter - interactive and script mode, the structure of a program, indentation, identifiers, keywords, constants, variables, types of operators, precedence of operators, data types, mutable and immutable data types, statements, expressions, evaluation and comments, input and output statements, data type conversion, debugging. Control Statements: if-else, for loop Lists: list operations - creating, initializing, traversing and manipulating lists, list methods and built-in functions. Dictionary: concept of key-value pair, creating, initializing, traversing, updating and deleting elements, dictionary methods and built-in functions. 3
  • 3. Tokens: Smallest unit in Python 1
  • 5. Identifiers Identifiers are names used to identify a variable, function, or other entities in a program. The rules for naming an identifier in Python are as follows: • The name should begin with an uppercase or a lowercase alphabet or an underscore (_)sign. This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_). • An identifier cannot start with a digit. • It can be of any length. (However, it is preferred to keep it short and meaningful). • It should not be a keyword or reserved word. • It cannot contain special symbols like !, @, #, $, %, etc. 3
  • 6. For example, to find the average of marks obtained by a student in three subjects, we can choose the identifiers as marks1, marks2, marks3 and avg rather than a, b, c, or A, B, C. avg = (marks1 + marks2 + marks3)/3 Similarly, to calculate the area of a rectangle, we can use identifier names, such as area, length, breadth instead of single alphabets as identifiers for clarity and more readability. area = length * breadth Identifiers Identifiers should have a informative name. 4
  • 7. Variables A variable is an identifier whose value can change. Variable in Python refers to an object — an item or element that is stored in the memory. Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or any combination of alphanumeric characters (CD67). In Python we can use an assignment statement to create new variables and assign specific values to them. gender = 'M' message = "Keep Smiling" price = 987.9 5
  • 8. Comments Comments are used to explain the programming code. Python ignores comments, and so will not execute code. Single line comment # This is the single line comment in Python Inline comment print(“Hello World”) # This prints on the screen Multiple lines comment: Comments spanning multiple lines have “ “ “ or ‘ ‘ ‘ on either side. This is the same as a multiline string, but they can be used as comments. “ “ “ This type of comment spans multiple lines. These are mostly used for documentation “ “ “ 6
  • 9. Everything as an object Python treats every value or data item whether numeric, string, or other type as an object in the sense that it can be assigned to some variable or can be passed to a function as an argument. Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime of that object. This ID is the to the memory address of the object. The function id() returns the identity of an object. >>> num1 = 20 >>> id(num1) 1433920576 #identity of num1 >>> num2 = 30 - 10 >>> id(num2) 1433920576 #identity of num2 and num1are same as both refers to object 20 7
  • 10. Data Type: It identifies the type of data values a variable can hold and the operations that can be performed on that data. 8
  • 11. Number: Number data type stores numerical values only. It is further classified into three different types. Type/class Description Examples int Integer numbers -12, -3, 0, 125, 2 bool Boolean It is the subtype of integer. True value is non-zero. False is value zero. True, False float Real of floating point numbers -2.04, 4.0, 14.23 complex Complex numbers 3+4j, 2-2j 9
  • 12. Number data type and built in function type() >>> num1 = 10 >>> type(num1) <class 'int'> >>> num2 = -1210 >>> type(num2) <class 'int'> >>> var1 = True >>> type(var1) <class 'bool’> >>> float1 = -1921.9 >>> type(float1) <class 'float'> >>> float2 = -9.8*10**2 >>> print(type(float2)) <class 'float'> >>> var2 = -3+7.2j >>> print(type(var2)) <class 'complex'> 10
  • 13. Sequence: A Python sequence is an ordered collection of items, where each item is indexed by an integer. Examples are string, list and tuple. Strings is a group of characters. These characters may be alphabets, digits or special characters including spaces. String values are enclosed either in single quotation marks (for example ‘Hello’) or in double quotation marks (for example “Hello”). The quotes are not a part of the string, they are used to mark the beginning and end of the string for the interpreter. For example, >>> str1 = 'Hello Friend' >>> str2 = "452" We cannot perform numerical operations on strings, even when the string contains a numeric value. For example str2 is a numeric string. String 11
  • 14. S = “Hello World” H e l l o W o r l d S[0] S[1] S[2] S[3] S[4] S[5] S[6] S[7] S[8] S[9] S[10] S = “Hello World” H e l l o W o r l d S[-11] S[-10] S[-9] S[-8] S[-7] S[-6] S[-5] S[-4] S[-3] S[-2] S[-1] 12
  • 15. List  List is a sequence of items separated by commas and the items are enclosed in square brackets [ ].  List is Mutable. #To create a list >>> list1 = [5, 3.4, "New Delhi", "20C", 45] #print the elements of the list list1 >>> print(list1) [5, 3.4, 'New Delhi', '20C', 45] Tuple  Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).  Tuple is Immutable. Once created, it cannot be changed. #create a tuple tuple1 >>> tuple1 = (10, 20, "Apple", 3.4, 'a') #print the elements of the tuple tuple1 >>> print(tuple1) (10, 20, "Apple", 3.4, 'a') 13
  • 16. S = [5, 3.4, "New Delhi", "20C", 45] or S = (5, 3.4, "New Delhi", "20C", 45) 1 5 3.4 “New Delhi” “20C” 45 S[0] S[1] S[2] S[3] S[4] S = [5, 3.4, "New Delhi", "20C", 45] or S = (5, 3.4, "New Delhi", "20C", 45) 5 3.4 “New Delhi” “20C” 45 S[-5] S[-4] S[-3] S[-2] S[-1] 14
  • 17. Mapping: Mapping is an unordered data type in Python. Currently, there is only one standard mapping data type in Python called dictionary.  Dictionary in Python holds data items in key-value pairs, separated by colon(:) and enclosed in curly brackets { }.  Dictionaries permit faster access to data.  The key : value pairs of a dictionary can be accessed using the key.  The keys can be immutable data type. >>> dict1 = {'Fruit':'Apple’, 'Climate':'Cold', 'Price(kg)':120} >>> print(dict1) {'Fruit': 'Apple', 'Climate': 'Cold’, 'Price(kg)': 120} >>> print(dict1['Price(kg)']) 120 15
  • 18. Mutable and Immutable Data Type Variables whose values can be changed after they are created and assigned are called mutable. Examples are List, Dictionary Data Type Mutable Immutable Variables whose values cannot be changed after they are created and assigned are called immutable. When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable is created by the same name in memory. Examples are Integers, Float, Boolean, Complex, Strings, Tuples, Sets 16
  • 19. Operators Operators Arithmetic Relational Assignment Logical Identity Membership + - * / // ** % < > <= >= == != = += -= *= /= //= **= %= and or not is is not in not in 17
  • 20. Arithmetic Operators: Let A = 24, B = 5, str = “Hello” Operator Examples + (Addition, Concatenation) print(A + B) # 29 print(str + “World”) # HelloWorld - (Subtraction) print(A - B) # 19 * (Multiplication) print(A * B) # 120 print(str * 2) # HelloHello / (Division) print(A / B) # 4.8 // (Floor Division) print(A // B) # 4 ** (Exponent) print(A ** B) # 7962624 % (Modulus) print(A % B) # 4 18
  • 21. Arithmetic Operators: Let A = 24.8 B = 5, str = “Hello” Operator Examples + (Addition) print(A + B) # 29.8 - (Subtraction) print(A - B) # 19.8 * (Multiplication) print(A * B) # 124.0 / (Division) print(A / B) # 4.96 // (Floor Division) print(A // B) # 4.0 ** (Exponent) print(A ** B) # 9381200.19968 % (Modulus) print(A % B) # 4.8 19
  • 22. Arithmetic Operators Precedence Order Operator Description 1 ** The exponent operation is performed first. 2 *, /, %, // These operators have equal priority. Solve the expression from left to right, whichever appears first will be solved first. 3 +, - These operators have equal priority. Solve the expression from left to right, whichever appears first will be solved first. 20
  • 23. Arithmetic Operators Precedence Example X = 2, Y = 3 and Z = 5 21
  • 24. Relational Operators: Let A = 10, B = 5, C = 10, s1 = “Hello”, s2 = “Good” Operator Examples == (Equals to) print(A == B) # False print(s1 == s2) # False != (Not equal to) print(A != B) # True print(s1 != s2) # True > (Greater than) print(A > B) # True print(s1 > s2) # True < (Less than) print(A < B) # False print(s1 < s2) # False <= (Less than or equal to) print(A <= C) # True print(s1 <= s2) # False >= (Greater than or equal to) print(A >= C) #True print(s1 >= s2) # True 22
  • 25. Logical Operators: and, or, not num1 = 10, num2 = -20, num3 = 0 Operator Examples and : if both the operands are True, it is True otherwise False >>> True and True True >>> num1 and num2 True >>> True and False False >>> num1 and num3 False >>> False and False False or : If any of the operands is True, it is True otherwise False >>> True or True True >>> True or False True >>> num1 or num3 True >>> False or False False not: It is used to reverse the logical status of the operand. >>> num1 = 10 >>> not (num1) False 23
  • 26. Assignment Operators Operator Examples = A = 5; B = A print(B) # 5 A = B = C = 0 # A, B and C equals 0 A, B = 10, 8 # A = 10, B = 8 A, B, C = 5, 3, 2 # A = 5, B = 3, C = 2 +=, -=, %=, /=, //=, **=, *= A = 5; A += 2 # A = A + 2 output 7 A = 5; A - = 2 # A = A – 2 output 3 A = 5; A *= 2 # A = A * 2 output 10 A = 5; A / = 2 # A = A / 2 output 2.5 A = 5; A **= 2 # A = A ** 2 output 25 A = 5; A // = 2 # A = A // 2 output 2 A = 5; A % = 2 # A = A % 2 output 1 24
  • 27. Identity Operators Operator Examples is Evaluates True if the variables on either side of the operator point towards the same memory location, otherwise False otherwise. >>>num1 = 10 >>> type(num1) is int True >>> num2 = num1 >>> id(num1) 1433920576 >>> id(num2) 1433920576 >>> num1 is num2 True is not Evaluates to True if the variables on either side of the operator point to different memory address, otherwise False >>> num1 = 10 >>> num2 = 20 >>> num1 is not num2 True 25
  • 28. Membership Operators Operator Examples in Returns True if the variable/value is found in the specified sequence, otherwise False. >>> a = [1,2,3] >>> 2 in a True >>> '1' in a False not in Returns True if the variable/value is not found in the specified sequence, otherwise False. >>> a = [1,2,3] >>> 10 not in a True >>> 1 not in a False 26
  • 29. Expression An expression is defined as a combination of constants, variables, and operators. An expression always evaluates to a value. A value or a standalone variable is also considered as an expression but a standalone operator is not an expression. Some examples of valid expressions are given below. (i) 100 (iv) 3.0 + 3.14 (ii) num (v) 23/3 -5 * 7(14 -2) (iii) num – 20.4 (vi) "Global" + "Citizen" 27
  • 30. Precedence of operators Order of precedence Operators Description 1 ** Exponent 2 +, - unary plus and minus 3 *, /, %, // multiply, divide, modulo, floor division 4 +, - addition and subtraction 5 <, >, <=, >= relational operator 6 ==, != equality operators 7 =, %=, /=, //=, -=, +=, *=, **= assignment operators 8 is, is not identity operators 9 in, not in membership operators 10 not, and ,or logical operators 28
  • 31. Input statement The input() function for taking the user input. It prompts the user to enter data. It accepts the input as string. The syntax for input() is: A = input ([Prompt]) Prompt is the string which you would like to display on the screen prior to take the input, and it is optional. The user enters the data and press the Enter key. It then assigns it to the variable on left-hand side of the assignment operator (=). 29
  • 32. Input statement Example >>> fname = input("Enter your first name: ") Enter your first name: Arnab >>> age = input("Enter your age: ") Enter your age: 19 >>> type(age) <class 'str'> The variable fname will get the string ‘Arnab’, entered by the user. Similarly, the variable age will get the string ‘19’. >>> age = int( input("Enter your age:")) Enter your age: 19 >>> type(age) <class 'int’> We can typecast or change the datatype of the string data accepted from user to an appropriate numeric value. float() change the data type to float. eval() change the data type to int or float depending on the input. 30
  • 33. Print statement The print() function to output data on the screen. It evaluates the expression before displaying it on the screen. The print() outputs a complete line and then moves to the next line for subsequent output. The syntax for print() is: print(value [, ..., sep = ' ', end = 'n']) sep: The optional parameter sep is a separator between the output values. We can use a character, integer or a string as a separator. The default separator is space. end: This is also optional and it allows us to specify any string to be appended after the last value. The default is a new line. 31
  • 35. Print statement print("Hello") #Hello print(10*2.5) #25.0 print("I" + "love" + "my" + "country") #Ilovemycountry print("I'm", 16, "years old") #I'm 16 years old The third print function use + (plus) between two strings to concatenate them. does not add any space between the two strings. The fourth print function use comma to display output. It inserts a space between two strings in a print statement. 33
  • 36. Data type conversion Explicit Implicit Data type conversion done by the programmer. Data type conversion done by the python interpreter. 34
  • 37. Explicit conversion The general form of an explicit data type conversion is: new_data_type(expression) int(x) Converts x to an integer float(x) Converts x to a float str(x) Converts x to a string chr(x) Converts x to a character unichr(x) Converts x to a Unicode character ord(x) Converts x to ascii value eval(x) Converts x to given data type 35
  • 38. Implicit Conversion #Implicit type conversion from int to float num1 = 10 #num1 is an integer num2 = 20.0 #num2 is a float sum1 = num1 + num2 print(sum1) print(type(sum1)) Output: 30.0 <class 'float’> In the above example, an integer value stored in variable num1 is added to a float value stored in variable num2, and the result was automatically converted to a float value stored in variable sum1 without explicitly telling the interpreter. 36
  • 39. L-value and R-value A left value or L-value is an object identifier on the left side of the assignment statement. A right value or R-value is any object identifier / expression / value that results in a value that appear on the right side of the assignment. Examples A = 5 B = 10 C = A*5 + B+ 2 print(C) B = A A = B + 5 10 = A # Wrong B * 10 = A # Wrong 37
  • 40. L-value and R-value A = 5 B = 10 C = A*5 + B+ 2 print(C) A, B = 5, 10 C = A*5 + B+ 2 print(C) A = 5 ; B = 10 C = A*5 + B+ 2 print(C) Wrong statements A, B, C = 10 A, B = 1, 2, 3 A, B, C = “XY” A,B,C = “XYZW” A = 1, 2, 3 print(A) A = B = C = 10 print(A) A, B, C = “XYZ” print(A, B, C) 38
  • 42. /, //, % operators The / operator always gives the answer in decimal. The // operator gives the floor value of the division always less than the result. The % operator gives the remainder. 40
  • 43. /, //, % operators The % operator gives the remainder. output = dividend – (divisor * dividend // divisor) -10 – (3 * (-4)) = -10 – (-12) = -10 + 12 = 2 -34 – (4 * (-9)) = -34 – (-36) = 2 21%2 = 1 32 – (-6 * (-6)) = 32 – 36 = -4 41
  • 46. Relational Operator A relational operator forms a condition and it results in either true or false. Operator Meaning == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to 44
  • 47. Logical Operator A logical operator is a combination of more than one relational expression and it results in either true or false. Operator Meaning and It is true, if all the relational expressions are true. Otherwise it is false. or It is true, if any one of the relational expression is true. Otherwise it is false. not It is true, if relational expression is false. It is false, if relational expression is true. 45
  • 48. if Statement if expression: statement1 statement2 statementN  If the expression evaluates to true, it executes Statement1, Statement2 and then StatementN.  If the expression evaluates to false, it executes StatementN. When you press the enter after colon : sign, the cursor in the next line is indented by four space. You can change the indentation spaces. This actually starts a block. All the statements to be executed when the condition is true should start from the same indentation i.e. after four spaces. 46
  • 50. Write a Python script to display the absolute value of a given number. Code 2 48
  • 51. if…else statement if expression: statement1 statement2 else: statement3 statement4 statementN  If the condition evaluates to true, it executes statement1, statement2 and then statementN.  If the condition evaluates to false, it executes statement3, statement4 and then statementN. 49
  • 52. if…else Example Enter your age 13 You cannot apply for scholarship Thank You Code 3 50
  • 53. Write a Python script to find whether the given number is an even or odd number Code 4 51
  • 54. Write a Python script to find whether the given year is a leap year or not. Code 5 52
  • 55. if...elif…else Statement if expression1: statement(s) 40 elif expression2: statement(s) elif expression3: statement(s) else: statement(s) statementN  It keeps on executing expression1, expression2,….so on.  If any of the expression evaluates to true, it executes the corresponding Statement Block and get out of the if statement.  If none of the expression evaluates to true, it executes Statement after else and get out of the if statement. 53
  • 57. Write a Python script to enter total marks in five subjects, each out of 100. Calculate percentage and assign grade according to the following: Percentage Grade >= 90 A >= 80 and < 90 B >= 70 and < 80 C >= 60 and < 70 D <60 E If percentage >= 90: grade = “A” elif percentage >= 80: grade = “B” elif percentage >= 70: grade = “C” elif percentage >= 60: grade = “D” elif :grade = “F” Code 7 55
  • 58. Write a program to input the month name as 3 chars and display the number of days in a given month. Code 8 56
  • 59. Nesting of if...else Statement Code 9 57
  • 60. Loops Repetition of a statement or set of statements, finite or infinite number of times is known as loop. We can use the term terminating loop for the loop, which allow the statement(s) to execute finite number of times and non-terminating loop, which allows a statement(s) to execute infinite number of times. The two types of loops used in Python are: • for • while 58
  • 61. range() function The range() function has the following format: range (start, end, increment) The start, end and increment should be of type integer. It produced a sequence of number from start to end-1 (the end number is not included in the sequence). If the third argument (increment) is not specified, by default it is 1. range (1, 10, 2) 1, 3, 5, 7, 9 range (1, 5) 1, 2, 3, 4 range(3, 20, 4) 3, 7, 11, 15, 19 59
  • 62. range() function Examples Output for i in range(1, 10): print(i, end = ‘ ’) 1 2 3 4 5 6 7 8 9 for i in range(1, 10, 2): print(i, end = ‘ ’) 1 3 5 7 9 for i in range(-20, 5, 7): print(i, end = ‘ ’) -20 -13 -6 1 for i in range(11): print(i, end = ‘ ’) 0 1 2 3 4 5 6 7 8 9 10 for i in range( -10, -15, -3): print(i, end = ‘ ’) -10 -13 60
  • 63. Using list, tuple, dictionary, string Examples Output L = [‘amit’, 12, 342] for i in L: print(i, end = ‘ ’) amit 12 342 T = (‘yellow’, ‘orange’, ‘blue’) for i in T: print(i, end = ‘ ’) yellow orange blue D = {1: ‘John’, 2: ‘Annie’} for i in D: print(i, end = ‘ ’) 1 2 for i in ‘Python’: print(i, end = ‘ ’) P y t h o n 61
  • 64. Write a Python script to input lower and higher limit of numbers and display the numbers in this range. Code 10 62
  • 65. Write a Python script to display even/odd numbers in the range 1 to 100. # even numbers in the range 1 to 100 for i in range(2, 101, 2): print(i, end = ' ') # odd numbers in the range 1 to 100 for i in range(1, 100, 2): print(i, end = ' ') Code 11 63
  • 66. Write a Python script to display the table of given number. # print table of any number n = int(input("Enter a number whose table you want ")) for i in range(1, 11): print(n, "x", i, "=", n * i, end = 'n') Code 12 64
  • 67. Write a Python script to display the sum of 100 natural number. # print sum of first 100 natural number s = 0 for i in range(1, 101): s = s + i # s += i print ("The sum of 100 natural numbers is ", s) Code 12 65
  • 68. Write a Python script to display the factorial of given number. # print factorial of any number n = int(input("Enter a number whose factorial you want ")) s = 1 for i in range(1, n+1): s = s * i # s *= i print ("The factorial of a number", n, "is", s) Code 13 66
  • 69. Write a Python script to display the first N number of Even numbers. # print first N number of Even numbers n = int(input("Enter a number")) for I in range (N): print(2 * (I + 1)) Code 14 67
  • 70. Write a Python script to display the series 1, 4, 7…. Upto N numbers. # print series 1, 4, 7 upto N numbers n = int(input("Enter a number")) for I in range (1, N+1, 3): print(I) Code 15 68
  • 71. Write a Python script to display the pattern. # print pattern1 n = int(input("Enter a number")) for I in range (n): print( “*” * (I + 1)) Code 16 69
  • 72. Write a Python script to display the pattern. # print pattern1 n = int(input("Enter a number")) for I in range (n): print( “*” * (5 - I)) Code 17 70
  • 73. Write a Python script to find and print all the factors of N. # To find and print all the factors of N n = int(input("Enter a number")) for I in range (1, n+1): if n%I == 0: print(I, end = “, “) Code 18 71
  • 74. Code 19 Write a Python script to find and print all the factors of N. # To find and first N terms of Fibonacci series F, S = 0, 1 N = int(input("Enter a number")) For I in range (N): print(F, end = “’”) F, S = S, F+S 72
  • 75. Write a program to display the input number is a prime number or not. Code 20N = int(input(“Enter a number”)) Half = N //2 flag = 0 for I in range(2, Half): if N % I == 0: print(“Not prime”) flag = 1 break If flag == 0: print(“prime number”) 73