Python Fundamentals

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 91

Python Made Easy

By:

Manoj Jangra
(Digital Strategist & Analytics Consultant)
What is Python?

• Python is an open source, object-oriented, high-level powerful


programming language.
• Developed by Guido van Rossum in the early 1990s. Named
after Monty Python.
• Python runs on many Unix variants, on the Mac, and on
Windows 2000 and later.
• Available for download from http://www.python.org.
Features of Python
1. Easy to use,
2. Expressive language,
3. Interpreted language,
4. Cross platform language,
5. Free and open source,
6. Object-oriented language,
7. Extensible language,
8. Large standard library,
9. GUI programming,
10. Integrated.
Python Interpreter

• In interactive mode, type Python programs and the interpreter


displays the result:
• Type python into your terminal's command line
• After a short message, the >>> symbol will appear
• The above symbol signals the start of a Python interpreter's
command line.
• Python interpreter evaluates inputs (For example >>> 4*(6-2)
return 16)
Python Code Execution
Python’s traditional runtime execution model: source code you type is
translated to byte code, which is then run by the Python Virtual
Machine. Your code is automatically compiled, but then it is
interpreted.

Source code extension is .py


Byte code extension is .pyc (compiled python code)
History
• The name Python was selected from "Monty Python's Flying Circus" which was a
British sketch comedy series created by the comedy group Monty Python and
broadcast by the BBC from 1969 to 1974.
• Python was created in the early 1990s by Guido van Rossum at the National
Research Institute for Mathematics and Computer Science in Netherlands.
• Python was created as a successor of a language called ABC (All Basic Code) and
released publicly in1991. Guido remains Python's principal author, although it
includes many contributions from active user community.
• Between 1991 and 2001 there are several versions released, current stable
release is 3.2. In 2001 the Python Software Foundation (PSF) was formed, a non-
profit organization created specifically to own Python-related Intellectual Property.
Zope Corporation is a sponsoring member of the PSF.
• All most all Python releases are Open Source. To see the details of release
versions and licence agreement of Python www.python.org.
Python Is Easy to Use

A simple program written in C++, C, Java and Python. All program prints
"Hello world".

C++ Program :
#include <iostream>
int main()
{
std::cout << "Hello World" << std::endl;
return 0;
}
C Program

#include <stdio.h>
int main(int argc, char ** argv)
{
printf(“Hello, World!\n”);
}
Java Program

Public class Hello


{
public static void main(String argv[])
{
System.out.println(“Hello, World!”);
}
}
Python Program

print ( "Hello World")


Major uses of Python

• System utilities (system admin tools, command line programs).


• Web Development
• Graphical User Interfaces (Tkinter, gtk, Qt)
• Internet scripting
• Embedded scripting
• Database access and programming
• Game programming
• Rapid prototyping and development
• Distributed programming
Organizations Using Python
• Web Development : Yahoo Maps, Yahoo Groups, Google, Zope Corporation,
Ultraseek, Linux Weekly News, ElasticHosts Cloud Servers, Mojam.com, hunch,
Shopzilla, Movieplayer.it, Multiplayer.it.
• Games: Battlefield 2, Crystal Space, Star Trek Bridge Commander, The Temple
of Elemental Evil, Vampire: The Masquerade: Bloodlines, Civilization 4, QuArK
(Quake Army Knife)
• Graphics : Industrial Light & Magic, Walt Disney Feature Animation, HKS, Inc.
(ABAQUS/CAE), RoboFog, Caligari Corporation, Blender 3D, Jasc Software,
Paint Shop Pro.
• Financial : Altis Investment Management, ABN AMRO Bank, Treasury Systems,
Bellco Credit Union, Journyx Timesheet and Resource Management Software.
Organizations Using Python

