Nothing Special   »   [go: up one dir, main page]

Python Book

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

Priti Patel

Department of Computer Applications


Python
 Python is a popular programming language. It was
created by Guido van Rossum, and released in 1991.
 It is used for:
 web development (server-side),
 software development,
 mathematics,
 system scripting.
Python
 Programmer friendly language.
 General purpose language.[you can create any type of
application]
 Simple and easy to understand
 Less code / concise code
 All rounder language[functional,object-
oriented,scripting]
 Freeware and Open-source
Python
 High level Programming Language
 Platform-Independent
 Portable
 Dynamically Typed Language
 Interpreted
 Extensible
 Embedded
 Extensive Library
Why Python?
 Python is a cross-platform programming language, which
means that it can run on multiple platforms like Windows,
macOS, Linux, Raspberry Pi, etc.
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
 Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
 Python can be treated in a procedural way, an object-
oriented way or a functional way.
 Dynamically typed language.
 Python language is being used by almost all tech-giant
companies like – Google, Amazon, Facebook, Instagram,
Dropbox, Uber… etc.
Python Syntax compared to other programming
languages

 Python was designed for readability, and has some


similarities to the English language with influence
from mathematics.
 Python uses new lines to complete a command, as
opposed to other programming languages which often
use semicolons or parentheses.
 Python relies on indentation, using whitespace, to
define scope; such as the scope of loops, functions and
classes. Other programming languages often use curly-
brackets for this purpose.
Python Version

 There are two major Python versions: Python 2 and


Python 3. Both are quite different.
Thonny IDE.
 The easiest way to run Python is by using Thonny IDE.
 The Thonny IDE comes with the latest version of Python
bundled in it. So you don't have to install Python
separately.
 Follow the following steps to run Python on your computer.
 Download Thonny IDE.
 Run the installer to install Thonny on your computer.
 Go to: File > New. Then save the file with .py extension.
For example, hello.py, example.py, etc.
You can give any name to the file. However, the file name
should end with .py
 Write Python code in the file and save it.
Install Python Separately

 Download the latest version of Python.


 Run the installer file and follow the steps to install Python
During the install process, check Add Python to
environment variables. This will add Python to
environment variables, and you can run Python from any
part of the computer.

Also, you can choose the path where Python is installed.



Run Python in Immediate mode

 Once Python is installed, typing python in the


command line will invoke the interpreter in
immediate mode. We can directly type in Python code,
and press Enter to get the output.
 Try typing in 1 + 1 and press enter. We get 2 as the
output. This prompt can be used as a calculator. To exit
this mode, type quit() and press enter.
Run Python in the Integrated
Development Environment (IDE)
 when you install Python, an IDE named IDLE is also
installed. You can use it to run Python on your
computer. It's a decent IDE for beginners.
 When you open IDLE, an interactive Python Shell is
opened.
 Now you can create a new file and save it
with .py extension. For example, hello.py
 Write Python code in the file and save it. To run the
file, go to Run > Run Module or simply click F5.

Exercise
 Install Latest version of Python
Priti Patel
Department of Computer Applications
Flavors of Python
 CPython:
 The base of all these implementation is Cpython or
more formally known as python .It is a Python
compiler that was implemented in C language. Even
C++ code can be execute using CPython.
 JPython:
 It is enables Python implementation to be run on Java
platform. It runs on JVM.
 IronPython:
 It is compiler designed for .NET framework, but it is
written in C#. It can run on CLR(Common Language
Run time).
Flavors of Python
 PyPy:
 Pypy is actually bit different than other implementations its primary
focus is to overcome drawbacks(so called) of python. It is a Python
interpreter and just-in-time compiler. It is written in Python itself.
 In Python, the source code (or .py) is first compiled into a much
simpler form called bytecode (or .pyc). This byte code can be
interpreted (official CPython), or JIT-compiled (PyPy).
 Ruby Python:
 It acts as a bridge from Ruby to Python interpreter. It embeds the
Python interpreter inside the Ruby application
 Pythonxy:
 It is written in the form of Python(X,Y). It is designed by adding
scientific and engineering related packages.
 Anaconda Python:
 The name Anaconda Python is obtained after redeveloping it to handle
large scale data processing, predictive analytics and scientific
computing. It handles huge amount of data.
Flavors of Python
 Stackless Python:
 Tasklets are the small tasks that are run independently.
