Advance Python Compressed$20241122125807

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Python Programming

Introduction and Background


• Python was by Guido Van Rossum and released in 1991 by
Python software foundation.
• It’s source code is available under the General Public
License (GPL).
• It uses object oriented style or technique that encapsulates
codes
within objects.
• It is highly readable.
• Uses mostly English keywords as compared to
punctuations used by other languages.
• Fewer syntactical constructions.
• Prebuilt libraries like NumPy for scientific computations,
Matplotlib for plotting 2D figures like line, histogram, bar
graph, NLTK, OpenCV
• Platform independent.
IDE or IDLE
• Acronym of Integrated Development Environment. It lets one edit, run,
browse and debug Python Programs from a single interface. This
environment makes it easy to write programs. It is GUI integrated and is the
standard, most popular Python development environment.
• Two modes -
– Interactive mode - allows us to interact with OS from the
command line or command prompt.
– Script mode lets us create and edit Python source file. Python
programs are written in a file and then using the interpreter,
contents from the file are executed.
Input
Process
Output
Flowchart - 2

Input
Process
Output
Variable
A placeholder or a named location to hold or store
the data in memory. Ex: a = 5, b = “hello”
print() and input()

• print() function to output data to the standard output


device (screen).
• input() function allows us to take user’s input into the
program.
– By default input () returns a string value.
Task Sample Code Output
Assigning a value to a txt = “hi learner" hi learner
variable print(txt)
Changing value of a txt = “hi learner" hi learner
variable print(txt) welcome to python
txt = “welcome to programming
python programming"
print(txt)
Assigning different a,b,c=5, 3.2, "Hello" 5
values to different print(a) 3.2
variables print(b) Hello
print(c)
Assigning same value to x=y=z=“same" same
different variable print(x) same
print(y) same
print(z)
Constants

• A constant is a type of variable whose value cannot be


changed.
• Create an info.py
Name = “<Your Name>”
Age = 18
• Create a main.py
import info
print(info.Name)
print(info.Age)
Datatype
• Every value in Python has a datatype. Since everything is an object in
Python programming. Data types are actually classes and variables are
instance (object) of these classes. In other words, they define the type of
the variable.
Datatypes

Numbers Sequences Sets Maps

int float string list tuple dictionary


Type Conversion

• Implicit Type Conversion: Python automatically converts


one data type to another data type. This process doesn't
need any user involvement.
• Explicit Type Conversion: users convert the data type of
an object to required data type. We use the predefined
functions like int(), float(), str(), etc to perform explicit type
conversion.
– This type of conversion is also called typecasting because the
user casts (changes) the data type of the objects.
1) Python Numbers : Numerical Values.
– Integer & Long Integer: Range of an integer in Python can
be from -2147483648 to 2147483647, and long integer has
unlimited range subject to available memory.
– Float / floating point: Numbers with fractions or decimal
point are called floating point numbers.
• A floating-point number will consist of sign (+,-) sequence
of decimals digits and a dot such as 0.0, -21.9,
0.98333328, 15.2963. These numbers can also be used
to represent a number in engineering/ scientific notation.
• -2.0 x 105 will be represented as -2.0e5
• 2.0X10-5 will be 2.0E-5
2) Sequence: A sequence is an ordered collection of items,
indexed by positive integers.
– Strings - String is an ordered sequence of
letters/characters. They are enclosed in single quotes (‘ ‘) or
double (“ “).
– Lists - List is also a sequence of values of any type. Values
in the list are called elements / items. These are
indexed/ordered. List is enclosed in square brackets.
• Example: dob = [19,"January",1990]
– Tuples - Tuples are a sequence of values of any type, and
are indexed by integers. They are immutable. Tuples are
enclosed in ().
• Example: t = (5,'program',2.5)
3) Sets: It is an unordered collection of values, of any type, with
no duplicate entry.
Example: >>> a = {1,2,2,3,3,3}
>>> a
Output: {1,2,3}
4) Mapping: This data type is unordered. Dictionaries fall under
Mappings. Dictionary is an unordered collection of key-value
pairs. It is generally used when we have a huge amount of data.
Dictionaries are optimized for retrieving data. In Python,
dictionaries are defined within braces {} with each item being a
pair in the form key: value. Key and value can be of any type.
Example: d = {‘key’:'Ajay',‘value':2}
Lists

• List is a sequence of values of any type. Values in the list


are called elements / items. A list is created by enclosing
the elements in square brackets[], separated by commas.
• It can have any number of items and they may be of
different types (integer, float, string etc.).
Ex: age = [15,12,18] #list of integers
student_height_weight = ["Ansh", 5.7, 60] #list with mixed
data types
student marks = ["Aditya", "10-A", [ "english",75]] # nested
list
Accessing List elements
• A list is made up of various elements which need to be individually
accessed on the basis of the application it is used for. There are
two ways to access an individual element of a list:
1) List Index or Positive Indexing
2) Negative Indexing
• List Index : A list index is the position at which any element is
present in the list. Index in the list starts from 0, so if a list has 5
elements the index will start from 0 and go on till 4. In order to
access an element in a list we need to use index operator [].
• 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.
Task Sample Code Output

