0% found this document useful (0 votes)
2 views78 pages

Introduction To Python

The document provides an introduction to Python, a high-level, interpreted programming language created by Guido van Rossum. It outlines the advantages of learning Python, its characteristics, applications, and basic syntax, including variable types and data structures like lists, tuples, and dictionaries. Additionally, it covers fundamental concepts such as identifiers, reserved words, and data type conversion.

Uploaded by

Jade Magdua
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views78 pages

Introduction To Python

The document provides an introduction to Python, a high-level, interpreted programming language created by Guido van Rossum. It outlines the advantages of learning Python, its characteristics, applications, and basic syntax, including variable types and data structures like lists, tuples, and dictionaries. Additionally, it covers fundamental concepts such as identifiers, reserved words, and data type conversion.

Uploaded by

Jade Magdua
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Applications Development

&
Emerging Technologies

Introduction to
Python

Subject: IT 320
Title: Applications Development & Emerging Technologies
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Introduction
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL). Python is named after a TV Show called ëMonty Pythonís Flying Circusí and not
after Python-the snake.
Python 3.0 was released in 2008. Although this version is supposed to be
backward incompatibles, later on many of its important features have been backported
to be compatible with version 2.7.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Why to Learn Python?


Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords frequently
where as other languages use punctuation, and it has fewer syntactical constructions
than other languages.
Python is a MUST for students and working professionals to become a great
Software Engineer specially when they are working in Web Development Domain.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Why to Learn Python?


The following are key advantages of learning 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.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Characteristics of Python
Following are important characteristics of python −

• It supports functional and structured programming methods as well as OOP.


• It can be used as a scripting language or can be compiled to byte-code for building
large applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Applications of Python
Python is one of the most widely used language over the web.

• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Applications of Python
• Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs than
shell scripting.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Python Identifiers


A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language. Thus, Manpower and
manpower are two different identifiers in Python. Here are 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.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Reserved Words


The following list shows the Python keywords. These are reserved words and
you cannot use them as constants or variables or any other identifier names. All the
Python keywords contain lowercase letters only.
and exec not with
as finally or yield
assert for pass is
break from print lambda
class global raise elif
continue if return else
def import try except
del in while
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Lines and Indentation


Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line indentation, which
is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount.
Thus, in Python all the continuous lines indented with the same number of
spaces would form a block.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Multi-Line Statements


Statements in Python typically end with a new line. Python, however, allows
the use of the line continuation character (\) to denote that the line should continue.
Example:
total = item_one + \
item_two + \
item_three

The statements contained within the [], {}, or () brackets do not need to use
the line continuation character.
Example:
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Quotation in Python


Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For
example, all the following are legal:

• word = 'word'
• sentence = "This is a sentence."
• paragraph = """This is a paragraph. It is
• made up of multiple lines and sentences."""
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Comments in Python


A hash sign (#) that is not inside a string literal is the beginning of a comment.
All characters after the #, up to the end of the physical line, are part of the comment and
the Python interpreter ignores them.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Syntax - Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on a single line given that no
statement starts a new code block.
Example:
import sys; x = 'foo'; [Link](x + '\n')
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types
Variables are nothing but reserved memory locations to store values. It means
that when you create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different
data types to the variables, you can store integers, decimals or characters in these
variables.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - 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. The
equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.
Example:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Multiple Assignment


Python allows you to assign a single value to several variables
simultaneously.
Example:
a=b=c=1
Here, an integer object is created with the value 1, and all the three variables
are assigned to the same memory location. You can also assign multiple objects to
multiple variables.

Example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a
and b respectively, and one string object with the value "john" is assigned to the variable
c.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Standard Data Types


The data stored in memory can be of many types. For example, a person's
age is stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.

Python has five standard data types:

• Numbers
• String
• List
• Tuple
• Dictionary
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Numbers


Number data types store numeric values. Number objects are created when you assign a value to
them.
Example:
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement.
Example:
del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement.
Example:
del var
del var_a, var_b
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Numbers


Python supports three different numerical types:

• int (signed integers)


• float (floating point real values)
• complex (complex numbers)
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Numbers


Here are some examples of numbers −

int float complex


10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Strings


Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows either pair of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator.
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
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Lists


Lists are the most versatile of Python's compound data types. 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.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Lists


Example:

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
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - 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 are − 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
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Dictionary


Python's dictionaries are kind of hash-table type. They work like associative
arrays or hashes found in Perl 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 ([]).
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Python Dictionary


Example:
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 ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types.
To convert between types, you simply use the type-names as a function. There are
several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.
[Link]. Function & Description
1 int(x [,base])
Converts x to an integer. The base specifies the base if x is a string.

2 float(x)
Converts x to a floating-point number.

3 complex(real [,imag])
Creates a complex number.

4 str(x)
Converts object x to a string representation.

5 repr(x)
Converts object x to an expression string.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Data Type Conversion


6 eval(str)
Evaluates a string and returns an object.

7 tuple(s)
Converts s to a tuple.

8 list(s)
Converts s to a list.

9 set(s)
Converts s to a set.

10 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Data Type Conversion


11 frozenset(s)
Converts s to a frozen set.

12 chr(x)
Converts an integer to a character.

13 unichr(x)
Converts an integer to a Unicode character.

14 ord(x)
Converts a single character to its integer value.

15 hex(x)
Converts an integer to a hexadecimal string.

16 oct(x)
Converts an integer to an octal string.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Variable Types - Data Type Conversion


11 frozenset(s)
Converts s to a frozen set.

12 chr(x)
Converts an integer to a character.

13 unichr(x)
Converts an integer to a Unicode character.

14 ord(x)
Converts a single character to its integer value.

15 hex(x)
Converts an integer to a hexadecimal string.

16 oct(x)
Converts an integer to an octal string.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators
Operators are the constructs, which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called the operands and + is
called the operator.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Types of Operator


Python language supports the following types of operators −

• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Arithmetic Operators


Assume variable a holds the value 10 and variable b holds the value 21, then:
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 31
- Subtraction Subtracts right hand operand from left hand operand. a – b = -11
* Multiplication Multiplies values on either side of the operator a * b = 210
/ Division Divides left hand operand by right hand operand b / a = 2.1
% Modulus Divides left hand operand by right hand operand and b % a = 1
returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the power 20
operators
// Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 =
result is the quotient in which the digits after the -4.0
decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity):
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Arithmetic Operators


