Basics of Python Programming

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

Basics of

Python Programming
What is Python?
● Python is a popular programming language.
● Its implementation was started in December 1989 by Guido van
Rossum, and released in 1991.
● It is used for:
– web development (server-side),
– software development,
– mathematics,
– system scripting.
Python
● Python is Interpreted: Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is similar
to PERL and PHP.
● Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
● Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
● Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide range
of applications from simple text processing to WWW browsers to games.
Note
● The most recent major version of Python is Python 3, which we
shall be using. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
● Python program can be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such
as Thonny, Pycharm, Netbeans or Eclipse which are particularly
useful when managing larger collections of Python files.
Naming conventions for Python identifiers
● Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
● Starting an identifier with a single leading underscore indicates
that the identifier is private.
● Starting an identifier with two leading underscores indicates a
strong private identifier.
● If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
Python Variables
● Variables are containers for storing data values.
● Unlike other programming languages, Python has no command for declaring
a variable.
● A variable is created the moment you first assign a value to it.
● A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
● Rules for Python variables:
– A variable name must start with a letter or the underscore character
– A variable name cannot start with a number
– A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
– Variable names are case-sensitive (age, Age and AGE are three different variables)
Reserved Words
Input and output in Python
● print ("Hello World")
● print(x)
● print(x, end=" ")
● x=input('Enter value of X:')
Lines and Indentation
● Quotation in Python: Python accepts single ('), double (") and
triple (''' or """) quotes to denote string literals.
● Comments in Python: hash sign (#)
● Multiple Statements on a Single Line: The semicolon ( ; )
allows multiple statements on a single line.
● Multiple Statement Groups as Suites: Groups of individual
statements, which make a single code block are called suites in
Python, and starts with a header line.
● Assigning Values to Variables: Python variables do not need
explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable.
● Multiple Assignment: Python allows you to assign a single
value to several variables simultaneously. e.g.,
a=b=c=1 “OR”
a, b, c = 1, 2, "john"
Standard Data Types
● Python has five standard data types-
– Text Type: str
– Numeric Types: int, float, complex
– Sequence Types: list, tuple
– Mapping Type: dictionary
– Set Types: set, frozenset
Text Type: Python Strings
● Strings in Python are identified as a contiguous set of characters represented
in the quotation marks.
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
Numeric Types: Python Numbers
● Number data types store numeric values.
● Number objects are created when you assign a value to them.
● Python supports three different numerical types:
1. int (signed integers)
2. float (floating point real values)
3. complex (complex numbers)
Python Lists
● A list contains items separated by commas and enclosed within
square brackets ([ ]).
● To some extent, lists are similar to arrays in C.
● One of the differences between them is that all the items
belonging to a list can be of different data type.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Python Tuples
● A tuple is another sequence data type that is similar to the list.
● A tuple consists of a number of values separated by commas.
● Unlike lists, however, tuples are enclosed within parenthesis.
● The main difference between lists and tuples is- Lists are
enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.
● Tuples can be thought of as read-only lists.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
Python Dictionary
● Python's dictionaries are kind of hash-table type.
● They work like associative arrays or hashes and consist of key-
value pairs.
● A dictionary key can be almost any Python type, but are usually
numbers or strings.
● Values, on the other hand, can be any arbitrary Python object.
● Dictionaries are enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces ([ ]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
● del dict['Name'] # remove entry with key 'Name'
● dict.clear() # remove all entries in dict
● del dict # delete entire dictionary
Set
● A Set is an unordered collection data type that is iterable,
mutable, and has no duplicate elements.
● Python’s set class represents the mathematical notion of a set.
● The major advantage of using a set, as opposed to a list, is
that it has a highly optimized method for checking whether a
specific element is contained in the set.
● This is based on a data structure known as a hash table.
– normal_set = set(["a", "b","c"])
– # Same as {"a", "b","c"}
Frozen Sets
● Frozen set is just an immutable version of a Python set object.
While elements of a set can be modified at any time, elements
of frozen set remains the same after creation.
– frozen_set = frozenset(["e", "f", "g"])

● However there are two major pitfalls in Python sets:


– The set doesn’t maintain elements in any particular order.
– Only instances of immutable types can be added to a Python set.
Data Type Conversion
Types of Operator
● Python language supports the following types of operators-
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators
Let a = 10 and b = 21
● + –-----> a + b = 31
● - –-----> a – b = -11
● * –-----> a * b = 210
● / –-----> b / a = 2.1
● % –-----> b%a=1
● ** –-----> a**b = 10 to the power 21
● // –-----> 9//2 = 4 and 9.0//2.0 = 4.0
Python Comparison Operators
Python Assignment Operators
● =
● +=
● -=
● *=
● /=
● %=
● **=
● //=
Python Bitwise Operators
Python Logical Operators
Python Membership Operators
Python Identity Operators
Decision-making
● if Statement
● if...else Statements
● if...elif...else Statement
● Note: no stitch-case available in python
Loops
● While loop
● For loop
● Nested loop
While loop:
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
For loop

fruits = ['banana', 'apple','mango']


for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!")
● Note:
● The range( ) function: The built-in function range() is the right
function to iterate over a sequence of numbers.
● It generates an iterator of arithmetic progressions.
● >>> range(5)
● range(0, 5)
● >>> list(range(5))
● [0, 1, 2, 3, 4]
Loop Control Statements
Functions
● A function is a block of organized, reusable code that is used to
perform a single, related action.
● Functions provide better modularity for your application and a
high degree of code reusing.
● Python gives you many built-in functions like print(), etc. but you
can also create your own functions.
Simple rules to
define a function in Python
● Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
● Any input parameters or arguments should be placed within these
parentheses.
● The code block within every function starts with a colon (:) and is
indented.
● The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with no
arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Function Arguments
● Required arguments
● Keyword arguments
● Default arguments
● Variable-length arguments
Required Arguments
● Required arguments are the arguments passed to a function in
correct positional order.
Keyword Arguments
● When we use keyword arguments in a function call, the caller
identifies the arguments by the parameter name. e.g.,:
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return
printinfo( age=50, name="miki" )
Default Arguments
● A default argument is an argument that assumes a default value
if a value is not provided in the function call for that argument.
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
return
printinfo( age=50, name="miki" )printinfo( name="miki" )
Variable-length Arguments
● You may need to process a function for more arguments than
you specified while defining the function.
● These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default
arguments.
● An asterisk (*) is placed before the variable name that holds the
values of all nonkeyword variable arguments.
E.g. of Variable-length Arguments
def printinfo(*vartuple ):
print ("Output is: ")
for var in vartuple:
print (var)
return
printinfo( 10 )
printinfo( 70, 60, 50 )
lambda: The Anonymous Functions
● Lambda forms can take any number of arguments but return just
one value in the form of an expression.
● They cannot contain commands or multiple expressions.
● An anonymous function cannot be a direct call to print because
lambda requires an expression.
● Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.
● Although it appears that lambdas are a one-line version of a
function, they are not equivalent to inline statements in C or C++.
Syntax for lambda function:
lambda [arg1 [,arg2,.....argn]]:expression
● E.g.:
sum = lambda arg1, arg2: arg1 + arg2
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
Use of lambda() with filter()
● In python, filter() function takes another function and a list of
arguments.
● E.g:
li = [3,4,5,8,18,19,10,16,20]
finalList = list(filter(lambda x: (x%2==0) , li))
print(finalList)
Use of lambda() with map()
● In python, map() function takes another function and a list of
arguments.
● E.g:
li=[3,4,5,8,18,19,10,16,20]
finalList=list(map(lambda x: x*2 , li))
print(finalList)
Use of lambda() with reduce()
● In python, reduce() function takes another function and a list of
arguments.
● E.g:
from functools import reduce
li=[3,4,5,8,18,19,10,16,20]
sum = reduce ( (lambda x, y : x+y) , li)
print(sum)
Modules
● A module allows you to logically organize your Python code.
● Grouping related code into a module makes the code easier to
understand and use.
● Simply, a module is a file consisting of Python code.
● A module can define functions, classes and variables.
● A module can also include runnable code.
The import Statement
● import module1[, module2[,... moduleN]

● A module is loaded only once, regardless of the number of


times it is imported.
● This prevents the module execution from happening repeatedly,
if multiple imports occur.
The from...import Statement
● from modname import name1[, name2[, ... nameN]]

● For example, to import the function fibonacci from the module fib, use the following
statement-
def fib(n):
result = [ ]
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

>>> from fib import fib

>>> fib(100)

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Packages in Python
● A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules
and subpackages and sub-subpackages, and so on.

You might also like