• Science : National Weather Service, Radar Remote Sensing Group, Applied Maths,
Biosoft, The National Research Council of Canada, Los Alamos National Laboratory
(LANL) Theoretical Physics Division, AlphaGene, Inc., LLNL, NASA, Swedish
Meteorological and Hydrological Institute (SMHI), Environmental Systems Research
Institute (ESRI), Objexx Engineering, Nmag Computational Micromagnetics
• Electronic Design Automation: Ciranova, Productivity Design Tools, Object Domain,
Pardus, Red Hat, SGI, Inc., MCI Worldcom, Nokia,
• Education : University of California, Irvine, Smeal College of Business, The Pennsylvania
State University, New Zealand Digital Library, IT Certification Exam preparation,
SchoolTool,
• Business Software : Raven Bear Systems Corporation, Thawte Consulting, Advanced
Management Solutions Inc., IBM, Arakn<E9>, RealNetworks, dSPACE, Escom, The Tiny
Company, Nexedi, Piensa Technologies - Bufete Consultor de Mexico, Nektra, WuBook.
Comments in Python
A comment begins with a hash character(#).
Joining two lines
When you want to write a long code in a single line you can break the logical
line in two or more physical lines using backslash character(\).
Multiple Statements on a Single Line

You can write two separate statements into a single line using a semicolon (;)
character between two line.
Indentation
Python uses whitespace (spaces and tabs) to define program blocks whereas other
languages like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow
control. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all
statements within the block must be the indented same amount. In the following program,
the block statements have no indentation.
Python Coding Style
• Use 4 spaces per indentation and no tabs.
• Do not mix tabs and spaces. Tabs create confusion and it is recommended
to use only spaces.
• Maximum line length : 79 characters which help users with a small display.
• Use blank lines to separate top-level function and class definitions and
single blank line to separate methods definitions inside a class and larger
blocks of code inside functions.
• When possible, put inline comments (should be complete sentences).
• Use spaces around expressions and statements.
Python Reserve words:
Python Variable

A variable is a memory location where a programmer can store a value.


Example : roll_no, amount, name etc.
• Value is either string, numeric etc. Example : "Sara", 120, 25.36
• Variables are created when first assigned.
• Variables must be assigned before being referenced.
• The value stored in a variable can be accessed or updated later.
• No declaration required
• The type (string, int, float etc.) of the variable is determined by Python
• The interpreter allocates memory on the basis of the data type of a variable.
Python Variable Name Rules

• Must begin with a letter (a - z, A - B) or underscore (_)


• Other characters can be letters, numbers or _
• Case Sensitive
• Can be any (reasonable) length
• There are some reserved words which you cannot use as a
variable name because Python uses them for other things.
Python Assignment Statements

The assignment statement creates new variables and gives them


values.
Basic assignment statement in Python is:
Syntax:
<variable>=<expr>
Single Assignment
X=10

Multiple Assignment
x=y=z=1
x,y,z=1,2,”abcd”
Swap Variables

Python swap values in a single line and this applies to all objects in
python.

Syntax:
var1,var2=var2,var1

X=10
Y=20
X,Y=Y,X
Local & Global Variables
Global: Variables that are only referenced inside a function are implicitly global.
Local: If a variable is assigned a value anywhere within the function’s body, it’s assumed to be
a local unless explicitly declared as global. E.g.
var1 = "Python"
def func1():
var1 = "PHP"
print("In side func1() var1 = ",var1)
 
def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
You can use a global variable in other functions by declaring it as global keyword : Example:

def func1():
global var1
var1 = "PHP"
print("In side func1() var1 = ",var1)
 
def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
Python Data Type

• Numbers
• Integers
• Floating Point Numbers
• Complex Numbers
• Boolean (bool)
• Strings
• Tuples
• Lists
• Dictionaries
Python Arithmetic Operators
Python Comparison Operators
Python Logical Operators
Python Assignment Operators
Strings
A Python string is a sequence, which consists of zero or more characters. The string is an
immutable data structure, which means they cannot be changed. E.g.

string str1 = "Satyamev jayate",


then str1 will always remain "Satyamev jayate".

You cannot edit the value of the str1 variable. Although you can reassign str1, let's discuss
this with examples:

str1 = "satyamev jayate"


print(str1): 'satyamev jayate'

Print(id(str1)): 47173288
The Subscript Operator
The subscript operator is defined as square brackets []. It is used to access the elements of string, list
tuple, and so on. E.g.

<given string>[<index>]

The given string is the string you want to examine and the index is the position of the character you
want to obtain. E.g.
name = "The Avengers"
print(name[0]): 'T'

Print(len(name)): 12

Print(name[11]): 's'
Slicing for Substrings
In many situations, you might need a particular portion of strings such as the first three
characters of the string.
Python's subscript operator uses slicing. In slicing, colon : is used.

An integer value will appear on either side of the colon. E.g.

Print(name[0:3]): 'The'

Print(name[:6]): 'The Av'

Print(name[4:]): 'Avengers'

Print(name[5:9]): 'veng'

Print(name[::2]): 'TeAegr'
Python String Methods

count() - returns the number of occurrences of the substring substr in string


str1.
str1 = 'The Avengers'
str1.count("e"): 3
str1.count("e",5,12): 2

find() -The find() method is used to find out whether a string occurs in a
given string or its substrings.
str1 = "peace begins with a smile"
str1.find("with"):13
str1 = "what we think, we become"
str1.find("we"): 5
String Case Methods

lower() -The lower() method returns a string in which all case-based characters are
present in lowercase. E.g.
name = "Mohit RAJ1234"
name.lower() : 'mohit raj1234'

upper() -The upper method returns a copy of string str1, which contains all
uppercase characters. E.g.
name = "Hello jarvis"
name.upper(): 'HELLO JARVIS'

capitalize() -This method capitalizes the first letter of the returned string. E.g.
name = "the game"
name.capitalize(): 'The game'
String Case Methods

title() – The title() method returns a copy of the string in which the first character of
every word of the string is capitalized. E.g.

name = 'genesis of a new realm of possibility.'


name.title(): 'Genesis Of A New Realm Of Possibility.'

swapcase() - A swapcase method allows the user to swap the cases. E.g.

name = 'Genesis Of A New Realm Of Possibility.'


name.swapcase(): 'gENESIS oF a nEW rEALM oF pOSSIBILITY.'
String Strip Methods

The syntax for the method is given as follows:

str1.rstrip([chars])

str1 = "Dr Ambedkarn"


print(str1.rstrip("n")) : 'Dr Ambedkar'

str2 = " Baba Saheb "


print(str2.rstrip()): ' Baba Saheb'
String Split Methods

The syntax for the method is given as follows:

Str1.split(“delimiter”, num)

str1.split("-", 1): ['27', '12-2016']


str1 = "27-12-2016"

str1.split("-"): ['27', '12', '2016']


list1 = str1.split("-")
list1[2]: '2016'
String Justify Methods
The syntax for the method is given as follows:

str1.ljust(width[, fillchar])

str1= "Mohit Raj"


Strings

str1.ljust(15, "#")
'Mohit Raj######'

str2= "Bhaskar Narayan Das"


str2.ljust(15, "#")
'Bhaskar Narayan Das'
String Justify Methods

center() method:
str1= "Mohit Raj"
str1.center(16, "#")
'###Mohit Raj####'

str.zfill(width)
acc_no = "3214567987"
acc_no.zfill(15)
'000003214567987'

binary_num = "10101010"
binary_num.zfill(16)
'0000000010101010
String Justify Methods

replace() - The syntax for the method is as follows:

str.replace(old, new max)

tr1 = "time is great and time is money"


str1.replace("is","was")
'time was great and time was money'

str1
'time is great and time is money'
str1.replace("is",1)
str1.replace("is","was",1)
'time was great and time is money'
String Justify Methods

join() -The syntax for the method is:

str1.join(seq)

1. The space as the separator:


name = ["Mohit","raj"]
" ".join(name)
'Mohit raj'

2. Nothing as separator:
"".join(name)
'Mohitraj'

3. A hyphen - as the separator:


"-".join(name)
'Mohit-raj'
String Functions
min() -The min() function returns the min character from string str1 according to
the ASCII value:

str1 = "Life should be great rather than long"


print(min(str1)): ' '
str2 = "hello!"
print(min(str2)): '!'

max() - The max function returns the max characters from string str according to
the ASCII value. Let's see some examples:

str1 = "Life should be great rather than long"


print(max(str1)): 'u'
String Functions

str() -This function converts an argument value to string type. The argument
value can be any type.
a = 123
type(a)
type 'int'>
str(a)
'123'

list1 = [1,2]
type(list1)
<type 'list'>
str(list1)
'[1, 2]'
Tuple

Tuple - Tuple is a sequence, which can store heterogeneous data types such as integers,
floats, strings, lists, and dictionaries.

Like strings, tuple is immutable.

Creating an empty tuple


<variable –name > = ()
Tup1 = ()
The empty tuple is written as two parentheses containing nothing.

Creating tuple with elements


To create a tuple, fill the values in tuple separated by commas:
tup1 = (1,2,3,4.6, "hello", "a")
Indexing Tuple

In order to access a particular value of tuple, specify a position number, in brackets. Let's discuss with
an example.

Avengers = ("iron-man", "vision", "Thor", "hulk")


Avengers[0]
'iron-man'

Avengers[2]
'Thor'

Avengers[-1]
'hulk'
Slicing of tuple

Consider the following example:


Avengers[1:3]
('vision', 'Thor')

Avengers[:3]
('iron-man', 'vision', 'Thor')

Avengers[1:]
('vision', 'Thor', 'hulk')

Avengers[5:6]

Avengers[-3:-2]
('vision',)
Tuple functions

len() - The len() function returns the length of the tuple, which means the total number
of elements in a tuple.

tup1 = ("C", "Python", "java","html")


len(tup1): 4

max() - The max(tuple) function returns the element of tuple with the maximum value.

t2 = (1,2,3,4,510)
max(t2): 510

min() – The min() function returns the element of tuple with a minimum value.
tup1 = (1,2,3,4,"1")
min(tup1): 1
Operations of Tuples

By using the + operator, two tuples can be added as shown:


avenger1 = ("Iron-man", "captain", "Thor")
avenger2 = ("Vision", "Sam")
avenger1 + avenger2
('Iron-man', 'captain', 'Thor', 'Vision', 'Sam')

By using the * operator, you can perform multiplication:


language = ("Python","html")
language*2
('Python', 'html', 'Python', 'html')
Lists

In the real world, we often make lists, such as -


• daily to-do lists, a list of players of the Cricket team,
• a guest list for a wedding, lists of food, and so on.

A list is a built-in data structure Python. It can contain heterogeneous values such as
integers, floats, strings, tuples, lists, and dictionaries.

Characteristics of a Python list:


• Values are ordered
• Mutable (can be changed)
• A list can hold any number of values
• A list can add, remove, and alter the values
Creating A List

Creating empty list:


<Variable name > = []
List1 = []

Creating a list with values:


Avengers = [‘Hulk', ‘Iron-man', 'Captain', 'Thor']
DailyItems=[“Banana”, “Mango”, “Rice”, “Tea”]
Emp_id=[1,2,3,4,5,6,78,9]
Emp_name=[“Anil”, “Anuj”, “Himani”, “Shivam”]
List Operations

1. Accessing list values


Avengers = ['hulk', 'iron-man', 'Captain', 'Thor']
Avengers[0]
'hulk

2. Slicing the list


Syntax:
<list-name>[start : stop : step]
Avengers[1:3]
['iron-man', 'Captain']
Other range examples:
Avengers[:4] , Avengers[:] , Avengers[2:] , list1[1:13:3]
Updating the list

Lists are mutable, so the values of a list can be updated.

Avengers = ['hulk', 'iron-man', 'Captain', 'Thor']

Updating Captain to Captain-America

Avengers[2] = "Captain-America"
Print(Avengers)
Deleting values from a list

By using the del keyword, you can delete a value or a slice of list from the list. E.g.

C_W_team = ['hulk', 'iron-man', 'Captain-America', 'Thor',"Vision"]

del C_W_team[0]

Print(C_W_team)
['iron-man', 'Captain-America', 'Thor', 'Vision']

del C_W_team[2:4]

Print (C_W_team)
['iron-man', 'Captain-America']
Addition of Lists

You can add two lists by using the + operator.

Avengers1 = ['hulk', 'iron-man', 'Captain-America', 'Thor']

Avengers2 = ["Vision","sam"]

Avengers1+Avengers2
['hulk', 'iron-man', 'Captain-America', 'Thor', 'Vision', 'sam']

Avengers2+Avengers1
['Vision', 'sam', 'hulk', 'iron-man', 'Captain-America', 'Thor']
Multiplication of Lists

By using the * operator, you can perform multiplication of Python lists,


as shown in the following example:

Av = ['Vision', 'sam']
new_Av = Av*2

new_Av
['Vision', 'sam', 'Vision', 'sam']
In Operator

You can use the in operator on list with the if statement. E.g.

Avengers= ['hulk', 'iron-man', 'Captain-America', 'Thor']


if "iron-man" in Avengers:
print "yes "
yes

if "vision" in Avengers:
print "yes "
List Functions

len() - The len() function returns the number of elements or values in the list, as shown in the following
example:

avengers = ['hulk', 'iron-man', 'Captain-America', 'Thor']


len(avengers): 4

max () - The max (list) function returns the element of the list with the maximum value:
list1 = [1, 2, 3, 4,510]
max (list1): 510

list () -The list function converts the sequence into a list. Let's see the following example:
tup1 = ("a","b","c")
list (tup1): ['a', 'b', 'c']

sorted () -The sorted () function returns a new sorted list from the values in iterable. See the
following example:
list1 = [2, 3, 0, 3, 1, 4, 7, 1]
sorted (list1): [0, 1, 1, 2, 3, 3, 4, 7]
List Methods

append () -The method adds a value at the end of the list. Let's see the
following example:

Avengers = []

Avengers.append("Captain-America")

Avengers.append("Iron-man")

Avengers: ['Captain-America', 'Iron-man']


List Methods

extend () - Consider a situation where you want to add a list to an existing list. For example, we
have two lists of our heroes:
Avengers1 = ['hulk', 'iron-man', 'Captain-America', 'Thor']
Avengers2 = ["Vision","sam"]

We want to add the Avengers2 list to the Avengers1 list. If you are thinking about the +operator, you
might be right to some extent but not completely because the + operator just shows the addition but
doesn't change the original lists.

Avengers1 = ['hulk', 'iron-man', 'Captain-America', 'Thor']

Avengers2 = ["Vision","sam"]

Avengers1.extend(Avengers2)

Avengers1 ['hulk', 'iron-man', 'Captain-America', 'Thor', 'Vision', 'sam']

Avengers2 ['Vision', 'sam']


Difference B/W Append & Extend
Linux = ["kali", "Ubuntu", "debian"]
Linux2 = ["RHEL", "Centos"]
Linux.extend(Linux2)
Linux
['kali', 'Ubuntu', 'debian', 'RHEL', 'Centos']

Linux = ["kali", "Ubuntu", "debian"]


Linux2 = ["RHEL", "Centos"]
Linux.append(Linux2)
Linux

['kali', 'Ubuntu', 'debian', ['RHEL', 'Centos']]


List Methods

count () – C. Method is used to find the occurrence of an item in a list. E.g.


list1 = ["a","c","b","c","a","h","l", 1, 2, 3, 4]
list1.count ("a"): 2
index () - I.Method is used to find the index of a particular item in a list. E.g.
consider the following code snippet:
OS = ['kali', 'Ubuntu', 'debian', 'RHEL', 'Centos']
OS.index("debian"): 2
insert() - I.Method is used to insert needed items. The item is the value to be
inserted into list1:
A = [‘iron-man', 'hulk', 'Thor']
A.insert (0,"Captain-America")
A
['Captain-America', 'iron-man', 'hulk', 'Thor']
List Methods

remove() - R.Method is used to remove an item from a list. E.g.


Avengers1 = ["Iron-man","Thor","Loki","hulk"]
Avengers1.remove ("Loki")
print(Avengers1): ['Iron-man', 'Thor', 'hulk']

pop() – P.Method removes and returns the last item from the list. E.g.
GoT = ["Tyrion","Sansa", "Arya","Joffrey","Ned-Stark"]
GoT.pop()
'Ned-Stark'
GoT.pop(): 'Joffrey'

reverse() – R.Method reverses the items of a list. E.g.


av = ['hulk', 'iron-man', 'Captain-America', 'Thor', 'vision', 'Clint']
av.reverse()
av:['Clint', 'vision', 'Thor', 'Captain-America', 'iron-man', 'hulk']
Dictionary

A Dictionary is a sequence of key-value, or item, pairs separated by commas.

Dictionary_name = {key: value}

The key-value pair is called an item. The key and value are separated by a colon (:),
and each item is separated by a comma (,).

The items are enclosed by curly braces ({ }).

An empty dictionary can be created just by using curly braces ({ }).

port = {22: "SSH", 23: "Telnet" , 53: "DNS", 80: "HTTP" }


companies = {"IBM": "International Business Machines", "L&T" :"Larsen & Toubro"}
Dictionary
Key features of the dictionary are:

• The key of the dictionary can not be changed


• A string, int, or float can be used as a key
• A tuple that does not contain any list can be used as a key
•Keys are unique
• Values can be anything, for example, list, string, int, and so on
• Values can be repeated
• Values can be changed
• A dictionary is an unordered collection, which means that the order in which you have
entered the items in a dictionary may not be retained and you may get the items in a
different order
Operations on the Dictionary

Accessing the values of dictionary

Port = {80: “HTTP”, 23 : “Telnet”, 443 : “HTTPS”}

Let's learn by example:

port = {80: "HTTP", 23 : "Telnet", 443 : "HTTPS"}


port[80]
'HTTP'
port[443]
'HTTPS
Deleting an item from the dictionary
By using the del keyword, you can delete the entire dictionary or the dictionary's items.

If you want to delete the dictionary's items, use the following syntax:

del dict[key]

Considering the following code snippet for example:

port = {80: "HTTP", 23 : "Telnet", 443 : "HTTPS"}


del port[23]
port
{80: 'HTTP', 443: 'HTTPS'}

If you want to delete the entire dictionary, then use the following syntax:

The del dict


Updating Dictionary Values
Updating the dictionary is pretty simple; just specify the key in the square bracket along with the
dictionary name.

The syntax is as follows:

dict[key] = new_value

Consider the following example:


port = {80: "HTTP", 23 : "SMTP”, 443 : "HTTPS"}

In the preceding dictionary, the value of port 23 is "SMTP", but in reality, port number 23 is
for telnet protocol. Let's update the preceding dictionary with the following code:

port = {80: "HTTP", 23 : "SMTP", 443 : "HTTPS"}


port
{80: 'HTTP', 443: 'HTTPS', 23: 'SMTP'}
port[23] = "Telnet"
port
{80: 'HTTP', 443: 'HTTPS', 23: 'Telnet'}
Adding Item to the Dictionary

Adding an item to the dictionary is very simple; just specify a new key in the square
brackets along with the dictionary.

The syntax is as follows:

dict[new_key] = value

Consider the following example:

port = {80: "HTTP", 23 : "Telnet"}


port[110]="POP"
port
{80: 'HTTP', 110: 'POP', 23: 'Telnet'}
Dictionary Functions
len() - In order to find the number of items that are present in a
dictionary, you can use the len() function. E.g.
port = {80: "http", 443: "https", 23:"telnet"}
len(port): 3

str() - The str() function converts a dictionary into a string. E.g.

port = {80: "http", 443: "https", 23:"telnet"}


port
{80: 'http', 443: 'https', 23: 'telnet'}
str(port): "{80: 'http', 443: 'https', 23: 'telnet'}"
Dictionary Functions

max() - If you pass a dictionary to the max() function, then it returns the key with the
maximum
worth. E.g.
dict1 = {1:"abc",5:"hj", 43:"Dhoni", ("a","b"):"game", "hj":56}
max(dict1): ('a', 'b')

min() - The min() function is just opposite to the max() function. It returns the dictionary's
key with the lowest worth. E.g.

dict1 = {1:"abc",5:"hj", 43:"Dhoni", ("a","b"):"game", "hj":56,(1,3):"kl"}


dict1
{1: 'abc', (1, 3): 'kl', 5: 'hj', 43: 'Dhoni', 'hj': 56, ('a', 'b'):
'game'}
min(dict1)
Dictionary Functions

dict() - You can pass a tuple or list to the dict() function, but that tuple or list contain elements as pairs of
two values, as shown in the next example.

The syntax of the method is as follows:


dict(list or tuple)

port = [[80,"http"],[20,"ftp"],[23,"telnet"],[443,"https"],[53,"DNS"]]
port
[[80, 'http'], [20, 'ftp'], [23, 'telnet'], [443, 'https'], [53, 'DNS']]
dict(port)
{80: 'http', 443: 'https', 20: 'ftp', 53: 'DNS', 23: 'telnet'}
port = [(80,"http"),(20,"ftp"),(23,"telnet"),(443,"https"),(53,"DNS")]
dict(port)
{80: 'http', 443: 'https', 20: 'ftp', 53: 'DNS', 23: 'telnet'}
Dictionary Methods
copy() - The syntax of the copy() method is as follows:

dict.copy()

Avengers ={'iron-man':"Tony", "CA":"Steve","BW":"Natasha"}


Avengers
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
Avengers2 = Avengers.copy()
Avengers2
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha'}
Dictionary Methods
get() – The get() method is used to get the value of a given key from the dictionary. If key is
not found, then the default value or message will return. See the following example, where
key is present:

The syntax of the get() method is as follows:

dict.get(key, default=None)

A1 = {'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk':'Bruce-Banner'}


A1.get('iron-man',"not found")
'Tony'
In the preceding example, since the key is found, the custom message, not found, does not
get printed. Let's see another example:
A1.get('panther',"not found")
'not found'
A1.get("Black")
Dictionary Methods
setdefault() - The syntax of setdefault() is as follows:

dict.setdefault(key1, default=None)

key1 -- This is key to be searched.

Default -- if key1 is not found, then the message will be returned and added to the

dictionary. Let's see the following example:


port1.setdefault(23, "Unknown")
'Telnet'
port1
{80: 'http', 22: 'SSH', 23: 'Telnet'}
port1.setdefault(19, "Unknown")
'Unknown'
port1
{80: 'http', 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}
Dictionary Methods
• has_key() - The syntax for has_key() is given as:
dict.has_key(key)
key--this is the key to be searched in the dictionary, dict. The has_key() method
returns True or False, as shown in the following example:
>>> port1 = {80: 'http', 18: None, 19: 'Unknown', 22: 'SSH', 23: 'Telnet'}
>>> port1.has_key(80)
True
>>>
>>> port1.has_key(20)
False
>>>
Consider a situation where you want to do some operation on a dictionary's keys and want
to get all the keys in different lists. In this situation, you can use the keys() method.

• keys() - The syntax of keys() is as follows:


dict.keys()

Let's consider the following example:


A1 = {'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk': 'BruceBanner'}
In the preceding dictionary, we want the superhero's characters, that is, all the keys:
>>> A1 = {'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk':
'Bruce-Banner'}
>>> A1.keys()
['iron-man', 'CA', 'BW', 'hulk']
Dictionary Methods

values() - The syntax of values() is as follows:

dict.values()

Let's consider the following example:

A1 = {'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk': 'BruceBanner'}

In the preceding dictionary, we want to get all the real names of our heroes:1 =
{'iron-man': 'Tony', 'CA': 'Steve', 'BW': 'Natasha', 'hulk':
'Bruce-Banner'}
A1.values()
['Tony', 'Steve', 'Natasha', 'Bruce-Banner']
Dictionary Methods
update() - The syntax is given as:

dict.update(dict2)

dict2--this is the dictionary to be added.

Consider the following example:

port1 = {22: "SSH", 23: "telnet", 80: "Http" }


port2 = {53 :"DNS", 443 : "https"}
port1.update(port2)
port1
{80: 'Http', 443: 'https', 53: 'DNS', 22: 'SSH', 23: 'telnet'}
Dictionary Methods
items() - The syntax of the items() method is as follows:
dict.items()

The items() method returns the list of dictionary's (key, value) tuple pairs:
dict1 = d={1:'one',2:'two',3:'three'}
dict1.items()
[(1, 'one'), (2, 'two'), (3, 'three')]

Sometimes, we need to delete all the items of a dictionary. This can be done by using the clear() method.

clear() - The syntax of clear() is as follows:


dict.clear()

Let's consider the following example:


dict1={1:'one',2:'two',3:'three'}
dict1
{1: 'one', 2: 'two', 3: 'three'}
dict1.clear()
dict1
if statement

The Python if statement is same as it is with other programming


languages. It executes a set of statements conditionally, based on the
value of a logical expression.
Here is the general form of a one way if statement.
• Syntax:
if expression :
statement_1
statement_2
....
if .. else statement

In Python if .. else statement, if has two blocks, one following the expression and other
following the else clause. Here is the syntax.
Syntax:
if expression :
statement_1
statement_2
....
else :
statement_3
statement_4
....
if .. elif .. else statement

Sometimes a situation arises when there are several conditions. To handle the situation
Python allows adding any number of elif clause after an if and before an else clause. Here
is the syntax.
Syntax:
if expression1 :
statement_1
statement_2
....
elif expression2 :
statement_3
statement_4
....
else :
statement_7
statement_8
Nested if .. else statement
In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to true or
not. If a true condition is found the statement(s) block associated with the condition executes
otherwise it goes to next condition. Here is the syntax :
Syntax:
if expression1 :
if expression2 :
statement_3
statement_4
....
else :
statement_5
statement_6
....
else :
statement_7
statement_8
for loop

In Python for loop is used to iterate over the items of any sequence
including the Python list, string, tuple etc. The for loop is also used to
access elements from a container (for example list, string, tuple) using
built-in function range().
• Syntax:
for variable_name in sequence :
statement_1
statement_2
....
• >>> #The list has four elements, indices start at 0 and end at 3
• >>> color_list = ["Red", "Blue", "Green", "Black"]
• >>> for c in color_list:
• print(c)

• Red
• Blue
• Green
• Black
Python for loop and range() function

The range() function returns a list of consecutive integers. The function


has one, two or three parameters where last two parameters are range(a),
range(a,b), range(a,b,c)
optional. It is widely used in for loops. Here is the syntax.

• for a in range(4): print(a) 0, 1,2,3,4


• for a in range(2,7): print(a) 2 3 4 5 6
• for a in range(2,19,5): print(a) 2,7,12 ,17
While loop

The basic loop structure in Python is while loop. Here is the syntax.
Syntax:
while (expression) :
    statement_1 
    statement_2
    ....
The while loop runs as long as the expression (condition) evaluates to True
and execute the program block. The condition is checked every time at the
beginning of the loop and the first time when the expression evaluates to
False, the loop stops without executing any remaining statement(s). The
following example prints the digits 0 to 4 as we set the condition x < 5.
break, continue statement

• he break statement is used to exit a for or a while loop. The purpose of this statement
is to end the execution of the loop (for or while) immediately and the program control
goes to the statement after the last statement of the loop. If there is an optional else
statement in while or for loop it skips the optional clause also. Here is the syntax.
• Syntax:
• while (expression1) :
• statement_1
• statement_2
• ......
• if expression2 :
• break
Example: break in for loop
• numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
• num_sum = 0
• count = 0
• for x in numbers:
• num_sum = num_sum + x
• count = count + 1
• if count == 5:
• break
• print("Sum of first ",count,"integers is: ", num_sum)
Example: break in while loop

• 
• num_sum = 0
• count = 0
• while(count<10):
• num_sum = num_sum + count
• count = count + 1
• if count== 5:
• break
• print("Sum of first ",count,"integers is: ", num_sum)
continue statement

• The continue statement is used in a while or for loop to take the


control to the top of the loop without executing the rest statements
inside the loop. Here is a simple example.
• for x in range(7):
• if (x == 3 or x==6):
• continue
• print(x)

You might also like