These operators compare the values on either side of them and decide the relation among them.
They are also called Relational operators. Assume variable a holds the value 10 and variable b
holds the value 21, then:
Operator Description Example

== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.

!= If values of two operands are not equal, then condition becomes true. (a!= b) is true.

> If the value of left operand is greater than the value of right operand, then (a > b) is not true.
condition becomes true.

< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.

>= If the value of left operand is greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.

<= If the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, then condition becomes true.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Assignment Operators


Assume variable a holds the value 10 and variable b holds the value 21, then:
Operator Description Example

= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c

+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a

-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a

*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a

/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is
equivalent to c = c / a

%= Modulus It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
AND

**= Exponent Performs exponential (power) calculation on operators and assign value to the left c **= a is equivalent to c = c ** a
AND operand

//= Floor It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c //
Division
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Bitwise Operators


Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and
b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Python's built-in function bin() can be used to obtain binary representation of an integer
number.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Bitwise Operators


The following Bitwise operators are supported by Python language −
Operator Description Example
& Binary AND Operator copies a bit, to the result, if it exists in both (a & b) (means 0000 1100)
operands

| Binary OR It copies a bit, if it exists in either operand. (a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit, if it is set in one operand but not (a ^ b) = 49 (means 0011 0001)
both.

~ Binary Ones (~a ) = -61 (means 1100 0011 in 2's complement


Complement It is unary and has the effect of 'flipping' bits. form due to a signed binary number.

<< Binary Left Shift The left operand's value is moved left by the number a << 2 = 240 (means 1111 0000)
of bits specified by the right operand.

>> Binary Right Shift The left operand's value is moved right by the number a >> 2 = 15 (means 0000 1111)
of bits specified by the right operand.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Logical Operators


The following logical operators are supported by Python language. Assume variable a
holds True and variable b holds False then:
Operator Description Example
and Logical If both the operands are true then (a and b) is False.
AND condition becomes true.

or Logical OR If any of the two operands are non-zero (a or b) is True.


then condition becomes true.

not Logical NOT Used to reverse the logical state of its Not(a and b) is True.
operand.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples. There are two membership operators as explained below:
Operator Description Example
in Evaluates to true if it finds a variable in x in y, here in results in a 1 if x is a
the specified sequence and false member of sequence y.
otherwise.

not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if x
variable in the specified sequence and is not a member of sequence y.
false otherwise.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below:
Operator Description Example
is Evaluates to true if the variables on x is y, here is results in 1 if id(x)
either side of the operator point to the equals id(y).
same object and false otherwise.

is not Evaluates to false if the variables on x is not y, here is not results in 1 if


either side of the operator point to the id(x) is not equal to id(y).
same object and true otherwise.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Operators Precedence


The following table lists all operators from highest precedence to the lowest.
[Link]. Operator & Description
1 **
Exponentiation (raise to the power)

2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)

3 * / % //
Multiply, divide, modulo and floor division

4 +-
Addition and subtraction

5 >> <<
Right and left bitwise shift

6 &
Bitwise 'AND'

7 ^|
Bitwise exclusive `OR' and regular `OR'
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Basic Operators - Python Operators Precedence


The following table lists all operators from highest precedence to the lowest.
[Link]. Operator & Description
8 <= < > >=
Comparison operators

9 <> == !=
Equality operators

10 = %= /= //= -= += *= **=
Assignment operators

11 is is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Decision Making
Decision-making is the anticipation of conditions occurring during the
execution of a program and specified actions taken according to the conditions.
Decision structures evaluate multiple expressions, which produce TRUE or
FALSE as the outcome. You need to determine which action to take and which
statements to execute if the outcome is TRUE or FALSE otherwise.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Decision Making
Following is the general form of a typical decision making structure found in
most of the programming languages −
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Decision Making
Python programming language assumes any non-zero and non-null values as
TRUE, and any zero or null values as FALSE value.
Python programming language provides the following types of decision-
making statements.
[Link]. Statement & Description
1 if statements. An if statement consists of a boolean expression followed by one
or more statements.

2 if...else statements. An if statement can be followed by an optional else


statement, which executes when the boolean expression is FALSE.

3 nested if statements. You can use one if or else if statement inside


another if or else if statement(s).
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops
In general, statements are executed sequentially − The first statement in a
function is executed first, followed by the second, and so on. There may be a situation
when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow more
complicated execution paths.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops
A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement:
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops
Python programming language provides the following types of loops to handle
looping requirements.
[Link]. Loop Type & Description
1 while loop. Repeats a statement or group of statements while a given condition is
TRUE. It tests the condition before executing the loop body.

2 for loop. Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

3 nested loops. You can use one or more loop inside any another while, or for loop.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops - Loop Control Statements


The Loop control statements change the execution from its normal sequence.
When the execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
Python supports the following control statements.
[Link]. Control Statement & Description
1 break statement. Terminates the loop statement and transfers execution to the
statement immediately following the loop.

2 continue statement. Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.

3 pass statement. The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops - Iterator and Generator


Iterator is an object which allows a programmer to traverse through all the
elements of a collection, regardless of its specific implementation. In Python, an iterator
object implements two methods, iter() and next(). String, List or Tuple objects can be
used to create an Iterator.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops - Iterator and Generator


Example:
list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
[Link]() #you have to import sys module for this
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops - Iterator and Generator


A generator is a function that produces or yields a sequence of values using
yield method. When a generator function is called, it returns a generator object without
even beginning execution of the function. When the next() method is called for the first
time, the function starts executing until it reaches the yield statement, which returns the
yielded value. The yield keeps track i.e. remembers the last execution and the second
next() call continues from previous value.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Loops - Iterator and Generator


The following example defines a generator, which generates an iterator for all the Fibonacci numbers.
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object

while True:
try:
print (next(f), end=" ")
except StopIteration:
[Link]()
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

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.
As you already know, Python gives you many built-in functions like print(), etc.
but you can also create your own functions. These functions are called user-defined
functions.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Defining a Function


You can define functions to provide the required functionality. Here are simple
rules to define a function in PFunction blocks begin with the keyword def followed by the
function name and parentheses ( ( ) ).

• Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
• 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.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Defining a Function


Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Calling a Function


Defining a function gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt. Following is an example to
call the printme() function:
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Pass by Reference vs Value


All parameters (arguments) in the Python language are passed by reference.
It means if you change what a parameter refers to within a function, the change also
reflects back in the calling function. For example:
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Pass by Reference vs Value


Here, we are maintaining reference of the passed object and appending
values in the same object. Therefore, this would produce the following result:

Values inside the function before change: [10, 20, 30]


Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Pass by Reference vs Value


There is one more example where argument is being passed by reference
and the reference is being overwritten inside the called function.
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Pass by Reference vs Value


The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes nothing and finally
this would produce the following result −

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Pass by Reference vs Value


The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes nothing and finally
this would produce the following result −

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Function Arguments


You can call a function by using the following types of formal arguments:

• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Required Arguments


Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should match
exactly with the function definition.
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows:
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return

# Now you can call printme function


printme()
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Required Arguments


When the code is executed, it produces the following result −

Traceback (most recent call last):


File "[Link]", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Keyword Arguments


Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values with
parameters. You can also make keyword calls to the printme() function in the following
ways:
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme( str = "My string")
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Keyword Arguments


The following example gives a clearer picture. Note that the order of
parameters does not matter.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age = 50, name = "miki" )
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - 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. The following example gives an idea
on default arguments, it prints default age if it is not passed:
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - 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. Syntax
for a function with non-keyword variable arguments is given below:

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - 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. Syntax
for a function with non-keyword variable arguments is given below:

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Variable-length Arguments


# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)

for var in vartuple:


print (var)
return

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - The Anonymous Functions


These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword to create
small 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++, whose purpose is to stack allocation by
passing function, during invocation for performance reasons.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - The Anonymous Functions


Syntax
The syntax of lambda functions contains only a single statement, which is as follows:
lambda [arg1 [,arg2,.....argn]]:expression

Following is an example to show how lambda form of function works −

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2

# Now you can call sum as a function


print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - The return Statement


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. All the
examples given below are not returning any value. You can return a value from a function as
follows:
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total

# Now you can call sum function


total = sum( 10, 20 )
print ("Outside the function : ", total )
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Scope of Variables


All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python:
• Global variables
• Local variables
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Global vs. Local variables


Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared inside it
are brought into scope.
TRINIDAD MUNICIPAL COLLEGE
COLLEGE OF COMPUTER STUDIES

Functions - Global vs. Local variables


Following is a simple example:

total = 0 # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total

# Now you can call sum function


sum( 10, 20 )
print ("Outside the function global total : ", total )

You might also like