The communication is done with each by using
channels. They schedule, control and suspend the
tasklets. Hundreds of tasklets can run by a thread. The
thread and tasklets can be created in stackless python.
It is a re-implementation of python.
Drawbacks of Python
 Speed
 Python is slower than C or C++. But of
course, Python is a high-level language, unlike C or
C++ it's not closer to hardware.
 Mobile Development
 Python is not a very good language for mobile
development . It is seen as a weak language for
mobile computing. This is the reason very few mobile
applications are built in it like Carbonnelle.
 Memory Consumption
 Python is not a good choice for memory
intensive tasks. Due to the flexibility of the data-
types, Python's memory consumption is also high.
Drawbacks of Python
 Database Access
 Python has limitations with database access . As
compared to the popular technologies like JDBC and
ODBC, the Python's database access layer is found to
be bit underdeveloped and primitive . However, it
cannot be applied in the enterprises that need smooth
interaction of complex legacy data .
 Runtime Errors
 Python programmers cited several issues with
the design of the language. Because the language
is dynamically typed , it requires more testing and
has errors that only show up at runtime .
Python 2 vs 3
 Python 3.x is devloped as completely new
programming language
 Python 3.0 is not backward-compatible on
purpose.
 so the great features can be implemented even despite
the fact Python 2.x code may not work correctly under
Python 3.x.
Python Identifiers
 An identifier is a name given to entities like class,
functions, variables, etc. It helps to differentiate one
entity from another.
 Rules for writing identifiers
 Identifiers can be a combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0 to
9) or an underscore _.
 Example:
myClass, var_1 ,print_this_to_screen
 An identifier cannot start with a digit. 1variable is
invalid, but variable1 is a valid name.
 Keywords cannot be used as identifiers.
 We cannot use special symbols like !, @, #, $, % etc. in
our identifier.
 An identifier can be of any length.
 Python is a case-sensitive language. This
means, Variable and variable are not the same.
 Always give the identifiers a name that makes sense.
While c = 10 is a valid name, writing count = 10 would
make more sense, and it would be easier to figure out
what it represents when you look at your code after a
long gap.
 Multiple words can be separated using an underscore,
like this_is_a_long_variable.
Valid/Invalid Identifiers
 Cash :
 Ca$h :
 Total123 :
 123total :
 all@hands :
 Java2share :
 if :
 _fy__bca :
Python Keywords
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.7. This number can
vary slightly over the course of time.
 All the keywords except True, False and None are in
lowercase and they must be written as they are.
 To display list of keywords :
import keyword
keyword.kwlist
Python Keywords
Python Data Types : Built-in Data
Types
 Everything in python is Object.
a = 10
type(a) //display type of variable
id(a) //address of object
print(a) //value of variable
Priti Patel
Department of Computer Applications
Built-in Data Types
 Immutable Data types in Python
1. Numeric
2. String
3. Tuple
 Mutable Data types in Python
1. List
2. Dictionary
3. Set
Immutable Object
 Most python objects (booleans, integers, floats,
strings, and tuples) are immutable. This means that
after you create the object and assign some value to it,
you can’t modify that value.
 Definition An immutable object is an object whose
value cannot change.
 Figure 1 shows the memory locations of objects and
what happens when you bind the same variable to a
new object using the expressions a = 1 and then a = 2.
The object with value 1 still exists in memory, but
you’ve lost the binding to it.
Immutable Object
Immutable Object
 A= 10
 B=10
 C=10
for this, only one object is created and 3 refrences are
created.PVM is responsible to create object.
 It improves memory utilisation,object reusability and
improve performance.
 You can get the data type of any object by using
the type() function:

 Print the data type of the variable x:


x=5
print(type(x))

 In Python, the data type is set when you assign a value


to a variable:
Numeric Data Type
 Numeric value can be integer, floating number or even complex
numbers.
 These values are defined as int, float and complex class in
Python.
Integers – This value is represented by int class. It contains
positive or negative whole numbers (without fraction or
decimal).
In Python there is no limit to how long an integer value can be.
Float – This value is represented by float class. It is a real number
with floating point representation.
It is specified by a decimal point. Optionally, the character e or
E followed by a positive or negative integer may be appended
to specify scientific notation. For example, x = 12.34
y = 12E4
z = -87.7e100
Numeric Data Type
 Complex Numbers – Complex number is represented
by complex class.
 It is specified as (real part) + (imaginary part)j.
 For example : 2+3j
