Python Fundamentals
Python Fundamentals
Python Fundamentals
By:
Manoj Jangra
(Digital Strategist & Analytics Consultant)
What is Python?
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
• 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
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.
You cannot edit the value of the str1 variable. Although you can reassign str1, let's discuss
this with examples:
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.
Print(name[0:3]): 'The'
Print(name[4:]): 'Avengers'
Print(name[5:9]): 'veng'
Print(name[::2]): 'TeAegr'
Python String Methods
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.
swapcase() - A swapcase method allows the user to swap the cases. E.g.
str1.rstrip([chars])
Str1.split(“delimiter”, num)
str1.ljust(width[, fillchar])
str1.ljust(15, "#")
'Mohit Raj######'
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
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
str1.join(seq)
2. Nothing as separator:
"".join(name)
'Mohitraj'
max() - The max function returns the max characters from string str according to
the ASCII value. Let's see some examples:
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.
In order to access a particular value of tuple, specify a position number, in brackets. Let's discuss with
an example.
Avengers[2]
'Thor'
Avengers[-1]
'hulk'
Slicing of tuple
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.
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
A list is a built-in data structure Python. It can contain heterogeneous values such as
integers, floats, strings, tuples, lists, and dictionaries.
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.
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
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
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.
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:
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")
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.
Avengers2 = ["Vision","sam"]
Avengers1.extend(Avengers2)
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'
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 (,).
If you want to delete the dictionary's items, use the following syntax:
del dict[key]
If you want to delete the entire dictionary, then use the following syntax:
dict[key] = new_value
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:
Adding an item to the dictionary is very simple; just specify a new key in the square
brackets along with the dictionary.
dict[new_key] = value
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.
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.
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()
dict.get(key, default=None)
dict.setdefault(key1, default=None)
Default -- if key1 is not found, then the message will be returned and added to the
dict.values()
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)
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.
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 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