Introduction
• Python is a general purpose high level programming language.
• Python was developed by Guido Van Rossam in 1989 while working
at National Research Institute at Netherlands.
• But officially Python was made available to public in 1991. The official
Date of Birth for Python is : Feb 20th 1991.
• Guido developed Python language by taking almost all programming
features from different languages
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script.
4. Modular Programming Features from Modula-3.
Features
1. Easy to use – Due to simple syntax rule
2. Interpreted language – Code execution & interpretation line by line
3. Cross-platform language – It can run on windows,linux,macinetosh
etc. equally
4. Expressive language – Less code to be written as it itself express the
purpose of the code.
5. Completeness – Support wide range of library
6. Free & Open Source – Can be downloaded freely and source code
can be modify for improvement
IDLE
• IDLE (Integrated Development and Learning
Environment) is an integrated development environment
(IDE) for Python. The Python installer for Windows
contains the IDLE module by default.
• IDLE can be used to execute a single statement just like
Python Shell and also to create, modify, and execute
Python scripts. IDLE provides a fully-featured text editor
to create Python script that includes features like syntax
highlighting, autocompletion, and smart indent. It also
has a debugger with stepping and breakpoints features.
To start an IDLE interactive shell, search for the IDLE
icon in the start menu and double click on it.
To execute a Python script, create a new file
by selecting File -> New File from the menu.
Enter multiple statements and save the file with extension .py
using File -> Save. For example, save the following code as
[Link].
Now, press F5 to run the script in the editor
window. The IDLE shell will show the output.
Where we can use Phython
We can use everywhere. The most common important application
areas are
1. For developing Desktop Applications
2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT
...
Internally Google and Youtube use Python coding
NASA and Nework Stock Exchange Applications developed by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo using Python.
Eg1: To print Helloworld:
Java:
1) public class HelloWorld
2) {
3) p s v main(String[] args)
4) {
5) SOP("Hello world");
6) }
7) }
C:
1) #include<stdio.h>
2) void main()
3) {
4) print("Hello world");
5) }
Python:
print("Hello World“)
Eg2: To print the sum of 2 numbers
Java:
1) public class Add
2) {
3) public static void main(String[] args)
4) {
5) int a,b;
6) a =10;
7) b=20;
8) [Link]("The Sum:"+(a+b));
9) }
10) }
C:
1) #include <stdio.h>
2)
3) void main()
4) {
5) int a,b;
6) a =10;
7) b=20;
8) printf("The Sum:%d",(a+b));
9) }
Python:
1) a=10
2) b=20
3) print("The Sum:",(a+b))
input() function
• Python user input from the keyboard can be read using the input()
built-in function.
• The input from the user is read as a string and can be assigned to a
variable.
• After entering the value from the keyboard, we have to press the
“Enter” button. Then the input() function reads the value entered by
the user.
Syntax
input(prompt)
The prompt is a String, representing a default message before the input.
The prompt string is printed on the console and the control is given to
the user to enter the value.
Examples
1. name=input("Enter your name")
print("hello " + name)
2. To convert the string input to integer we use the
int() function over the received input.
num = int(input("Enter an Integer: "))
print(num)
3. a=int(input("Enter your value"))
b=int(input("Enter your value"))
c=a+b
print("Addition of two numbers",c)
Type Conversion
The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion.
we use float() function to convert the received input into a float value.
num = float(input("Enter a float value: "))
print(num)
Output:
Enter a float value: 45.67
45.67
Example to check data type of input value
Python has a built-in function called type() that helps you find the class
type of the variable given as input. Using type() command, you can pass
a single argument, and the return value will be the class type of the
argument given, example: type(object).
number = input("Enter roll number ")
name = input("Enter age ")
print("\n")
print('Roll number:', number, 'Name:', name) Output
Enter roll number 22
print("Printing type of a input values") Enter age raja
print("type of number", type(number)) Roll number: 22 Name: raja
print("type of name", type(name)) Printing type of a input values
type of number <class 'str'>
type of name <class 'str'>
To check data type of input value
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
x=x+y
print(x)
print("x is of type:",type(x))
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
x is of type: <class 'float'>
Python Character Set
A set of valid characters recognized by python. Python uses the
traditional ASCII character set. The latest version recognizes the
Unicode character set. The ASCII character set is a subset of the
Unicode character set.
Letters :– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbol available over keyboard
White spaces:– blank space,tab,carriage return,new line, form feed
Other characters:- Unicode
Indentation
• Indentation refers to the spaces applied at the beginning of a code line. In other
programming languages the indentation in code is for readability only, where as the
indentation in Python is very important.
• Python uses indentation to indicate a block of code or used in block of codes. Python
uses indentation to express the block structure of a program.
• Indentation is used to specify blocks in Python. Where other programming
languages use curly brackets or keywords such as begin, end, Python uses white
space.
E.g.1
if 3 > 2:
print(“Three is greater than two!") //syntax error due to not indented
E.g.2
if 3 > 2:
print(“Three is greater than two!") //indented so no error
Token
Smallest individual unit in a program is known as token. Python breaks
each logical line into a sequence of elementary lexical components
known as tokens. Computer languages, like human languages, have
a lexical structure.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. punctuators
Keywords
Reserve word of the compiler/interpreter which can’t be used as
identifier.
Identifiers
A Python identifier is a name used to identify a variable, function, class,
module or other object.
* An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
* Identifier must not be a keyword of Python.
* Python is a case sensitive programming language.
Thus, Rollnumber and rollnumber are two different
identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no
Literals
Literals in Python can be defined as number, text, or other data that
represent values to be stored in variables. Technically, a literal is
assigned a value at compile time, while a variable is assigned at
runtime.
Example of String Literals in Python
name = ‘Python’ , fname =“raja”
Example of Integer Literals in Python(numeric literal)
age = 22
Example of Float Literals in Python(numeric literal)
height = 6.2
Example of Special Literals in Python
name = None
Escape sequence/Back slash character
constants
Operators
Operators can be defined as symbols that are used to perform
operations on operands.
Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators
Arithmetic Operators are used to perform arithmetic
operations like addition, multiplication, division etc.
2. Relational Operators/Comparison Operator
Relational Operators are used to compare the values.
3. Assignment Operators
Used to assign values to the variables.
4. Logical Operators
Logical Operators are used to perform logical operations on the given
two variables or values.
6. Membership Operators
The membership operators in Python are used to validate whether a
value is found within a sequence such as such as strings, lists, or tuples.
7. Identity Operators
Identity operators in Python compare the memory locations of two
objects.
Punctuators
Used to implement the grammatical and structure of a Syntax.
Following are the python punctuators.
Bitwise operators
• In Python, bitwise operators are used to performing bitwise
calculations on integers. The integers are first converted into binary
and then operations are performed on bit by bit, hence the name
bitwise operators.
OPERATOR DESCRIPTION SYNTAX
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
• Bitwise AND operator: Returns 1 if both the bits are 1 else 0.
• Bitwise or operator: Returns 1 if either of the bit is 1 else 0.
• Bitwise not operator: Returns one’s complement of the number.
• Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0
else returns false.
• 1 XOR 0 =1
• 0 XOR 1 =1
• 0 XOR 0=0
• 1 XOR 1=0
Backbone of Phython
1. Expression : - which is evaluated and produce result. E.g. (20 + 4) / 4
2. Statement :- instruction that does something.
e.g
a = 20
print("Python program")
3. Comments : which is readable for programmer but ignored by python
interpreter
1. Single line comment: Which begins with # sign.
2. Multi line comment (docstring): either write multiple line beginning with # sign
or use triple quoted multiple line. e.g.
‘’’this is my
first
python multiline comment
‘’’
4. Function: A function is a block of code which only runs when it is
called. You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function In Python a function is defined using the def
keyword: Example
def my_function():
print("Hello from a function")
To call a function, use the function name followed by parenthesis:
my_function()
5. Block: A Python program is constructed from code blocks. A
block is a piece of Python program text that is executed as a unit. The
following are blocks: a module, a function body, and a class definition
Variables
Variable is a name given to a memory location. A variable can consider as a container which
holds value. Python is a type infer language that means you don't need to specify the
datatype of variable. Python automatically get variable datatype depending upon the value
assigned to the variable.
Assigning Values To Variable
name = ‘python' # String Data Type
sum = None # a variable without value
a = 23 # Integer
b = 6.2 # Float
sum = a + b
print (sum)
Multiple Assignment: assign a single value to many variables
a = b = c = 1 # single value to multiple variable
a,b = 1,2 # multiple value to multiple variable
a,b = b,a # value of a and b is swaped
Variable Scope And Lifetime in Python Program
1. Local Variable
def fun():
x=8
print(x)
>>>fun()
2. Global Variable
x=8
def fun():
print(x)
>>>fun()
Constants
A constant is a type of variable whose value cannot be changed. It is
helpful to think of constants as containers that hold information which
cannot be changed later.
In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, functions, etc which is imported to the
main file. Inside the module, constants are written in all capital letters and
underscores separating the words.
Python doesn’t have built-in constant types.
By convention, Python uses a variable whose name contains all capital letters to
define a constant.
Examples:
PI = 3.14
MAX_SPEED = 100
Multiple values to multiple variables
• You can assign values to multiple variables on one line.
• Assign multiple values to multiple variables
• Assign the same value to multiple variables
1. a, b, c = 5, 3.2, "Hello“
print (a)
print (b)
print (c)
2. x = y = z = "same“
print (x)
print (y)
print (z)
You can take multiple inputs in one single line by using the input() function
3. A,B=int(input("Enter the Frint Number:")),int(input("Enter the Second Number"))
C=A+B
print("the Result is:",C)
Data types
• Data Type specifies which type of value a variable can store. type()
function is used to determine a variable's type in Python.
• Data Types in Python
1. Number
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary
1. Number In Python
It is used to store numeric values
Python has three numeric types:
1. Integers
2. Floating point numbers
3. Complex numbers
1. Integers
Integers or int are positive or negative numbers with no decimal point. Integers in Python 3 are
of unlimited size. e.g.
a= 100
b= -100
print(a)
print(b)
Output :-
100
-100
Type Conversion of Integer
int() function converts any data type to integer. e.g.
a = "101" # string
b=int(a) # converts string data type to integer.
c=int(122.4) # converts float data type to integer.
print(b)
print(c)
Output :-
101
122
Floating point numbers
It is a positive or negative real numbers with a decimal point. e.g.
a = 101.2
b = -101.4
c = 111.23
d = 2.3*3
print(a)
print(b)
print(c)
print(d)
Output :-
101.2
-101.4
111.23
6.8999999999999995
Complex numbers
Complex numbers are combination of a real and imaginary [Link]
numbers are in the form of X+Yj, where X is a real part and Y is imaginary
part.
e.g.
a = complex(5) # convert 5 to a real part val and zero imaginary part
print(a)
b=complex(101,23) #convert 101 with real part and 23 as imaginary part
print(b)
Output :-
(5+0j)
(101+23j)
Type Conversion of Floating point numbers
float() function converts any data type to floating point number.
e.g.
a='301.4' #string
b=float(a) #converts string data type to floating point number.
c=float(121) #converts integer data type to floating point number.
print(b)
print(c)
Output :-
301.4
121.0
2. String In Python
A string is a sequence of characters. In python we can create string using single (' ') or double quotes ("
").Both are same in python. e.g.
str='computer science'
print('str-', str) # print string
print('str[0]-', str[0]) # print first char
print('str[1:3]-', str[1:3]) # print string from postion 1 to 3
print('str[3:]-', str[3:]) # print string starting from 3rd char
print('str *2-', str *2 ) # print string two times
print("str +'yes'-", str +'yes') # concatenated string
Output
str- computer science
str[0]- c
str[1:3]- om
str[3:]- puter science
str *2- computer sciencecomputer science
str +'yes'- computer scienceyes
Iterating through string
The following are various ways to iterate the chars in a Python string.
In Python, while operating with String, one can do multiple operations on
it.
# Iterate over string
# Iterate over index
str='comp sc' str='comp sc'
for i in str: for element in range(0, len(str)):
print(i) print(str[element])
Output
c
o
m
p
s
C
3. Boolean In Python
It is used to store two possible values either true or false
e.g.
str=‘this is a string’
result=[Link]() # test if string contains upper case
print(result)
Output
False
[Link] In Python
List are collections of items and each item has its own index value. Index of first item is 0 and the last item is n-
[Link] n is number of items in a list. Lists are enclosed in square brackets [ ] and each item is separated by a comma.
e.g. of list
list =[6,9]
list[0]=55
print(list[0])
print(list[1])
OUTPUT
55
9
5. Tuple In Python
List and tuple, both are same except ,a list is mutable python objects and tuple is immutable Python objects.
Immutable Python objects mean you cannot modify the contents of a tuple once it is assigned.
e.g. of tuple
tup=(66,99)
tup[0]=3 # error message will be displayed
print(tup[0])
print(tup[1])
6. Set In Python
Sets are used to store multiple items in a single variable. It is an
unordered collection of unique and immutable (which cannot be
modified)items.
e.g.
set1={11,22,33,22}
print(set1)
Output
{33, 11, 22}
7. Dictionary In Python
It is an unordered collection of items and each item consist of a key and a value.
e.g.
dict = {'Subject': ‘Phython', ‘Class': ‘MCA'}
print(dict)
print ("Subject : ", dict['Subject'])
print (“Class : ", dict[‘Class’])
Output
{'Subject': ‘Phython', ‘Class': ‘MCA'}
Subject : Phython
Class : MCA
format() method
• The python format() method will return a formatted value as specified by the format
passed as a parameter.
Syntax: format(value, format)
• The first parameter contains the value on which the formatting operation is to be
performed and the second parameter specifies the format on how the value has to be
formatted.
Example: print (format (100, “d”))
# floating point numbers
print (format (100.12, “f”))
# binary format
print (format (7, “b”))
Output:
100
100.12
111
Number Formatting With Precision
Precision allows us to define the number of digits to be shown after a decimal point.
precision_value = format(123.4567, '.2f')
print(precision_value) # Output: 123.46
x = 12.3456789
print('The value of x is %3.2f' %x)
The value of x is 12.35
print('The value of x is %3.4f' %x)
The value of x is 12.3457
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
Palindrome program
def isPalindrome(string):
if (string == string[::-1]) :
return "The string is a palindrome."
else:
return "The string is not a palindrome."
#Enter input string
string = input ("Enter string: ")
print(isPalindrome(string))
Factorial program
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Fibonacci program
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1
while count <= n:
print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()
Output formatting
• Sometimes we would like to format our output to make it look attractive. This can be
done by using the [Link]() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which
they are printed by using numbers.
We can also format strings like the old sprintf() style used in C programming language.
We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Control Flow
• In Python programming, flow control is the order in which statements
or blocks of code are executed at runtime based on a condition.
• The flow control statements are divided into three categories
1. Conditional statements
2. Transfer statements
3. Iterative statements.
Conditional statements
• In Python, condition statements act depending on whether a given condition is true or
false. You can execute different blocks of codes depending on the outcome of a
condition. Condition statements always evaluate to either True or False.
• There are four types of conditional statements.
[Link] statement
[Link]-else
[Link]-elif-else
[Link] if-else
Iterative statements
• In Python, iterative statements allow us to execute a block of code repeatedly as long as
the condition is True. We also call it a loop statements.
• Python provides us the following two loop statement to perform some actions
repeatedly.
[Link] loop
[Link] loop
• Transfer statements
In Python, transfer statements are used to alter the program’s way of
execution in a certain manner. For this purpose, we use three types of
transfer statements.
[Link] statement
[Link] statement
[Link] statements
1. Conditional statements
In control statements, The if statement is the simplest form. It takes a
condition and evaluates to either True or False.
If the condition is True, then the True block of code will be executed,
and if the condition is False, then the block of code is skipped, and The
controller moves to the next line.
Syntax: Example:
if condition: number = 6
if number > 5:
statement 1 # Calculate square
print(number * number)
statement 2 print('Next lines of code’)
statement n
Output
36
Next lines of code
The if-else statement checks the condition and executes the if block of
code when the condition is True, and if the condition is False, it will
execute the else block of code.
Syntax: Example
password = input('Enter password ')
if condition: if password == "PYnative@#29":
print("Correct password")
statement 1 else:
else: print("Incorrect Password")
statement 2 Output 1:
Enter password PYnative@#29
If the condition is True, then Correct password
statement 1 will be executed Output 2:
Enter password PYnative
If the condition is False, statement 2 Incorrect Password
will be executed.
In Python, the if-elif-else condition statement has an elif blocks to chain
multiple conditions one after another. This is useful when you need to
check multiple conditions. With the help of if-elif-else we can make a tricky
decision. The elif statement checks multiple conditions one by one and if
the condition fulfils, then executes that code.
Example:
def user_check(choice):
Syntax : if choice == 1:
print("Admin")
if condition-1: elif choice == 2:
statement 1 print("Editor")
elif choice == 3:
elif condition-2: print("Guest")
else:
stetement 2 print("Wrong entry")
user_check(1)
elif condition-3: user_check(2)
user_check(3)
stetement 3 user_check(4)
... Output
Admin
else: Editor
Guest
statement Wrong entry
In Python, the nested if-else statement is an if statement inside another if-else
statement. It is allowed in Python to put any number of if statements in another
if statement. Indentation is the only way to differentiate the level of nesting. The
nested if-else is useful when we want to make a series of decisions.
Example:
Syntax: num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
if conditon_outer: if num1 >= num2:
if condition_inner: if num1 == num2:
print(num1, 'and', num2, 'are equal')
statement of inner if else:
print(num1, 'is greater than', num2)
else: else:
print(num1, 'is smaller than', num2)
statement of inner else: Output1:
statement of outer if Enter first number 56
Enter second number 15
else: 56 is greater than 15
Output2:
Outer else Enter first number 29
Enter second number 78
statement outside if block 29 is smaller than 78
2. Iterative statements
while loop in Python
• In Python, The while loop statement repeatedly executes a code block
while a particular condition is true.
• In a while-loop, every time the condition is checked at the beginning
of the loop, and if it is true, then the loop’s body gets executed. When
the condition became False, the controller comes out of the block.
Example:
Syntax: num = 10
sum = 0
while condition : i=1
body of while loop while i <= num:
sum = sum + i
i=i+1
print("Sum of first 10 number is:", sum)
Output:
Sum of first 10 number is: 55
We use a for loop when we want to repeat a code block a fixed number of times.
Using for loop, we can iterate any sequence or iterable variable. Sequences are
a generic term for an ordered set. The sequence can be string, list, dictionary, set,
or tuple.
Syntax:
for element in sequence:
body of for loop
Example:
for i in range(1, 11):
print(i)
Output:
1
2
..
10
3. Transfer statements
The break statement is used inside the loop to exit out of the loop. It is
useful when we want to terminate the loop as soon as the condition is
fulfilled instead of doing the remaining iterations. It reduces execution
time. Whenever the controller encountered a break statement, it
comes out of that loop immediately.
Example: Output:
for num in range(10): 0
1
if num > 5: 2
3
print("stop processing.") 4
break 5
stop processing.
else:
print(num)
• The continue statement is used to skip the current iteration and continue with
the next iteration. In Python, when the continue statement is encountered
inside the loop, it skips all the statements below it and immediately jumps to
the next iteration.
Example:
for num in range(3, 8):
if num == 5:
continue
else:
print(num)
Output:
3
4
6
7
• The pass is the keyword In Python, which won’t do anything. Sometimes there is a situation in
programming where we need to define a syntactically empty block. We can define that block with
the pass keyword.
• A pass statement is a Python null statement. When the interpreter finds a pass statement in the
program, it returns no operation. Nothing happens when the pass statement is executed.
• It is useful in a situation where we are implementing new methods or also in exception handling.
It plays a role like a placeholder. We can do the same thing in an empty function or class as well.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future. They cannot have an empty body. The interpreter would give an error. So, we use the
pass statement to construct a body that does nothing.
def function(args):
pass
class Example:
pass
Example:
months = ['Jan', ‘Feb', 'March', 'April'] Output:
for mon in months: ['Jan', ‘Feb', 'March', 'April']
pass
print(months)