Bool Data type
 bool: Data with one of two built-in values True means
1 or False means 0.
 Notice that 'T' and 'F' are capital.
 true and false are not valid booleans and Python will
throw an error for them.
Sequence Type
 In Python, sequence is the ordered collection of
similar or different data types.
 Sequences allows to store multiple values in an
organized and efficient fashion.
 There are several sequence types in Python –
1. String
2. List
3. Tuple
String Data Type
 A string is a collection of one or more characters put in
a single quote, double-quote or triple quote.
 In python there is no character data type, a character
is a string of length one.
 It is represented by str class.
 Single and double quote only applicable to single line.
 Triple single or triple double quote applicable to multi
line.
String Data Type
 In the case of string handling, the operator + is used to
concatenate two strings as the operation "hello"+"
python" returns "hello python".
 The operator * is known as a repetition operator as the
operation "Python" *2 returns 'Python Python'.
Accessing elements of String
 n Python, individual characters of a String can be
accessed by using the method of Indexing.
 Python support for positive and negative index.
 Indexing allows negative address references to access
characters from the back of the String, e.g. -1 refers to
the last character, -2 refers to the second last character
and so on.
Accessing elements of String
Accessing elements of String
 Get the character at position 1 (remember that the first
character has the position 0):
a = "Hello, World!"
print(a[1])

O/P : e
Slicing
 You can return a range of characters by using the slice
syntax.[start index : end index]
 Specify the start index and the end index, separated by
a colon, to return a part of the string.
 Default value of start index is 0(zero).
 Default value of end index is until end it display.
 Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!“
print(b[2:5])
O/P : llo
print(b[:9])
print(b[4:])
print(b[:])
Negative Indexing
b = "Hello, World!"
print(b[-5:-2])
O/P :
String Length
a = "Hello, World!"
print(len(a))
O/P : 13
 The strip() method removes any whitespace from the
beginning or the end:
a = “ Hello, World! "
print(a.strip())
O/P : "Hello, World!"
 The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
O/P : hello, world!
 The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
O/P : HELLO, WORLD!

 The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J"))
O/P : Jello, World!
Check String
 To check if a certain phrase or character is present in a
string, we can use the keywords in or not in.

 Check if the phrase "ain" is present in the following


text:

txt = "The rain in Spain stays mainly in the plain"


x = "ain" in txt
print(x)
O/P : True
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
O/P : False
String Concatenation
 To concatenate, or combine, two strings you can use
the + operator.
a = "Hello"
b = "World"
c=a+b
print(c)
O/P : HelloWorld
Use of format()
 we can combine strings and numbers by using
the format() method!
 The format() method takes the passed arguments, formats
them, and places them in the string where the
placeholders {} are:

 Use the format() method to insert numbers into strings:


age = 36
txt = "My name is Rahul, and I am {}"
print(txt.format(age))
O/P : My name is Rahul, and I am 36
Use of format()
 The format() method takes unlimited number of
arguments, and are placed into the respective
placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
O/P : I want 3 pieces of item 567 for 49.95 dollars.
Use of format()
 You can use index numbers {0} to be sure the arguments are
placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
O/P : I want to pay 49.95 dollars for 3 pieces of item 567
Escape Character
 An escape character is a backslash \ followed by the
character you want to insert.
 e.g. \' to include a quote, or \" to include a double
quotes in a string, as shown below.
str1='Welcome to \'Python Tutorial\'
print(str1)
O/P : Welcome to 'Python Tutorial'
str2="Welcome to \"Python Tutorial\"
print(str2)
O/P : Welcome to "Python Tutorial"
Raw Strings

 A raw string literal is preceded by r or R, which


specifies that escape sequences in the associated string
are not translated. The backslash character is left in
the string:
 Use r or R to ignore escape sequences in a string.

str1=r'Welcome to \'Python Tutorial\' on MSU'


print(str1)
O/P : Welcome to \'Python Tutorial\' on MSU
Escape Character
Python Comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more
readable.
 Comments can be used to prevent execution when
testing code.
 Comments starts with a #, and Python will ignore
them:
 Example
 #This is a comment
print("Hello, World!")
Python Comments
 Comments can be placed at the end of a line, and
Python will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment
 To add a multiline comment you could insert a # for
each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Python Comments
 Other way for Multi Line Comments
 you can use a multiline string.
 Since Python will ignore string literals that are not
assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment
inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
List
 List is Mutable and sequence data type.
 Lists are used to store multiple items in a single variable.
 Lists are created using square brackets:
 Example
mylist = ["a", "b", "c"]
print(mylist)
 List items are ordered, changeable, and allow duplicate
values.
 List items are indexed, the first item has index [0], the
second item has index [1] etc.
 Ordered, it means that the items have a defined order, and
that order will not change.
 If you add new items to a list, the new items will be placed
at the end of the list.
List
 The list is changeable, meaning that we can change,
add, and remove items in a list after it has been
created.
 Allow Duplicates : Since lists are indexed, lists can
have items with the same value:
 To determine how many items a list has, use
the len() function.
 List items can be of any data type,means hetrogeneous
objects are allowed.
 A list can contain different data types.
 Example :
list1 = ["abc", 34, True, 4.5, "male"]
Change Item Value in the list
 To change the value of a specific item, refer to the
index number:
 Example
 Change the second item:
thislist = ["a", "b", "c"]
thislist[1] = “d"
print(thislist)
Insert Items
 To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
 The insert() method inserts an item at the specified
index.
thislist = ["a", "b", "c"]
thislist.insert(2, “d")
print(thislist)
Append Items
 To add an item to the end of the list, use
the append() method.
 Example
thislist = ["a", "b", "c"]
thislist.append("o")
print(thislist)
Extend List
 To append elements from another list to the current
list, use the extend() method.
 Example
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Remove Specified Item
 The remove() method removes the specified item.
 Example
thislist = ["a", "b", "c"]
thislist.remove("b)
print(thislist)
Remove Specified Index
 The pop() method removes the specified index.
 Example
thislist = ["a", "b", "c"]
thislist.pop(1)
print(thislist)
 If you do not specify the index, the pop() method
removes the last item.
 The del keyword also removes the specified index.
del thislist[1]
 The del keyword can also delete the list completely.
del thislist
Clear the List
 The clear() method empties the list.
 The list still remains, but it has no content.
 Example
 Clear the list content:
thislist = ["a", "b", "c"]
thislist.clear()
print(thislist)
Tuple
 Tuple is Immutable and sequence data type.
 Read only version of List is Tuple.
 Tuples are used to store multiple items in a single variable.
 A tuple is a collection which is ordered and unchangeable.
 Tuples are written with round brackets.
 Tuple items are ordered, unchangeable, and allow duplicate values.
 Tuple items are indexed, the first item has index [0], the second item
has index [1] etc.
 Example
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
 To create a tuple with only one item, you have to add a comma after the
item, otherwise Python will not recognize it as a tuple.

thistuple = ("apple",)
print(type(thistuple))
Tuple
 Tuple items can be of any data type.
 A tuple can contain different data types.
 You can access tuple items by referring to the index
number, inside square brackets.
 Tuples are unchangeable, meaing that you cannot
change, add, or remove items once the tuple is created.
 But there is a workaround. You can convert the tuple
into a list, change the list, and convert the list back
into a tuple.
Example
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
 For conversion use list() and tuple() method.
Tuple
 Once a tuple is created, you cannot add items to it.
 You cannot remove items in a tuple.
 Tuples are unchangeable, so you cannot remove
items from it, but you can use the same workaround as
we used for changing and adding tuple items.
 you can delete the tuple completely.
 The del keyword can delete the tuple completely.
List Vs.Tuple
 Syntax Differences
 Lists are surrounded by square brackets [] and Tuples are
surrounded by parenthesis ().
list_num = [1,2,3,4]
tup_num = (1,2,3,4)
 List has mutable nature i.e., list can be changed or
modified after its creation according to needs whereas
tuple has immutable nature i.e., tuple can’t be changed or
modified after its creation.
 As the tuple is immutable these are fixed in size and list are
variable in size.
 Lists has more builtin function than that of tuple.
Set
 Sets are used to store multiple items in a single
variable.
 A set is a collection which is both unordered
and unindexed.
 Sets are written with curly brackets
 Sets are unordered, so you cannot be sure in which
order the items will appear.
 Example
thisset = {"a", "b", "c"}
print(thisset)
Set
 Set items are unordered, unchangeable, and do not
allow duplicate values.
 Unordered means that the items in a set do not have a
defined order.
 Set items can appear in a different order every time you
use them, and cannot be refferred to by index or key.
 Once a set is created, you cannot change its items, but
you can add new items.
 Set items can be of any data type.
 A set can contain different data types.
Set
 You cannot access items in a set by referring to an
index or a key.
 But you can loop through the set items using
a for loop, or ask if a specified value is present in a set,
by using the in keyword.

 Check if "b" is present in the set:


thisset = {"a", "b", "c"}
print("b" in thisset)
Add Items
 To add one item to a set use the add() method.
 Example
thisset = {"a", "b", "c"}
thisset.add("o")
print(thisset)
Add Sets
 To add items from another set into the current set, use
the update() method.
 Example
thisset = {"a", "b", "c"}
tropical = {"p", "m", “k"}
thisset.update(tropical)
print(thisset)
Remove Item
 To remove an item in a set, use the remove(), or
the discard() method.
 Example
thisset = {"a", "b", "c"}
thisset.remove("b")
print(thisset)
 If the item to remove does not exist, remove() will raise
an error.
thisset.discard(“c")
print(thisset)
 If the item to remove does not
exist, discard() will NOT raise an error.
Remove Item
 You can also use the pop(), method to remove an item,
but this method will remove the last item. Remember
that sets are unordered, so you will not know what
item that gets removed.
 The return value of the pop() method is the removed
item.
thisset = {"a", "b", "c"}
x = thisset.pop()
print(x) #removed item
print(thisset) #the set after removal
Remove Item
 The clear() method empties the set:
thisset = {"a", "b", "c"}
thisset.clear()
print(thisset)
 The del keyword will delete the set completely:
thisset = {"a", "b", "c"}
del thisset
print(thisset)
Type Conversion
 You can convert from one type to another with the int(), float(),
and complex() methods:
x=1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

 You cannot convert complex numbers into another number type.


Type Conversion
Priti Patel
Department of Computer Applications
 REPL
 Operators
 Input()
REPL Tool in Python
 REPL is an interactive way to talk to your computer in
Python
 The term “REPL” is an acronym for Read, Evaluate,
Print and Loop because that’s precisely what the
computer does..!
 In python, Python IDLE is REPL Tool.
Python Operators
 Operators are used to perform operations on variables
and values.
 Python divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Arithmetic Operators
 Division Operator always returns float result.
 Floor division operator returns int ot float result.
 In floor division, if both arguments are int , the result
is int.
 In floor division, if one argument is float , the result is
float.
 + operator is used for String concatenation, but both
arguments must be String.
 * operator is used as String multiplication operator,
when one argument is int and one argument is String.
Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
 <,>,<=,>= are used to compare two values and known
as relational Operator.
 == and != known as Equality operators and used to
compare contents
Comparison Operators
 Relational operator is applied on numbers,String and
boolean data type.
 Chaining of relational operator is also possible.
i.e. 10 <20<30 O/P : True
10 <20<30>70 O/p : False
If one argument returns False then result is False.
 Chaining of equality operator is also possible.
i.e. 10==20==30==40 O/p : False
‘a’ ==97 O/p : False
Logical Operators
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
Or Returns True if one of
the statements is true x < 5 or x <4
Not Reverse the result,
returns False if the result
is true not(x < 5 and x < 10)
Logical Operators
 For Boolean type logical operator returns boolean
type.
 For non-boolean type logical operator may return
different result.
0(zero) means False
Non-zero means True
Empty String means False
X and Y :
 if X evaluates to False the result is X otherwise Y.
 10 and 20 O/P : 20
Logical Operators
 X or Y :
if X evaluates True ,the result is X otherwise Y.
10 or 20 O/P : 10
 Not X :
not 10 O/p : False
not “ ” O/p : True
input() method
 The input() method reads a line from input, converts into a
string and returns it.
 syntax :
input([prompt])
 The input() method takes a single optional argument:
prompt (Optional) - a string that is written to standard
output (usually screen) without trailing newline
 The input() method reads a line from the input (usually
from the user), converts the line into a string by removing
the trailing newline, and returns it.
Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Priti Patel
Department of Computer Applications
Conditional Statements
 In programming and scripting languages, conditional
statements or conditional constructs are used to
perform different computations or actions depending
on whether a condition evaluates to true or false.
(Please note that true and false are always written as
True and False in Python.)
 The condition usually uses comparisons and
arithmetic expressions with variables.
 These expressions are evaluated to the Boolean values
True or False.
 The statements for the decision taking are called
conditional statements, alternatively they are also
known as conditional expressions or conditional
constructs.
If statement
 The general form of the if statement in Python looks like
this:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
 If the condition "condition_1" is True, the statements in the
block statement_block_1 will be executed.
 If not, condition_2 will be executed.
 If condition_2 evaluates to True, statement_block_2 will
be executed, if condition_2 is False, the statements in
statement_block_3 will be executed.
Indentation is Important
 Python relies on indentation (whitespace at the
beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for
this purpose.
One-Line if Statements
if <expr>:
<statement>
 But it is permissible to write an entire if statement on
one line. The following is functionally equivalent to
the example above:
if <expr>: <statement>
Conditional Expressions (Python’s Ternary
Operator)
 Python supports one additional decision-making
entity called a conditional expression. (It is also
referred to as a conditional operator or ternary
operator in various places in the Python
documentation.)
 In its simplest form, the syntax of the conditional
expression is as follows:
<expr1> if <conditional_expr> else <expr2>
 In the above example, <conditional_expr> is evaluated
first. If it is true, the expression evaluates to <expr1>. If
it is false, the expression evaluates to <expr2>.
Nested if
 When there is if statement inside another if statement
then it is known as nested if.
if <expr>:
if <expr>:
if <expr>:
<statement>
else:
<statement>
else:
<statement>
else:
<statement>
Priti Patel
Department of Computer Applications
Topics
 Loops
 While Loop
 While with else
 For loop
 For with else
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.
 A loop statement allows us to execute a statement or
group of statements multiple times.
 Loops are used in programming to repeat a specific
block of code.
Loops
while loop
 The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true.
 Syntax :
while test_expression:
Body of while
 In the while loop, test expression is checked first. The body
of the loop is entered only if the test_expression evaluates
to True. After one iteration, the test expression is checked
again. This process continues until
the test_expression evaluates to False.
 In Python, the body of the while loop is determined
through indentation.
 The body starts with indentation and the first unindented
line marks the end.
 Python interprets any non-zero value
as True. None and 0 are interpreted as False.
Flowchart of while Loop
Example
# sum = 1+2+3+...+n
n = 10
# initialize sum and i
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
While loop with else
 while loops can also have an optional else block.
 The else part is executed if the condition in the while
loop evaluates to False.
 The while loop can be terminated with a break
statement. In such cases, the else part is ignored.
Hence, a while loop's else part runs if no break occurs
and the condition is false.
Example
'''Example to illustrate the use of else statement with the
while loop'''
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
for Loop
 The for loop in Python is used to iterate over a
sequence (list, tuple, string) or other iterable objects.
 Iterating over a sequence is called traversal.
 Syntax :
for variable in sequence:
Body of for
 Here, variable takes the value of the item inside the
sequence on each iteration.
 Loop continues until we reach the last item in the
sequence.
 The body of for loop is separated from the rest of the
code using indentation.
Flowchart of for Loop
Example
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
for loop with else
 A for loop can have an optional else block as well.
The else part is executed if the items in the sequence
used in for loop exhausts.
 The break keyword can be used to stop a for loop. In
such cases, the else part is ignored.
 Hence, a for loop's else part runs if no break occurs.
Example
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

Here, the for loop prints items of the list until the loop
exhausts. When the for loop exhausts, it executes the
block of code in the else and prints No items left.
Priti Patel
Department of Computer Applications
Topics
 Function
Functions
 A function is a group of related statements that performs a
specific task.
 A function is a block of code which only runs when it is
called.
 Functions help break our program into smaller and
modular chunks.
 As our program grows larger and larger, functions make it
more organized and manageable.
 Furthermore, it avoids repetition and makes the code
reusable.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.
Creating a Function
 In Python a function is defined using the def keyword:
 Syntax :
def function_name(parameters):
"""docstring"""
statement(s)
Example
def greet(name):
""" This function greets to the person passed in as a parameter ""“
print("Hello, " + name + ". Good morning!")
Function Components
 Keyword def that marks the start of the function header.
 A function name to uniquely identify the function. Function
naming follows the same rules of writing identifiers in Python.
 Parameters (arguments) through which we pass values to a
function. They are optional.
 A colon (:) to mark the end of the function header.
 Optional documentation string (docstring) to describe what the
function does.
 One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually
4 spaces).
 An optional return statement to return a value from the
function.
Calling a Function
 Once we have defined a function, we can call it from
another function, program or even the Python prompt.
 To call a function we simply type the function name
with appropriate parameters.
 Example
def greet(name):
""" This function greets to the person passed in as a parameter ""“
print("Hello, " + name + ". Good morning!")

greet(“priti”)
Hello, Priti. Good morning!
How Function works in Python?
Types of Functions
 Basically, we can divide functions into the following
two types:
 Built-in functions - Functions that are built into
Python.
 User-defined functions - Functions defined by the
users themselves.
Arguments
 Information can be passed into functions as
arguments.
 Arguments are specified after the function name,
inside the parentheses. You can add as many
arguments as you want, just separate them with a
comma.
 By default, a function must be called with the correct
number of arguments. Meaning that if your function
expects 2 arguments, you have to call the function with
2 arguments, not more, and not less.
Arguments
 If you do not know how many arguments that will be
passed into your function, add a * before the
parameter name in the function definition.
 This way the function will receive a tuple of arguments,
and can access the items accordingly:
 If the number of arguments is unknown, add a * before
the parameter name:
def my_function(*subjects):
print("The most elected subject is " + subject[2])
my_function(“sub1", “sub2", “sub3")
Keyword Arguments
 You can also send arguments with
the key = value syntax.
 This way the order of the arguments does not matter.
def my_function(sub3, sub2, sub1):
print(" The most elected subject is " + sub3)
my_function(sub1 = “Hardware", sub2 = “Desktop
Publishing", sub3= “Accounting")
Keyword Arguments
 If you do not know how many keyword arguments that
will be passed into your function, add two
asterisk: ** before the parameter name in the function
definition.
 This way the function will receive a dictionary of
arguments, and can access the items accordingly:
 If the number of keyword arguments is unknown, add
a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Default Parameter Value
 The following example shows how to use a default
parameter value.
 If we call the function without argument, it uses the
default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
 You can send any data types of argument to a function
(string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
 E.g. if you send a List as an argument, it will still be a
List when it reaches the function:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
 To let a function return a value, use
the return statement:
def my(x):
return 5 * x
my(3)
 If there is no expression in the statement or
the return statement itself is not present inside a
function, then the function will return
the None object.
Scope and Lifetime of variables
 Scope of a variable is the portion of a program where
the variable is recognized. Parameters and variables
defined inside a function are not visible from outside
the function. Hence, they have a local scope.
 The lifetime of a variable is the period throughout
which the variable exits in the memory. The lifetime of
variables inside a function is as long as the function
executes.
 They are destroyed once we return from the function.
Hence, a function does not remember the value of a
variable from its previous calls.
Scope and Lifetime of variables
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
The pass Statement
 function definitions cannot be empty, but if you for
some reason have a function definition with no
content, put in the pass statement to avoid getting an
error.
def myfunction():
pass
Recursion
 Python also accepts function recursion, which means a
defined function can call itself.
 Recursion is a common mathematical and
programming concept. It means that a function calls
itself. This has the benefit of meaning that you can
loop through data to reach a result.
 The developer should be very careful with recursion as
it can be quite easy to slip into writing a function
which never terminates, or one that uses excess
amounts of memory or processor power.
 However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to
programming.
Recursion
Recursion Example
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))
Recursion Example
Recursion Example
Python Anonymous/Lambda
Function
 In Python, an anonymous function is a function that is
defined without a name.
 While normal functions are defined using
the def keyword in Python, anonymous functions are
defined using the lambda keyword.
 Hence, anonymous functions are also called lambda
functions.

Python Anonymous/Lambda
Function
 Syntax of Lambda Function in python
lambda arguments: expression
 Lambda functions can have any number of arguments
but only one expression.
 The expression is evaluated and returned.
 Lambda functions can be used wherever function
objects are required.
 Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
Python Anonymous/Lambda
Function
 We can now call it as a normal function. The
statement
double = lambda x: x * 2
 is nearly the same as:
def double(x):
return x * 2
Priti Patel
Department of Computer Applications
Topics
 Module
 Built in module
Module
 A module is a file containing Python definitions and
statements.
 we can use the module , by using
the import statement:
import module_name
 When using a function from a module, use the syntax:
module_name.function_name
 The module can contain functions, as already
described, but also variables of all types (arrays,
dictionaries, objects etc).
 There are several built-in modules in Python, which
you can import whenever you like.
 There are several built-in modules in Python, which
you can import whenever you like.
Module
import platform
x = platform.system()
print(x)
 There is a built-in function to list all the function
names (or variable names) in a module.
The dir() function.
 List all the defined names belonging to the platform
module:
import platform
x = dir(platform)
print(x)
Python Math
 Python has a set of built-in math functions, including
an extensive math module, that allows you to perform
mathematical tasks on numbers.
 The min() and max() functions can be used to find the
lowest or highest value in an iterable.
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
 The pow(x, y) function returns the value of x to the
power of y (xy).
The Math Module
 Python has also a built-in module called math, which
extends the list of mathematical functions.
 To use it, you must import the math module.
import math
 When you have imported the math module, you can
start using methods and constants of the module.
 The math.sqrt() method for example, returns the
square root of a number.
import math
x = math.sqrt(64)
print(x)
The Math Module
 The math.ceil() method rounds a number upwards to
its nearest integer, and the math.floor() method
rounds a number downwards to its nearest integer, and
returns the result.
 The math.pi constant, returns the value of PI (3.14...).
Priti Patel
Department of Computer Applications
Topics
 Array
Array
 An array is a collection of items stored at contiguous
memory locations.
 The idea is to store multiple items of the same type
together.
 Arrays are sequence types and behave very much like
lists, except that the type of objects stored in them is
constrained.
Array Module
 The array module allows us to store a collection of
numeric values.
 In a way, this is like a Python list, but we specify a
type at the time of creation.
 To create an array of numeric values, we need to
import the array module.
import array
class array.array(typecode[,initializer])
For example:
arr=array.array('i',[1,3,4])
Array Module
Type Code C Type Python Type
b signed char int
B unsigned char int
h signed short int
H unsigned short int
i signed int int
I unsigned int int
l signed long int
L unsigned long int
q signed long long int
Q unsigned long long int
f float float
d double float
Array Module
 array.typecode
The typecode character used to create the array.
from array import *
array_num = array('i', [1,3,5,7,9])
array_num.typecode
 array.itemsize
The length in bytes of one array item in the internal
representation.
array_num = array('i', [1,3,5,7,9,10,15])
array_num.itemsize
Array Module
 array.append(x)
Append a new item with value x to the end of the array.
array_num = array('i', [1,3,5,7,9,10,15])
array_num.append(100)
 array.count(x)
Return the number of occurrences of x in the array.
 # How to count the number of occurrences of an
element in an array?
array_num = array('i', [1,3,5,7,9,10,15,10])
array_num.count(10)
Array Module
 array.extend(iterable)
Append items from iterable to the end of the array. If
iterable is another array, it must have exactly the same
type code; if not, TypeError will be raised.
 # How to extend an array with values from a list?
from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: "+str(array_num))
array_num.extend(array_num)
print("Extended array: "+str(array_num))
Array Module
 array.index(x)
Return the smallest i such that i is the index of the first
occurrence of x in the array.
 array.insert(i, x)
Insert a new item with value x in the array before
position i. Negative values are treated as being relative
to the end of the array.
 array.pop([i])
Removes the item with the index i from the array and
returns it. The optional argument defaults to -1,
so that by default the last item is removed and
returned.
Array Module
 array.remove(x)
Remove the first occurrence of x from the array.
 array.reverse()
Reverse the order of the items in the array.
 array.tolist()
Convert the array to an ordinary list with the same
items.
 Concatenate two arrays in Python
arr+arr
 Multiply an array by a constant
arr*2
Priti Patel
Department of Computer Applications
Flow Chart
 A flowchart is a diagrammatic representation of an
algorithm.
 A flowchart can be helpful for both writing programs and
explaining the program to others.
 A flowchart is a diagram that depicts a process, system or
computer algorithm
 Flowchart is a diagrammatic representation of sequence of
logical steps of a program.
 Flowcharts use simple geometric shapes to depict processes
and arrows to show relationships and process/data flow.
Symbols Used In Flowchart
Symbols Used In Flowchart
Guidelines for Developing
Flowcharts
 Flowchart can have only one start and one stop symbol
 On-page connectors are referenced using numbers
 Off-page connectors are referenced using alphabets
 General flow of processes is top to bottom or left to
right
 Arrows should not cross each other
Flowchart for going to the market
to purchase a pen.
Examples of flowcharts in programming
Add two numbers entered by the user.

You might also like