Introduction to Python Programming
Introduction to Python Programming
• It was mainly developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code.
GUIDO VAN ROSSUM was a fan of the popular comedy show “Monty
Pythons Flying circus” broadcasted by BBC(1969 – 74). So he decides to choose
that name for his language as python.
Features in Python
1. Free and Open Source :
• Python language is freely available at the official website and you can download it
freely.
• Open-source means that source code is also available to the public. So you can
download it, use it as well as share it.
2. Easy to code:
4. Object-Oriented Language:
• One of the key aspects of any programming language is support for GUI or
Graphical User Interface.
• A user can easily interact with the software using a GUI.
• Python offers various toolkits, such as Tkinter, wxPython and JPython, which
allows for GUI's easy and fast development.
6. High-level Language :
7. Extensible feature :
Python is an Extensible language. We can write some Python code into C or C++
language and also we can compile that code in C/C++ language.
8. Easy to Debug :
• Python is portable in the sense that the same code can be used on different
machines.
• For example, if we have Python code for windows and if we want to run this code
on other platforms such as Linux, Unix, and Mac then we do not need to change
it, we can run this code on any platform.
• As such, there is no need to write a program multiple times for several platforms.
10. Interpreted Language:
• Python has a large standard library that provides a rich set of modules and
functions so you do not have to write your own code for every single thing.
• There are many libraries present in Python such as regular expressions, unit-
testing, web browsers, etc.
12. Allocating Memory Dynamically :
13. Expressive :
• Python needs to use only a few lines of code to perform complex tasks.
• For example, to display Hello World, you simply need to type one line -
print(“Hello World”). Other languages like Java or C would take up multiple lines
to execute this.
IDENTIFIERS
Identifier names in Python can contain numbers (0-9), uppercase letters (A-Z),
lowercase letters (a-z), and underscore (_).
The name should always start with a non-numeric character. Eg: 5a =10
An identifier name should not contain numeric characters only.
Users can begin identifiers with an underscore; it will not display an error.
Eg _a= 5
Valid Python Identifiers
• _ : this may look odd, but a single underscore can be used as an identifier name.
• TeXt : identifier names can contain uppercase and lowercase alphabets in any
pattern.
• DRE, dre and Dre : will be considered three different identifier names due to the
difference in the case.
Invalid Python Identifiers
999: Identifier names that cannot contain only digits or numeric values.
x+iy: identifier names cannot contain any other special character except
underscore.
• Keywords are reserved words whose meaning is already defined in the python
interpreter.
• Python has a set of keywords that cannot be used as variable names, function
names, or any other identifiers.
• Python contains a total of 33 keywords.
Keyword Description
and A logical operator
as To create an alias (we can give another
name of the function)
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as
else if
else Used in conditional statements
except Used with exceptions, what to do when
an exception occurs
False Boolean value, result of comparison
operations
finally Used with exceptions, a block of code that
will be executed no matter if there is an
exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple,
etc
is To test if two variables are equal
Creating Variables
Example:
et
x=5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any particular type, and can even change
type after they have been set.
Example
Casting
• If you want to specify the data type of a variable, this can be done with casting.
Example
• You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes:
Example:
Example :
a=4
A = "Sally"
#A will not overwrite a
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Comments in Python
• Comments in Python is the inclusion of short descriptions along with the code to
increase its readability.
• A developer uses them to write his or her thought process while writing the code.
• It explains the basic logic behind why a particular line of code was written.
• Python interpreter completely ignores comments in Python.
• Comments in Python are identified with a hash symbol, #, and extend to the end of
the line.
• There are multiple uses of writing comments in Python:
1. Increasing readability
2. Explaining the code to others
3. Understanding the code easily after a long-term
4. Including resources
5. Re-using the existing code
What Are the Advantages of Using Comments in Python?
Single-Line Comments :
• Single-line comments begin with the “#” character.
• Anything that is written in a single line after ‘#’ is considered as a comment.
The syntax for writing single-line comments is:
# comments here
There are two ways of using single-line comments in Python. You can use it before
the code or next to the code.
Eg : #you can
#create the comment
#using multiline
• The next way is by using string literals but not assigning them to any variables.
• If you do not assign a string literal to a variable, the Python interpreter ignores it.
• Use this to your advantage to write multi-line comments.
• You can either use a single (‘’) quotation or double (“”) quotation.
Python Docstrings :
Python input:
• Until now our program was static, the values were defined to the variables. In
some cases user might want to input values to variables, which allows flexibility.
• Python has input() function to perform this.
Syntax:
Example:
Example:
• To make your output look easy on the eye, you have to format the actual
appearance of the output.
Example:
x=5
y = 10
Python Import:
• When your program grows deeper, we cannot keep writing codes for each and
every action we need to perform. So in real time, we break the program into
different modules.
• Python has various modules and libraries. These modules contain python
definitions and statements.
• Definitions inside a module can be imported into another module or interactive
interpreter in python.
• We use import keyword do perform this.
import math
pie = [Link]
print("The value of pi is : ",pie)
Python Operators
Operators are special symbols that perform operations on variables and values.
For example,
print(5 + 6) # 11
Here, + is an operator that adds two numbers: 5 and 6. 5 and 6 are called operands.
Types of Python Operators :
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Identity Operators
7. Membership Operators
sub = 10 - 5 # 5
Here, - is an arithmetic operator that subtracts two values or variables.
a=7 Example
Operator Operation Example b=2
# addition
+ Addition 5+2=7 print ('Sum: ', a + b)
# subtraction
- Subtraction 4-2=2 print ('Subtraction: ', a - b)
# multiplication
* Multiplication 2*3=6 print ('Multiplication: ', a * b)
# division
/ Division 4/2=2
print ('Division: ', a / b)
Output
// Floor Division 10 // 3 = 3 # floor division
print ('Floor Division: ', a // b) Sum: 9
Subtraction: 5
% Modulo 5%2=1 # modulo Multiplication: 14
print ('Modulo: ', a % b) Division: 3.5
Floor Division: 3
** Power 4 ** 2 = 16 # a to the power b Modulo: 1
print ('Power: ', a ** b) Power: 49
2. Python Assignment Operators:
# assign 5 to x
var x = 5
Here, = is an assignment operator that assigns 5 to x.
Operator Name Example
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
# assign 10 to a
a = 10
# assign 5 to b
b=5
3 < 5 gives us
print (a > b) # True < Less Than
True
# equal to operator
print('a == b =', a == b)
and a and b Logical AND: True only if both the operands are True
not not a Logical NOT: True if the operand is False and vice-versa
For example,
Here, and is the logical operator AND.
a=5
b=6 Since both a > 2 and b >= 6 are True, the
result is True.
print((a > 2) and (b >= 6)) # True
5. Python Bitwise operators
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
• In Python, is and is not are used to check if two values are located on the same
part of the memory.
• Two variables that are equal does not imply that they are identical.
True if the operands are not identical (do not refer to the
is not x is not True
same object)
x = 200
y = 100
For example, z=y
• They are used to test whether a value or variable is found in a sequence (string,
list, tuple, set and dictionary).
x = 'Hello world'
y = {1:'a', 2:'b'}
num2 = -12
print(type(num2)) output : < class 'int’ >
var1 = True
print(type(var1)) output : < class ‘bool’ >
float1 = -121.9
print(type(float1)) output : < class ‘float’ >
float2 = -9.8*10**2
print(float2, type(float2)) output : 980.0000000000001 < class ‘float’ >
var2 = -3+7.2j
print(type(var2)) output:< class ‘complex’ >
Variables of simple data types like integers, float, Boolean, etc., hold
single values.
But such variables are not useful to hold a long list of information, for
example, names of the months in a year, names of students in a class,
names and numbers in a phone book or the list of artefacts in a museum.
For this, Python provides data types like tuples, lists, dictionaries and
sets. 2. Sequence
• The three types of sequence data types available in Python are Strings,
Lists and Tuples.
String :
Syntax:
str = "Hi Python !"
For example,
str1 = 'Hello Friend’
str2 = "452"
We cannot perform numerical operations on strings, even when the string
contains a numeric value, as in str2.
The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
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.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[6]) # It returns the Index
Error because 6th index
Output:doesn't exist
H
E
L
L
O
IndexError: string index out of range
In Python, 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.
Example:
• Python lists are mutable type which implies that we may modify its
element after it has been formed.
Characteristics of Lists
# a simple list
print(type(list1))
print(type(list2))
Ordered List Checking
• The indexing is processed in the same way as it happens with the strings.
• The elements of the list can be accessed by using the slice operator [].
• The first element of the list is stored at the 0th index, the second element of
the list is stored at the 1st index, and so on.
Negative indexing :
• In contrast to other languages, Python gives you the option to employ negative
indexing as well.
• The final element on the right-hand side of the list is represented by the index -1,
followed by the next member on the left at the index -2, and so on until the last
element on the left is reached.
list = [1,2,3,4,5]
Output:
print(list[-1])
5
print(list[-3:])
[3, 4, 5]
print(list[:-1])
[1, 2, 3, 4]
print(list[-3:-1])
[3, 4]
List Indexing
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1]) Output:
1
# Slicing the elements 2
print(list[0:6]) [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
# By default, the index value is 0 [3, 4, 5]
#so its starts from the 0th element and go for index -1. [2, 4, 6]
print(list[:])
print(list[2:5])
print(list[Link])
Updating List Values
• Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.
• The list elements can also be deleted by using the del keyword.
Python also provides us the remove() method if we do not know
which element is to be deleted from the list.
# updating list values
list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10 Output:
print(list) [1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
# Adding multiple-element [1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
list[1:3] = [89, 78]
print(list)
Example :
Create a Tuple:
• Tuples are an immutable data type, which means that once they have been
generated, their elements cannot be changed.
• Since tuples are ordered sequences, each element has a specific order that
will never change.
Creating of Tuple:
• To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (),
each one separated by a comma.
• A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).
Code:
# Python program to show how to create a tuple
# Creating tuple having integers
Code
1. Indexing
• To access an object of a tuple, we can use the index operator [], where indexing
in the tuple starts from 0.
• A tuple with 5 items will have indices ranging from 0 to 4.
Slice Operator
print(tuple[0][3])
print(tuple[1][1])
print(tuple[2][0])
# Negative indexing
tuple = ("P " "y ", "t ", "h“, "o " , " n")
print(tuple[-1])
print(tuple[-4 : -1])
#column operator
print(tuple[0 : 3])
print(tuple[ : 5])
Python Set
Creating a set
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Adding items to the set
• Python provides the add() method and update() method which can be used to
add some particular item to the set.
• The add() method is used to add a single element whereas the update()
method is used to add multiple elements to the set.
• Python provides the discard() method and remove() method which can be used
to remove the items from the set.
• The difference between these function, using discard() function if the item does
not exist in the set then the set remain unchanged whereas remove() method will
through an error.
Example : Using discard() and remove() function
• Python provides the clear() method to remove all the items from the set.
Example:
[Link]()
print("Printing the modified set...")
print(Months)
• The simplest approach to create a Python dictionary is by using curly brackets {},
but there are other methods as well.
• The dictionary can be created by using multiple key-value pairs enclosed with the
curly brackets {}, and each key is separated from its value by the colon (:).
Syntax:
Dict = {"Name": "Anu", "Age": 20}
• Python provides the built-in function dict() method which is also used to create
the dictionary.
• The empty curly braces {} is used to create empty dictionary.
Example:
# Creating a Dictionary
# with dict() method
We can access values using keys ,but we can't access keys using values.
• The dictionary is a mutable data type, and its values can be updated by using the
specific keys.
• The value can be updated along with key Dict[key] = value.
• The update() method is also used to update an existing value.
Example : Output :
student = {"Name": "Anu", "Age": 20, "Fees":25000} {'Name': 'Anu', 'Age': 20, 'Fees': 25000}
{'Name': 'Ammu', 'Age': 20, 'Fees': 30000}
print(student)
student["Fees"]=30000
student["Name"]="Ammu"
print(student)
Deleting Elements using del Keyword
• The items of the dictionary can be deleted by using the del keyword
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming.
In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement.
x = 10 Output:
print("x is of type:",type(x))
y = 10.6 x is of type: <class 'int'>
print("y is of type:",type(y)) y is of type: <class 'float'>
z=x+y 20.6
print(z) z is of type: <class 'float'>
print("z is of type:",type(z))
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data type.
Various forms of explicit type conversion are :
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies
the base in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.
9. dict() : This function is used to convert a tuple of order (key,value) into a
dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.
12. chr(number) : This function converts number to its corresponding ASCII
character.
flow control is the order in which statement or block of code are executed at runtime
based on a condition.
1. Conditional statements
2. Iterative statements.
3. Transfer statements
1. CONDITIONAL STATEMENTS
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
If statement in Python
if condition: Example:
statement 1
statement 2 number = 6
statement n if number > 5:
# Calculate square
print(number * number)
If – else statement
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.
if condition:
statement 1
else:
statement 2
if-elif-else condition statement
• 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.
• The elif statement checks multiple conditions one by one and if the condition fulfills,
then executes that code.
Syntax of the if-elif-else statement: Syntax of the nested-if-else:
if condition-1: if conditon_outer:
statement 1 if condition_inner:
elif condition-2: statement of inner if
stetement 2 else:
elif condition-3: statement of inner else:
stetement 3 statement ot outer if
... else:
else: Outer else
statement statement outside if block
1. for loop
2. while loop
Python for loop
• We use a for loop when we want to repeat a code block a fixed number of times.
• In Python, the for loop is used to iterate over a sequence such as a list, string,
tuple, other iterable objects such as range.
• With the help of for loop, we can iterate over each item present in the sequence
and executes the same set of operations for each item.
• Using a for loops in Python we can automate and repeat tasks in an efficient
manner.
As opposed to while loops that execute until a condition is true, for loops are
executed a fixed number of times
Syntax of for loop
for i in range/sequencee:
statement 1
statement 2
statement n
• In the syntax, i is the iterating variable, and the range specifies how many times
the loop should run. For example, if a list contains 10 numbers then for loop will
execute 10 times to print each number.
• In each iteration of the loop, the variable i get the current value.
The range() function returns a sequence of numbers starting from 0 (by default) if
the initial limit is not specified and it increments by 1 (by default) until a final limit is
reached.
The range() function is used with a loop to specify the range (how many times) the
code block will be executed.
Syntax :
Start : (Lower limit) It is the starting position of the sequence. The default value is 0
if not specified. For example, range(0, 10). Here, start=0 and stop = 10
Step : Specify the increment value. Each next number in the sequence is generated
by adding the step value to a preceding number. The default value is 1 if not
specified. It is nothing but a difference between each number in the result. For
example, range(0, 6, 1). Here, step = 1.
• The while loop statement repeatedly executes a code block while a particular
condition is true.
• In simple words, The while loop enables the Python program to repeat a set of
operations while a particular condition is true. When the condition becomes
false, execution comes out of the loop immediately, and the first statement after
the while loop is executed.
while condition:
# Block of statement(s)
• The while statement checks the condition. The condition must return a Boolean
value. Either True or False.
• Next, If the condition evaluates to true, the while statement executes the
statements present inside its block.
• The while statement continues checking the condition in each iteration and
keeps executing its block until the condition becomes false.
2. 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.
1. break statement
2. continue statement
3. pass 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
Output
Example of using a break statement
0
for num in range(10): 1
if num > 5: 2
print("stop processing.") 3
break 4
print(num) 5
stop processing.
2. Continue statement in python
The continue statement is used to skip the current iteration and continue with the
next iteration.
Example of a continue statement Output
Example Output