Accessing Using List my_list = ['p','y','t','h','o','n'] p


Index print(my_list[0]) e
print(my_list[4])
my_list = ['p','y','t','h','o','n']
print(my_list[4.0]) Error!
Accessing Value in a n_list = [“Happy”,[2,0,1,5]] A
nested list print(n_list[0][1]) 5
print(n_list[1][3])
Accessing using day = ['f','r','i','d','a','y'] y
Negative Index print(day[-1]) f
print(day[-6])
List - methods
• append() - Elements can be added to the List by using built-in
append() function. Only one element at a time can be added
to the list by using append() method, for addition of multiple
elements with the append() method, loops are used. Tuples
can also be added to the List with the use of append method
because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of append() method.
• insert() - addition of element at the desired position. Unlike
append() which takes only one argument, insert() method
requires two arguments(position, value).
• extend() - used to add multiple elements at the same time at
the end of the list.
• Removing Elements from a List
– remove () method - The remove() method removes the
specified item one at a time. An error arises if element doesn't
exist in the set. Remove() method. To remove range of
elements, iterator is used.
• remove method in List will only remove the first occurrence of the
searched element.
– pop() method - Pop() function can also be used to remove and
return an element from the set, but by default it removes only
the last element of the set, to remove an element from a
specific position of the List, index of the element is passed as
an argument to the pop() method.
• Slicing of a List
– Used to print a range of elements from the list, we use slice
operation. Slice operation is performed on Lists with the use of
colon(:).
– To print elements
• from beginning to a range use [:Index]
• from end use [:-Index]
• from specific Index till the end use [Index:]
• within a range, use [Start Index: End Index]
• To print whole List with the use of slicing operation, use [:]
• To print whole List in reverse order, use [::-1].
Tuples
• Tuple is a collection of Python objects which is ordered and
unchangeable. The sequence of values stored in a tuple can be of
any type, and they are indexed by integers. Tuples are created by
placing sequence of values separated by ‘comma’ with or without
the use of parentheses for grouping of data sequence. It can
contain any number of elements and of any datatype (like strings,
integers, list, etc.).
• Example : fruits = ("apple", "banana", "cherry")
• Tuple1 = ('Artificial', 'Intelligence') #Creating a Tuple with the
use of string
• Tuple1 = (5, 'Artificial', 7, 'Intelligence') #Creating a Tuple with
Mixed Datatype
Accessing of Tuples

• We can use the index operator [] to access an item in a


tuple where the index starts from 0. So, a tuple having 6
elements will have indices from 0 to 5. Trying to access
an element outside of tuple (for example, 6, 7,...) will raise
an IndexError. The index must be an integer; so, we
cannot use float or other types. This will result in
TypeError.
• Example :
fruits = ("apple", "banana", "cherry")
print(fruits[1])
• Deleting a Tuple
• Tuples are immutable and hence they do not allow
deletion of a part of it. Entire tuple gets deleted by the use
of del() method.
• Example
num = (0, 1, 2, 3, 4)
del num
If statement

• Syntax:
if <condition or expression>:
Body of If
else:
Body of else
• Decision making statements
• if statement
• if..else statements
• if-elif ladder
if...elif...else Statement
• Syntax
if <condition or expression>:
Body of if
elif <condition or expression>:
Body of elif
else:
Body of else

• The elif is short for else if. It allows us to check for multiple expressions. If
the condition for if is False, it checks the condition of the next elif block
and so on. The if block can have only one else block. But it can have
multiple elif blocks.
• If all the conditions are False, body of else is executed.
for loop

• Syntax
for val in sequence:
Body of for

• range()
– Syntax : range(begin, end, step)
– It is used to iterate over a sequence
of numbers.
while loop

• The while statement allows you to


repeatedly execute a block of statements
as long as a condition is true.
• Syntax :
while test_expression:
Body of while

You might also like