Programming with Python - I
Unit I
UNIT I
PYTHON
• Python is one of the most dynamic and versatile programming
languages.
• It is a high-level programming language.
• It was created by Guido van Rossum during 1985- 1990.
• It is named after a BBC comedy series from the 1970s “Monty
Python’s Flying Circus”.
Features
Steps to Download and Install Python
3.8 for Windows
• To start, go to python.org/downloads and then click
on the button to download the latest version of
Python
Steps
• Step 2: Run the .exe file
• Next, run the .exe file that you just downloaded
• Step 3: Install Python 3.8
• You can now start the installation of Python by
clicking on Install Now
• Note that depending on your needs, you may also
check the box to Add Python to the Path.
• Your installation should now begin
• After a short period of time, your setup would be
completed
• So we have installed Python for Windows
• A quick way to find your Python IDLE on Windows is by clicking on
the Start menu. You should then see the IDLE under “Recently added”
• Once you click on the Python IDLE, you would then
see the Shell screen
Python prompt
• The three greater-than signs (>>>) represent python’s prompt.
• You type your commands after the prompt, and hit return for python
to execute them.
• If you’ve typed an executable statement, python will execute it
immediately and display the results of the statement on the screen.
To write in editor
• print ("Hello World")
• Save the file as Test
• It gets saved as Test.py
Types of Numeric Data
• There are four distinct numeric types:
• plain integers,
• floating point numbers, and
• complex numbers.
• In addition, Booleans are a subtype of plain integers.
• Python allows you to enter numbers as either
• octal (base 8) or
• hexadecimal (base 16) constants.
• Octal constants are recognized by python because they start with a
leading (O)
• Hexadecimal constants start with a leading zero, followed by the
letter “x”
Arithmetic operators
OPERATOR DESCRIPTION
+ Addition: adds two operands
- Subtraction: subtracts two operands
* Multiplication: multiplies two operands
Division (float): divides the first operand by the
/ second
Division (floor): divides the first operand by the
// second
Modulus: returns the remainder when first
% operand is divided by the second
** Power : Returns first raised to power second
Operator precedence
• >>> (212 - 32.0) * 5.0 / 9.0
• 100.0
Relational Operators
Operator Description Example
== If the values of two operands are (a == b) is not true.
equal, then the condition becomes
true.
!= If values of two operands are not (a != b) is true.
equal, then condition becomes true.
<> If values of two operands are not (a <> b) is true. This is similar to !=
equal, then condition becomes true. operator.
> If the value of left operand is greater (a > b) is not true.
than the value of right operand, then
condition becomes true.
< If the value of left operand is less (a < b) is true.
than the value of right operand, then
condition becomes true.
>= If the value of left operand is greater (a >= b) is not true.
than or equal to the value of right
operand, then condition becomes
true.
<= If the value of left operand is less (a <= b) is true.
than or equal to the value of right
operand, then condition becomes
true.
Logical operators
OPERATOR DESCRIPTION SYNTAX
Logical AND: True if both
and x and y
the operands are true
Logical OR: True if either
or x or y
of the operands is true
Logical NOT: True if
not not x
operand is false
Assignment operators
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
Bitwise operator
OPERATOR DESCRIPTION SYNTAX
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Built-in functions
• abs(x): Return the absolute value of a number.
• bin(x): Convert an integer number to a binary string prefixed with
“0b”.
• complex([real[, imag]]) : convert a string or number to a complex
number.
Built-in functions
• float([x]): Return a floating point number constructed from a number
or string x.
• hex(x): Convert an integer number to a lowercase hexadecimal string
prefixed with “0x”.
• input([prompt]): The function reads a line from input, converts it to a
string and returns that.
Built-in functions
• int(x): Return an integer object constructed from a number or
string x.
• oct(x): Convert an integer number to an octal string prefixed with
“0o”.
• pow(base, exp) The two-argument form pow(base, exp) is equivalent
to using the power operator: base**exp.
Built-in functions
• round(number[, ndigits]):Return number rounded
to ndigits precision after the decimal point.
• type(name): With one argument, return the type of
an object.
Statement types
• Simple statements
Count = 10
A = ‘Python’
• Expression statement
>>>((10 + 2) * 100 / 5 - 200)
40.0
>>> c = pow(2, 10)
>>> print(c)
1024
• Assignment Statement
count = 10
message = "Hello“
• Assert Statement
assert 5 < 10
assert (True or False)
• import module1[, module2[,... moduleN]
• from module2 import *
• del Statement
• A= “Hello”
• del A
List
• A list is a container that can be used to store multiple data at once.
• The elements are indexed according to a sequence and the indexing is
done with 0 as the first index.
Create List
• To create a list, you separate the elements with a
comma and enclose them with a bracket “[]”.
>>> companies = [“Alphabet", "google", “Wipro"]
empty list
New_list = []
list of integers
num_list = [1, 2, 3]
Access elements from a list
List Index
• We can use the index operator [] to access an item in
a list. In Python, indices start at 0.
list_n = ['p', 'r', 'o', 'b', 'e']
print(list_n[0])
Output: p
print(list_n[2])
Output: o
Nested list
• A list can also have another list as an item. This is called a nested list.
New_list = ["mouse", [8, 4, 6], ['a']]
Nested lists are accessed using nested indexing.
Nested list
# Nested indexing
n_list = ["Happy", [2, 0, 1, 5]]
print(n_list[0][1])
a
Negative indexing
• Python allows negative indexing for its sequences. The index of -1
refers to the last item, -2 to the second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1])
e
print(my_list[-5])
p
Mutable
• Lists are mutable, meaning their elements can be
changed
Correcting mistake values in a list
• odd = [2, 4, 6, 8]
change the 1st item
• odd[0] = 1
• print(odd)
[1, 4, 6, 8]
Add elements to the list
• We can add one item to a list using
the append() method or add several items
using extend() method.
• odd = [1, 3, 5]
• odd.append(7)
• print(odd)
• [1, 3, 5, 7]
• odd.extend([9, 11, 13])
• print(odd)
• [1, 3, 5, 7, 9, 11, 13]
Insert
• we can insert one item at a desired location by using
the method insert() or insert multiple items by
squeezing it into an empty slice of a list.
• odd = [1, 9]
• odd.insert(1,3)
• print(odd)
[1, 3, 9]
Concatenation
• We can also use + operator to combine two lists. This is also called
concatenation.
• The * operator repeats a list for the given number of times.
• odd = [1, 3, 5]
• print(odd + [9, 7])
Output: [1,3,5,9,7]
To delete or remove elements from a list
• del_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
delete one item
• del del_list[2]
• print(del_list)
Output: ['p', 'r', 'b', 'l', 'e', 'm']
Remove method
my_list=['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
Output: ['r', 'o', 'b', 'l', 'e', 'm']
pop() method to remove an item at the given index.
nlist=['W','E','L','C','O','M','E']
>>> nlist.pop(1)
'E'
>>> print(nlist)
['W', 'L', 'C', 'O', 'M', 'E']
Pop and clear
>>> print(nlist)
['W', 'L', 'C', 'O', 'M', 'E']
>>> nlist.pop()
'E'
>>> print(nlist)
['W', 'L', 'C', 'O', 'M']
>>> nlist.clear()
>>> print(nlist)
[]
List methods
index() - Returns the index of the first matched
item
count() - Returns the count of the number of
items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
List Membership Test
We can test if an item exists in a list or not, using the
keyword ’in’.
>>> p_list = ['P','Y','T','H','O','N']
>>> print('P' in p_list)
True
>>> print('A' not in p_list)
True
Sorted and len function
>>> print(sorted(p_list))
['H', 'N', 'O', 'P', 'T', 'Y']
>>> print(p_list)
['P', 'Y', 'T', 'H', 'O', 'N']
>>> print(len(p_list))
6
Functions
• max(): It returns the item from the list with the highest value.
• min(): It returns the item from the Python list with the lowest value.
• sum(): It returns the sum of all the elements in the list.
Slice lists in Python
If we want to get a sublist of the list. Or we want to
update a bunch of cells
>>> list2=['W','O','N','D','E','R','F','U','L']
>>> print(list2[2:6])
['N', 'D', 'E', 'R']
Strings
• A Python string is a sequence of characters.
>>> s='Welcome to K. C. College'
>>> print(s)
Welcome to K. C. College
>>> s='''Welcome to K. C. College'''
>>> print(s)
Welcome to K. C. College
Access the string
>>> s1 = "PYTHON"
>>> print(s1[2])
T
Negative indices can be used
>>> print(s1[-2])
O
Immutable
• Strings in python are immutable objects; this means
that you can’t change the value of a string in place.
>>> s1 = "PYTHON"
>>> s1[2]= 'D'
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
s1[2]= 'D'
TypeError: 'str' object does not support item
assignment
Slicing
>>> s2='Photography'
>>> print(s2[4:9])
ograp
String Concatenation
>>> a = "Hello "
>>> b = "Friends"
>>> c=a+b
>>> print(c)
Hello Friends
String operation
>>> a = "Hello "
>>> print(a*3)
Hello Hello Hello
>>> p=‘20'
>>> print(p*2)
??
Formating
>>> name = 'Ayush'
>>> stay = 'Andheri'
>>> print(name, “stays at “, stay)
Ayush stays at Andheri
% operator
>>> name = 'Ayush'
>>> stay = 'Andheri'
>>> print(" %s stays at %s. "%(name,stay))
Ayush stays at Andheri.
>>> age = 15
>>> print('%s stays at %s, his age is %i ‘ %(name,stay,age))
Ayush stays at Andheri, his age is 15
Escape Character
• To insert characters that are illegal in a string, use an escape
character.
• An escape character is a backslash \ followed by the character you
want to insert.
• An example of an illegal character is a double quote inside a string
that is surrounded by double quotes
• Text = “The cat said “Meow””
• Text = “The cat said \“Meow\””
String Functions
• len(): The len() function returns the length of a string.
• str(): This function converts any data type into a string.
Methods
• lower() and upper(): These methods return the string in lowercase
and uppercase, respectively.
• strip(): It removes whitespaces from the beginning and end of the
string.
String Methods
• isdigit(): Returns True if all characters in a string are digits.
• isalpha(): Returns True if all characters in a string are characters from
an alphabet.
• isspace(): Returns True if all characters in a string are spaces.
• startswith(): It takes a string as an argument, and returns True is the
string it is applied on begins with the string in the argument.
String Methods
• endswith(): It takes a string as an argument, and returns True if the
string it is applied on ends with the string in the argument.
• find(): It takes an argument and searches for it in the string on which
it is applied. It then returns the index of the substring
• If the string doesn’t exist in the main string, then the index it returns
is 1..
String Methods
• split(): It takes one argument. The string is then split around every
occurrence of the argument in the string.
• replace(): It takes two arguments. The first is the substring to be
replaced. The second is the substring to replace with.
• join(): It takes a list as an argument and joins the elements in the list
using the string it is applied on.
String Functions
• len(): The len() function returns the length of a string.
• str(): This function converts any data type into a string.
Methods
• lower() and upper(): These methods return the string in lowercase
and uppercase, respectively.
• strip(): It removes whitespaces from the beginning and end of the
string.
String Methods
• isdigit(): Returns True if all characters in a string are digits.
• isalpha(): Returns True if all characters in a string are characters from
an alphabet.
• isspace(): Returns True if all characters in a string are spaces.
• startswith(): It takes a string as an argument, and returns True is the
string it is applied on begins with the string in the argument.
String Methods
• endswith(): It takes a string as an argument, and returns True if the
string it is applied on ends with the string in the argument.
• find(): It takes an argument and searches for it in the string on which
it is applied. It then returns the index of the substring
• If the string doesn’t exist in the main string, then the index it returns
is 1..
String Methods
• split(): It takes one argument. The string is then split around every
occurrence of the argument in the string.
• replace(): It takes two arguments. The first is the substring to be
replaced. The second is the substring to replace with.
• join(): It takes a list as an argument and joins the elements in the list
using the string it is applied on.
Comparison
• ‘hey’ is lesser than ‘hi lexicographically
>>> a=‘hey
>>> b=‘hi’
>>> a<b
True
Arithmetic
>>> print(“Ba”+”ta”*2)
??
Tuples
• A tuple is a collection of items which are ordered and immutable.
• Tuples are sequences, just like lists.
• The differences between tuples and lists are, the tuples cannot be
changed unlike lists
• Tuples use parentheses, whereas lists use square brackets.
Creating Tuple
• tup1 = ('physics', 'chemistry', 1997, 2000)
• tup2 = (1, 2, 3, 4, 5 )
• T1 = ()
• Tuples are immutable which means you cannot update or change the
values of tuple elements.
PACKING
a="a","b","c","d“
print(a)
UNPACKING
p,q,r,s = a
print(q)
??
Nested tuples
b=((4,5,6),(8,9,1))
>>> b[0]
(4, 5, 6)
>>> b[0][2]
6
Deleting elements
• Removing individual tuple elements is not possible.
t =(4,5,6,7)
del t[1] will give error
del t the entire tuple can be deleted
Changing items
• Tuples are immutable, so the elements cannot be changed.
• However a mutable item that it holds may be changed.
Functions
• len()
• max()
• min()
• sum()
• sorted()
• tuple()
Python Dictionary
• A dictionary is a collection which is unordered, changeable and
indexed.
• Each key is separated from its value by a colon (:),
• The items are separated by commas, and
• The whole thing is enclosed in curly braces.
• Keys are unique within a dictionary while values may not be.
Creating a Python Dictionary
• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
• D3={0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
dict2={1:2,1:3,1:4,2:4}
print(dict2)
{1: 4, 2: 4}
Accessing
D3={0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}
>>> D3[36]
???
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> dict[‘Age’]
Functions
• len()
• sorted()
Methods
• keys()
• values()
• items()
• get()
• clear()
• copy()
• pop()
• popitems()
• fromkeys()
Nested Dictionary
>>> dict1={4:{1:2,2:4},8:16}
>>> dict1
{4: {1: 2, 2: 4}, 8: 16}