Python Programming Basics Guide
Python Programming Basics Guide
Content
• Introduction to Python:
• The basic elements of Python,
• Objects
• Expressions and numerical Types,
• Variables and assignments,
• IDLE,
• Branching programs,
• Strings and Input,
• Iteration
• Structured Types, Mutability and Higher-order Functions:
• Tuples,
• Lists and Mutability,
• Cloning and Comprehension
• Strings,
• Tuples
• Dictionaries
Python
• Python is an object-oriented, high level language, interpreted,
dynamic and multipurpose programming language.
• Python is easy to learn yet powerful and versatile scripting
language.
• Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it.
• It is dynamically typed. (no need to declare variable with data
type).
• It is case sensitive.
• no curly braces used.
Python
• It can be used for
• Console application
• Desktop application
• Web application
• Mobile application
• Games
• Python is being used by many popular websites and applications:
• Google
• Youtube
• Instagram
• Firefox
• Dropbox
History of Python
• Python was conceptualized by Guido Van
Rossum in the late 1980s.
• Rossum published the first version of Python
code (0.9.0) in February 1991 at the CWI
(Centrum Wiskunde & Informatica) in the
Netherlands ,Amsterdam.
• Python is derived from ABC programming
language, which is a general-purpose
programming language that had been developed
at the CWI.
• Rossum chose the name "Python", since he was
a big fan of Monty Python's Flying Circus. Guido Van Rossum
• Python is now maintained by a core development
team at the institute, although Rossum still holds
a vital role in directing its progress.
Features of Python
• Easy to learn, easy to read and easy to maintain.
• Portable: It can run on various hardware platforms.
• Extendable: You can add low-level modules to the Python interpreter.
• Scalable: Python provides a good structure and support for large programs.
• Python has support for an interactive mode of testing and debugging.
• Python has a broad standard library cross-platform.
• Everything in Python is an object: variables, functions, even code.
• Python supports functional and structured programming methods as well as OOP.
• Python supports GUI applications
• Python supports automatic garbage collection.
• Python can be easily integrated with C, C++, and Java.
Basic elements of Python
• A Python Program, sometimes called a Script, is a sequence of
definitions and commands.
• These definitions are evaluated and the commands are executed by
the Python interpreter in something called the Shell.
• Typically, a new shell is created whenever execution of a program
begins.
• A Command, often called a Statement, instructs the interpreter to so
something.
• E.g., the statement print(“hello”) instructs the interpreter to call the
function print, which will output the string hello to the window
associated with the shell.
Objects, Expressions and Numerical Types
• Objects are the core things that python programs manipulate.
• Every Object has a type that defines the kinds of things that
programs can do with objects of that type.
• Objects and Operators can be combined to form Expressions.
Example : 3+2 denotes the object 5 of type int.
• A Datatype represents the type of data stored into a variable or
memory.
• The Datatypes which are already available in Python language are
called built-in datatypes.
• The Datatypes which can be created by the programmers are called
user-defined datatypes.
Keywords
• Python has a set of keywords that are reserved words that cannot
be used as variable names, function names, or any other
identifiers:
Data Types
• Built –in Datatypes:-
• None Type
• Numeric Type
• Sequences
• Sets
• Mappings
• None Type :
• It represents an object that does not contain any value.
• Maximum of only one ‘None’ object is provided.
• In Boolean expression, ‘None’ datatype represents ‘False’.
• Numeric Type :
• A numeric value is any representation of data which has a numeric value.
• Python identifies three types of numbers: int, float, complex
Data Types(1)
• Integer: Positive or negative whole numbers(without fractional part).E.g., -
57
• Float: Any real number with a floating point representation. E.g., 55.67
• Complex number: A number with a real and imaginary component
represented as x+yj. x and y are floats and j is -1(square root of -1 called
an imaginary number). E.g., -15.5j
• Boolean:-
• Data with one of two built-in values True or False. Notice that 'T' and 'F'
are capital. true and false are not valid booleans and Python will throw an
error for them.
• Sequence Type:-
• A sequence is an ordered collection of similar or different data types.
Python has the following built-in sequence data types: str, bytes,
bytearray, list,tuple,range
Data Types(2)
• String: A string value is a collection of one or more characters put in single,
double or triple quotes. E.g., str=“welcome”
• List : A list object is an ordered collection of one or more data items, not
necessarily of the same type, put in square brackets. E.g., lst=[4,5,6]
• Tuple: A Tuple object is an ordered collection of one or more data items, not
necessarily of the same type, put in parentheses. E.g., tpl=(7,8,4)
• Bytes : It represents a group of byte numbers just like an array does. A byte
number is any positive integer 0 to 255.
• E.g., arr=[7,8,9]
x=bytes(arr)
• Bytearray : similar to byte data type. The difference is that the byte array
cannot be modified but the bytearray type array can be modified.
• E.g., arr=[7,8,9]
x=bytearray(arr)
Data Types(3)
• Set :-
• It is an unordered collection of unique items. Set is defined by values
separated by comma inside braces { }. Items in a set are not ordered.
• E.g., a = {5,2,3,1,4}
• Mappings(Dictionary):-
• Dictionary is an unordered collection of key-value pairs.
• In Python, dictionaries are defined within braces {} with each item being a pair
in the form key:value.
• E.g., d = {1:'value','key':2}
Python Variables
• Variable is a name which is used to refer memory location. Variable
also known as identifier and used to hold value.
• In Python, we don't need to specify the type of variable because
Python is a type infer language and smart enough to get variable
type.
• Variable names can be a group of both letters and digits, but they
have to begin with a letter or an underscore.
• It is recommended to use lowercase letters for variable name. Rahul
and rahul both are two different variables.
• Note - Variable name should not be a keyword.
Declaring Variable and Assigning Values
• We don't need to declare explicitly variable in Python.
• When we assign any value to the variable that variable is declared
automatically.
• The equal (=) operator is used to assign value to a variable.
• Examples :
• a=10
• name=‘ravi’
• salary=12006.70
Declaring Variable and Assigning Values
• Multiple Assignment
• Python allows us to assign a value to multiple variables in a single statement
which is also known as multiple assignment.
• We can apply multiple assignments in two ways either by assigning a single value
to multiple variables or assigning multiple values to multiple variables.
1. Assigning single value to multiple variables
Eg: x=y=z=50
[Link] multiple values to multiple variables:
Eg: a,b,c=5,10,15
IDLE
• IDLE is Python’s Integrated Development and Learning
Environment.
• IDLE has the following features:
• Used for GUI Based Python.
• cross-platform: works mostly same on Windows,Unix,Mac OS X
• Python shell window with colorizing of code input, output, and
error messages
• multi-window text editor with multiple undo,smart indent, call tips,
auto completion.
• debugger with persistent breakpoints
• IDLE has two main window types, the Shell window and the Editor
window
Python Example
• A simple hello world example is given below. Write below code in a file and save
with .py extension. Python source file has .py extension.
• [Link]
• print("hello world by python!")
• Execute this example by using following command: Python3 [Link]
• Python Example using Interactive Shell
• Python interactive shell is used to test the code immediately and does not require
to write and save code in file.
• A simple python example is given below.
>>> a="Welcome To Python"
>>> print a
Welcome To Python
Python Comments
• Python supports two types of comments:
• 1) Single lined comment:
• In case user wants to specify a single line comment, then comment
must start with #.
• Eg:# This is single line comment.
2) Multi lined Comment:
• Multi lined comment can be given inside triple quotes.
• eg: ''''' This
Is
Multipline comment'''
Output
• To display output or results, python provides the print() function.
1. The print() Statement : When the print() function is called simply, it
means a blank line will be displayed.
2. The print(“string”) Statement: When string is passed to printf()
function, the string is displayed as it is.
Example : print(“hello”) / print (‘hello’)
3. The print(variables list) Statement:display the values of variables.
Example: a, b=2, 4
print(a,b) / print(a,b,sep=“,”)
4. The print(“string”, variables list) Statement: print() function is to
use strings along with variables.
Example : a=2
Input
• To accept input from keyboard, Python provides the input()
function. This function takes value from keyboard and return
it as a string.
• Examples :
1. Str=input() #no message
2. Str =input(‘Enter your name:’) #with message
3. Str=input(‘Enter a number:’) # can be converted into int
x=int(Str)
4. X=int(input(‘Enter a number:’)) #directly converted with input()
5. X=float(input(‘Enter a number:’))
Operators
• Arithmetic Operators
• Assignment Operators
• Relational (Comparison)Operators
• Logical Operators
• Bitwise Operators
• Identity Operators
• Membership Operators
Arithmetic Operators
• Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication, etc.
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
Assignment Operators
• Assignment operators are used to assign values to
variables. Operator Operation Example
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
Multiplication
*= a *= 4 # a = a * 4
Assignment
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
Bitwise Operators
• Bitwise operators act on operands as if they were strings of
binary digits. They operate bit by bit, hence the name.
Operator Meaning Example
True if the operands are not identical (do not refer to the
is not x is not True
same object)
Membership Operators
• In python, in and not in are the membership operators.
They are used to test whether a value or variable is found in
a sequence (string, list, tuple, set and dictionary).
Operator Meaning Example
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))
•# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
Python Strings Formatting Number Formatting Types
• Type
You can format numbers using the format specifier given below:
Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. Except it uses current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. Except switches to 'E' if the number is large.
% Percentage. Multiples by 100 and puts % at the end.
Python List
• Python list is a data structure which is used to store various
types of data.
• In Python, lists are mutable i.e., Python will not create a new list if
we modify an element of the list.
• It works as a container that holds other objects in a given order. We
can perform various operations like insertion and deletion on list.
• A list can be composed by storing a sequence of different type of
values separated by commas.
• Python list is enclosed between square([]) brackets and elements
are stored in the index basis with starting index 0.
Python List
• Syntax: <list_name>=[value1,value2,value3,...,valuen];
• Example: data=['abhinav',10,56.4,'a'];
• Access List: print data[0:2]
• Elements in List: print data[0:2]
Python List Operation
1. Adding Python List :
• In Python, lists can be added by using the concatenation
operator(+) to join two lists.
• Example: list1=[10,20]
list2=[30,40]
list3=list1+list2
print list3
• Output: [10, 20, 30, 40 ]
2. Replicating Python List : Replicating means repeating, It can be
performed by using '*' operator by a specific number of time.
• Example : list1=[10,20]
print list1*1
Python List Operation
3. Python List Slicing : A subpart of a list can be retrieved on the
basis of index. This subpart is known as list slice. This feature
allows us to get sub-list of specified start and end index.
• Example: list1=[1,2,4,5,7]
• print list1[0:2]
• Output: [1,2]
4. Python Updating lists : To update or change the value of particular
index of a list, assign the value to that particular index of the List.
• Example: data1=[5,10,15,20,25]
data1[2]="Multiple of 5"
print data1
• Output: [5, 10, 'Multiple of 5', 20, 25]
Python List Operation
5. Appending Python List: Python provides, append() method which
is used to append i.e., add an element at the end of the existing
elements.
• Example: list1=[10,"rahul",'z']
[Link](10.45)
• Example 2: plant={}
plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print plant
Accessing Python Dictionary
• A Dictionary values can be accessed by their keys only. It means, to
access dictionary elements we need to pass key, associated to the
value.
• Python Accessing Dictionary Element Syntax
<dictionary_name>[key]
</dictionary_name>
• Accessing Elements Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
print data1['Id'] -> 100
print data1['Name'] ->Suresh
Updating Python Dictionary Elements
• The item i.e., key-value pair can be updated. Updating means new
item can be added. The values can be modified.
• Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data1['Profession']='Manager'
data1['Salary']=15000
print data1
• Output : {'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name':
'Suresh'}
Deleting Python Dictionary Elements
• del statement is used for performing deletion operation.
• An item can be deleted from a dictionary using the key only.
• Delete Syntax
del <dictionary_name>[key]
</dictionary_name>
• Whole of the dictionary can also be deleted using the del statement.
• Example
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102] #single item
del data #whole dictionary
Python Dictionary Functions &
Methods
No Functions Description Example Output
1 len(dictionary) It returns number of items in a data={100:'Ram', 101:'Suraj‘} 3
dictionary. print len(data)