Python
The Complete Course
TELCOMA
Copyright © TELCOMA. All Rights Reserved
Introduction
Copyright © TELCOMA. All Rights Reserved
What is Python ?
● Python is a general-purpose interpreted, interactive,
object-oriented, and high-level programming language.
● Python is designed to be highly readable.
● Python is copyrighted. Like Perl, Python source code is also
available under the GNU General Public License (GPL).
Copyright © TELCOMA. All Rights Reserved
Python’s Creator
● Guido van Rossum is the
creator of Python, one of the
world's most popular
programming languages
● Python was conceived in the
late 1980s, and its
implementation began in
December 1989
Copyright © TELCOMA. All Rights Reserved
Why named Python?
● Named after Monty Python
● Monty Python were a British
comedy group who created
their sketch comedy show
Monty Python's Flying Circus,
which first aired on the BBC in
1969.
Copyright © TELCOMA. All Rights Reserved
Companies using Python
Copyright © TELCOMA. All Rights Reserved
Python Feature
● 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.
Python Feature
● Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
● 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.
Python Feature
● 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
Getting Python
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
Copyright © TELCOMA. All Rights Reserved
IDLE SHELL (FILE MENU)
Entity Function
New File Create New File
Open Open Existing File
Recent File Open list of Recent File
Open Module Open Existing Module
Class Browser Show functions, classes
Path Browser Show sys.path Directories,Module etc
Save Save Current Window
Save As Save with New Associated File
Save Copy As Save Current window to different file
Print Window Print current window to default Printer
close Close Current Window
Exit Close all Window and Quit
IDLE SHELL (Edit MENU)
Entity Function
Undo Undo the last change of current window
Redo Redo the last undone change to current window
Cut Copy selection than delete selection
Copy Copy selection into system-wide clipboard
Paste Insert contents of system wide clipboard
Select all Select entire contents of current window
Find Open search dialog with many option
Find selection Search for the currently selected string
Find in files Open a file search dialog
Replace Open a search and replace dialog
Go to line Move cursor to the line number requested make a line
visible
IDLE SHELL (Edit MENU)
Entity Function
Show Completions Open a scrollable list allowing selection of
keyword and attribute
Expand word Expand a prefix you have type to match a
full word in the same window
Show call tip After an unclosed parenthesis for a function
, open a small window with function
parameter hints
Show surrounding parens Highlight the surrounding parenthesis
IDLE SHELL (Shell MENU)
Entity Function
View Last Restart Scroll the shell window to the
last shell restart
Restart shell Restart shell to clean the
environment
Interrupt Execution Stop a running program
IDLE SHELL (Debug MENU)
Entity Function
Go to file/line Look on the current line, for a file
name and line number
Debugger Code entered in shell or run from
an editor will run under the
debugger
Stack viewer Show the stack traceback of last
exception with local and global
Auto open stack viewer Toggle automatically opening the
stack viewer on an unhandled
exception
Debug MENU (Debugger)
● Debug control and it’s
entities
Debug MENU (Debugger)
Problem statement : write a program an
average of the three value[20,30,50].
•STEP 1: write a program in new file.
Debug MENU (Debugger)
•STEP 2: Run the Module
Debug MENU (Debugger)
•STEP 3 :On the Debug
•STEP 4 :Call a Function
Debug MENU (Debugger)
Step 5 : Check all step one by one by
clicking the step button
Debug MENU (Debugger)
•STEP 6: Getting an average of the three
value[20,30,50].
IDLE SHELL (option MENU)
Entity Function
Configure Idle change preferences for the following:
fonts, indentation, key bindings, text color
themes, startup windows and size,
additional help sources, and extensions
Option MENU (Font & Tabs)
•It has …..
•Font Face
•Indentation Width
OptionMENU (Highlighting)
•It Has……
•Custom Highlighting
•Highlighting Theme
•Foreground and Background
Option MENU (Keys)
•It Has…
•Key set
•Custom Key Building
Option MENU (General)
•It Has…..
•Start up preferences
•Auto save Preferences
•Initial Window Size
•Default Source Coding
Option MENU (Extensions)
•It Has…..
•Auto Complete Script Binding
•Auto Expand Zoom Height
•Call tips
•Code context
•Format Paragraph
•Parenmatch
•Rstripextension
IDLE SHELL (Window Menu)
Entity Function
Zoom Height Toggles the window between normal size and
maximum height. The initial size defaults to 40
lines by 80 char.
IDLE SHELL (Help MENU)
Entity Function
About Display version, copyright, license, credits, and more
IDLE
IDLE Display a help file for IDLE detailing the menu options, basic
Help editing and navigation, and other tips.
Python Access local Python documentation
Docs
Variable Type
Copyright © TELCOMA. All Rights Reserved
What is variable?
● Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve
some space in memory.
● Based on the datatype of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
● Can store integers, decimals or characters in these variables.
Assign Value to Variable
● 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.
= Operator It’s Mean
Left Side Name of the variable
Right Side Value stored in the variable
Assign Value to Variable
● Write a program that assign
10,50.00 and jack are the values
assigned to counter, kilometer and
name variables.
Multiple Assignment
● Python allows you to assign a
single value to several variables
simultaneously.
● Write a program ,assign the
same value to the three
different variable
Multiple Assignment
● Assign multiple objects to multiple
variables
● Write a program , assign two values
to two variable and one variable
with string Object.
Basic Operator
Copyright © TELCOMA. All Rights Reserved
What is Operator ?
● Operators are the constructs which can manipulate the value of
operands
● Consider the expression 1 + 6 = 7. Here, 1 and 6 are called operands
and + is called operator
Operator Types
1 Arithmetic Operators
2 Comparison (Relational) Operators
3 Assignment Operators
4 Logical Operators
5 Bitwise Operators
6 Membership Operators
7 Identity Operators
Arithmetic Operators
Operator Description
+ Addition Adds values on either side of the operator
- Subtraction Subtracts right hand operand from left hand operand
* Multiplication Multiplies values on either side of the operator
/ Division Divides left hand operand by right hand operand
% Modulus Divides left hand operand by right hand operand and returns
remainder
** Exponent Performs exponential (power)
// Floor Division Division of operands where the result is the quotient
Arithmetic Operators
● Difference b/w Division and Floor
Division
Comparison Operators
Operator Description
== If the values of two operands are equal, then the condition
becomes true
!= If values of two operands are not equal, then condition
becomes true.
> left operand is greater than the value of right operand, then
condition becomes true.
< left operand is less than the value of right operand, then
condition becomes true
>= left operand is greater than or equal to the value of right
operand, then condition becomes true
<= left operand is less than or equal to the value of right
operand, then condition becomes true
Assignment Operators
Operator Description
= Assigns values from right side operands to left side
operand
+= It adds right operand to the left operand and assign
the result to left operand
-= It subtracts right operand from the left operand and
assign the result to left operand
*= It multiplies right operand with the left operand and
assign the result to left operand
/= It divides left operand with the right operand and
assign the result to left operand
Assignment Operators
Operator Description
%= It takes modulus using two operands and assign
the result to left operand
**= Performs exponential (power) calculation on
operators and assign value to the left operand
//= It performs floor division on operators and assign
value to the left operand
Logical Operators
Operator Description Example
and If both the operands are true then (a and b ) is true
condition becomes true.
or If any of the two operands are (a 0r b ) is true
non-zero then condition becomes
true.
not Used to reverse the logical state of its Not (a and b) is false
operand.
Bitwise Operators
Operator Description
& binary and Operator copies a bit to the result if
it exists in both operands
| binary or It copies a bit if it exists in either
operand
^ binary xor It copies the bit if it is set in one
operand but not both
~ binary ones complement It is unary and has the effect of
'flipping' bits
<< binary Left Shift left operands value is moved left by
the number of bits specified by the
right operand
>> binary Right Shift left operands value is moved right
by the number of bits specified by
the right operand
Membership Operators
Operator Description
in True if it finds a variable in the specified sequence
and false otherwise
not in True if it does not finds a variable in the specified
sequence and false otherwise
Identity Operators
Operator Description
is True if it finds a variable in the specified sequence
and false otherwise
is not True if it does not finds a variable in the specified
sequence and false otherwise
Number
Copyright © TELCOMA. All Rights Reserved
Different Types
•Python supports four different numerical types
Type Examples
int 10,100,-786
long 51924368L , -4721584512L
float -21.9,-90,15.24
complex 3+4j,3e+26j
Number Type Conversion
Type Function
int(x) convert x to a plain integer
long(x) convert x to a long integer
float(x) convert x to a floating-point number
complex (x) x to a complex number with real part x and
imaginary part zero.
complex(x,y) convert x and y to a complex number with real
part x and imaginary part y
Mathematical Function
Function Description
abs(x) The absolute value of x
cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y
max(x1,x2,..) The largest of its arguments
min(x1,x2,..) The smallest of its arguments
pow(x,y) The value of x**y
round(x) x rounded
sqrt(x) The square root of x for x > 0
Trigonometric Function
Function Description
Sin(x) Return the sine of x, in radians
Cos(x) Return the cosine of x, in radians
Tan(x) Return the tangent of x, in radians
Mathematical Constant
Constants Description
pi The mathematical constant pi.
e The mathematical constant e
String
Copyright © TELCOMA. All Rights Reserved
String
● Strings are amongst the most
popular types in Python.
● We can create them simply by
enclosing characters in quotes.
● Python treats single quotes the
same as double quotes.
Values in String
● Python does not support a
character type; these are
treated as strings of length one,
also considered a substring.
● To access substrings, use the
square brackets
Updating String
● You can "update" an existing string
by (re)assigning a variable to
another string.
Escape Characters
Backslash Description
notation
\n For a new line
\t For a tab (space)
String Special Operator
Operator Description
+ Adds values on either side of the operator
* Multiple copies of the same string
[] Gives the character from the given index
[:] Gives the characters from the given range
In Returns true if a character exists in the given string
not in Returns true if a character does not exist in the given string
String Formatting Operator
Format conversion
symbol
%c character
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer
%e exponential notation
%f floating point real number
Triple Quotes
● Python's triple quotes comes
to the rescue by allowing
strings to span multiple lines
● No need of the \backslash n,
for the new line
Built In String Method
1. capitalize ()
•It returns a copy of the string with only
its first character capitalized.
Built In String Method
2. center(width, fillchar)
width -- This is the total width of the
string.
fillchar -- This is the filler character
• This method returns centered in a
string of length width
Built In String Method
3. count(sub, start= 0,end=len(string))
sub -- This is the substring to be
searched.
start -- Search starts from this index.
First character starts from 0 index. By
default search starts from 0 index.
end -- Search ends from this index. First
character starts from 0 index. By default
search ends at the last index.
Built In String Method
4. String encode and decode
encode(encoding='UTF-8',errors='strict')
decode(encoding='UTF-8',errors='strict')
Ref:
https://docs.python.org/3/library/codecs.html#standard-encodings
Built In String Method
5. String endswith ()
•It returns True if the string ends with the
specified suffix, otherwise return False
suffix -- This could be a string or could also be
a tuple of suffixes to look for.
start -- The slice begins from here.
end -- The slice ends here.
Built In String Method
6.String find
•Determine if str occurs in string or in a
substring of string if starting index beg
and ending index end are given returns
index if found and -1 otherwise.
str.find(str, beg=0, end=len(string))
Built In String Method
7. isalnum()
Returns true if string has at least 1 character and
all characters are alphanumeric and false
otherwise.
8. isalpha()
Returns true if string has at least 1 character and
all characters are alphabetic and false otherwise
9. isdigit()
Returns true if string contains only digits and
false otherwise
Built In String Method
10. islower()
Returns true if string has at least 1 cased
character and all cased characters are in
lowercase and false otherwise.
11. isspace()
Returns true if string contains only whitespace
characters and false otherwise
12.istitle()
Returns true if string is properly "titlecased" and
false otherwise
Built In String Method
13. join(seq).
Merges (concatenates) the string
representations of elements in sequence seq
into a string, with separator string
14. len(string)
Returns the length of the string
15.lstrip()
Removes all leading whitespace in string
Built In String Method
16. maketrans()
Returns a translation table to be used in
translate function.
17. max(str)
Returns the max alphabetical character from
the string str
18. min(str)
Returns the min alphabetical character from
the string str
Built In String Method
19. replace(old, new [, max])
Replaces all occurrences of old in string with new
or at most max occurrences if max given.
20.rindex( str, beg=0, end=len(string))
rindex() returns the last index where the
substring str is found
21. startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if
starting index beg and ending index end are given)
starts with substring str; returns true if so and false
otherwise
Built In String Method
22. swapcase()
Inverts case for all letters in string
23. zfill()
Returns original string leftpadded with zeros to
a total of width characters
List
Copyright © TELCOMA. All Rights Reserved
List in python
•The list is a most versatile data type
available in Python which can be written
as a list of comma-separated values
(items) between square brackets.
•Important thing about a list is that items
in a list need not be of the same type.
Assign Value in List
•To access values in lists, use the
square brackets for slicing along with
the index
Updating List
•You can update single or multiple
elements of lists …
Delete List
•To remove a list element, you can
use either the del statement if you
know exactly which element(s) you
want to delete.
Basic List Operation
List
Length
Concatenation
Repetition
Membership
Iteration
Indexing ,slice & Matrixes
•Because lists are sequences,
indexing and slicing work the same
way for lists as they do for strings
Built in Function & Methods
1 .Cmp(list1,list2)
The method cmp() compares elements
of two lists.
Built in Function & Methods
2. len(list)
•Gives the total length of the list
3.max(list)
•Returns item from the list with max value
4. min(list)
•Returns item from the list with min value
Built in Function & Methods
5. list(seq)
•Converts a tuple into list
Python list methods
1. list.append(obj)
• The method append() appends a
passed obj into the existing list
2. list.count(obj)
• The method count() returns count of
how many times obj occurs in list
3. list.extend(seq)
• The method extend() appends the
contents of seq to list
Python list methods
4. list.index(obj)
•The method index() returns the lowest
index in list that obj appears
5. list.insert(index, obj)
•The method insert() inserts
object obj into list at offset index
6. list.pop(obj=list[-1])
•The method pop() removes and returns
last object or obj from the list
Python list methods
7. list.remove(obj)
•Removes object obj from list
8. list.reverse()
•Reverses objects of list in place
9. list.sort([func])
•Sorts objects of list, use compare
function if given
Tuples
Copyright © TELCOMA. All Rights Reserved
Tuples
● Tuples are sequences, just like lists.
● The differences between tuples and
lists are, the tuples cannot be
changed unlike lists
● The tuples use parentheses, whereas
lists use square brackets
Assign Values in Tuples
● To access values in tuple, use the
square brackets for slicing along with
the index
Updating Tuples
● Tuples are immutable which means
you cannot update or change the
values of tuple elements.
Delete Tuples
● Removing individual tuple elements is not
possible.
Basic Tuples Operation
Function
Length
Concatenation
Repetition
Membership
iteration
Indexing, Slicing and
Matrixes
● Because tuples are sequences,
indexing and slicing work the same
way for tuples as they do for strings
Built-in Tuple Function
1. cmp(tuple1, tuple2)
Compares elements of both tuples.
2. len(tuple)
Gives the total length of the tuple.
Built-in Tuple Function
3. max(tuple)
Returns item from the tuple with max
value
4. min(tuple)
Returns item from the tuple with min
value
5.tuple(seq)
Converts a list into tuple
Dictionary
Copyright © TELCOMA. All Rights Reserved
Dictionary in Python
● Each key is separated from its value
by a colon (:)
● The items are separated by commas,
and the whole thing is enclosed in
curly braces
● Keys are unique within a dictionary
while values may not be.
● The values of a dictionary can be of
any type, but the keys must be of an
immutable data type such as strings,
numbers
Assign Value
● To access dictionary elements, you
can use the familiar square brackets
along with the key to obtain its value
Updating Dictionary
● You can update a dictionary by
adding a new entry or a key-value
pair, modifying an existing entry, or
deleting an existing entry
Deleting Dictionary
● You can either remove individual
dictionary elements or clear the
entire contents of a dictionary.
● You can also delete entire dictionary
in a single operation
Properties of Dictionary
keys
(a) More than one entry per key not
allowed. Which means no duplicate key is
allowed.
When duplicate keys encountered
during assignment, the last assignment
wins.
Properties of Dictionary
keys
(b) Keys must be immutable. Which
means you can use strings, numbers or
tuples as dictionary keys but something
like ['key'] is not allowed.
Built in Dictionary
1. cmp(dict1,dict2)
Compares elements of both dict
2. len(dict)
Gives the total length of the
dictionary. This would be equal to the
number of items in the dictionary
Built in Dictionary
3. str(dict)
Produces a printable string representation
of a dictionary
4. type(variable)
Returns the type of the passed variable. If
passed variable is dictionary, then it
would return a dictionary type
I/O Files
Copyright © TELCOMA. All Rights Reserved
Printing to the screen
•The simplest way to produce output
is using the print statement where
you can pass zero or more
expressions separated by commas.
•This function converts the
expressions you pass into a string and
writes the result to standard output
Reading Keyboard Input
a) raw_____ input Function
The raw_input([prompt]) function reads
one line from standard input and
returns it as a string.
b) input Function
The input([prompt]) function is equivalent
to raw_input, except that it assumes the
input is a valid Python expression and
returns the evaluated result to you.
Opening and closing Files
•Until now, you have been reading and
writing to the standard input and output.
Now, we will see how to use actual data
files.
•Python provides basic functions and
methods necessary to manipulate files by
default.
•You can do most of the file manipulation
using a file object.
Open Function
•Before you can read or write a file, you
have to open it using Python's
built-in open() function.
•This function creates a file object,
which would be utilized to call other
support methods associated with it.
Open Function
Syntax: file object = open(file_name [, access_mode][, buffering])
Name Parameter
file_name Argument is a string value that contains the name of the file that you want to access
access_mode The access_mode determines the mode in which the file has to be opened, i.e., read, write,
append, etc
buffering If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line
buffering is performed while accessing a file
Open Function
•Here is a list of the different modes of opening a file
Modes Description Modes Description
r Opens a file for reading only wb Opens a file for writing only in
binary format
rb Opens a file for reading only in w+ Opens a file for both writing and
binary format reading
r+ Opens a file for both reading wb+ Opens a file for both writing and
and writing reading in binary format
rb+ Opens a file for both reading a Opens a file for appending.
and writing in binary format
w Opens a file for writing only ab Opens a file for appending in binary
format
ab+ Opens a file for both appending
and reading in binary format
File Object Attributes
● Once a file is opened and you have
one file object, you can get various
information related to that file.
Attribute Description
file.closed Returns true if file is closed, false otherwise
file.mode Returns access mode with which file was opened
file.name Returns name of the file
file.softspace Returns false if space explicitly required with print, true
otherwise
Close Function
● The close() method of a file object
flushes any unwritten information and
closes the file object, after which no
more writing can be done.
•Syntax: fileObject.close()
Reading and Writing Files
a) Write() Method
The write() method writes any string to
an open file.
It is important to note that Python strings
can have binary data and not just text.
Syntax: fileObject.write(string)
Writing Files
For writing a file,
>>In Python Shell ,you have to open a
new file and write a code to open a file
and write something in it.
>>After that you have to run a module
>>That will create your jst.txt file on your
desktop and you can see a written string
which you wrote in python file.
Reading and Writing Files
b) read() Method
The read() method reads a string from an
open file. It is important to note that
Python strings can have binary data. apart
from text data.
Syntax:fileObject.read([count])
Reading and Writing Files
b) read() Method
Syntax:fileObject.read([count])
>> with different Count
File Positions
● The tell() method tells you the
current position within the file;
● In other words, the next read or
write will occur at that many
bytes from the beginning of the
file.
File Positions
● The seek(offset[,from]) method
changes the current file position.
● The offset argument indicates the
number of bytes to be moved.
● The from argument specifies the
reference position from where the
bytes are to be moved
File Positions
● The seek(offset[, from]) method
changes the current file position
● Offset position Change >>>>
File Positions
● If from is set to 0, it means use the
beginning of the file as the reference
position
● Set to 1 means use the current
position as the reference position
● set to 2 then the end of the file would
be taken as the reference position.
Renaming Files
● The rename() method takes two
arguments, the current filename and
the new filename
● Syntax:
os.rename(current_file_name,
new_file_name)
Deleting Files
● You can use the remove() method
to delete files by supplying the
name of the file to be deleted as
the argument.
● Syntax:
os.remove(file_name)
Directories in Python
● All files are contained within various
directories. & Python has no problem
handling these directories .
● The os module has several methods
that help you create, remove, and
change directories.
Get current working dict.
getcwd() :
•The getcwd() method displays the
current working directory.
Syntax :
•os.getcwd()
Create a dict.
mkdir() :
•The mkdir() method of the os module to
create directories in the current directory.
Syntax :
•os.mkdir("newdir")
Remove a dict.
rmdir() :
•The rmdir() method deletes the
directory, which is passed as an
argument in the method.
Syntax :
•os.rmdir('dirname')
Date & Time
Copyright © TELCOMA. All Rights Reserved
Date & Time
● A Python program can handle date
and time in several ways.
● Python's time and calendar
modules help track dates and
times.
Tick
● Time intervals are floating-point
numbers in units of seconds.
● Particular instants in time are
expressed in seconds since 12:00am,
January 1, 1970(epoch).
Time Tuple
IndexIndex Field Field Values
Values
0 0 4-digit year
4-digit year 2008
2008
● Many of Python's time
1 Month 1 to 12
functions handle time as a 1 Month 1 to 12
2 Day 1 to 31
tuple of numbers…… 2 Day 1 to 31
3 Hour 0 to 23
3 Hour 0 to 23
4 Minute 0 to 59
4 Minute 0 to 59
5 Second 0 to 61 (60 or 61 are
5 Second 0 to 61 (60 or 61 are
leap-seconds)
leap-seconds)
6 Day of Week 0 to 6 (0 is Monday)
6 Day of 0 to 6 (0 is Monday)
7 Day of year 1 to 366 (Julian day)
Week
8 Daylight -1, 0, 1, -1 means library
7 Day of savings
1 to 366determines
(JulianDSTday)
year
8 Daylight -1, 0, 1, -1 means
Time Attribute
Index Attributes Values
0 tm_year 2008
● Tuple is equivalent
to struct_time structure. This
1 tm_mon 1 to 12
structure has following 2 tm_mday 1 to 31
attributes ….. 3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are
leap-seconds)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian day)
8 tm_isdst -1, 0, 1, -1 means
library determines
DST
Getting Current Time
● To translate a time instant from
a seconds since the
epoch floating-point value into a
time-tuple
● pass the floating-point value to a
function (e.g., localtime) that
returns a time-tuple with all nine
items valid.
Getting Formatted Time
● Format any time as per your
requirement, but simple method to
get time in readable format is
asctime()
Getting calendar
● The calendar module gives a wide
range of methods to play with yearly
and monthly calendars. Here, we
print a calendar for a given month
calendar Module
1. calendar.isleap(year)
Returns True if year is a leap year;
otherwise, False.
2. calendar.leapdays(y1,y2)
Returns the total number of leap days
in the years within range(y1,y2)
3. calendar.month(year,month)
Returns a multiline string with a calendar
for month month of year.
If….else Statement
Copyright © TELCOMA. All Rights Reserved
If….else Statement
If Statement Syntax If test expression :
statement(s)
•Here, the program evaluates the test
expression and will execute statement(s)
only if the text expression is True.
•If the text expression is False, the
statement(s) is not executed.
•In Python, the body of the if statement is
indicated by the indentation. Body starts
with an indentation.
•Python interprets non-zero values
as True. None and 0 are interpreted
as False.
If Statement Example
# If the number is positive, we print
an appropriate message
num = 3
num > 0 is the test expression.
if num > 0:
The body of if is executed only if this
evaluates to True. print(num, "is a positive number")
When variable num is equal to 3, test print("This is always printed")
expression is true and body inside body
of if is executed. num = -1
If variable num is equal to -1, test if num > 0:
expression is false and body inside
body of if is skipped. print(num, "is a positive number")
print("This is also always printed")
If..else Statement syntax
If test expression :
Body of if
else:
Body of else
•The if..else statement evaluates test
expression and will execute body
of if only when test condition is True.
•If the condition is False, body of else is
executed. Indentation is used to separate
the blocks.
If..else Statement Example
# Program checks if the number is
positive or negative
when num is equal to 3, the test # And displays an appropriate
message
expression is true and body of if is
executed and body of else is skipped. num = 3
If num is equal to -5, the test expression is # Try these two variations as well.
false and body of else is executed and
body of if is skipped. # num = -5
# num = 0
If num is equal to 0, the test expression is
true and body of if is executed if num >= 0:
print("Positive or Zero")
and body of else is skipped.
else:
print("Negative number")
If test expression:
If..elif..else Syntax Body of if
Elif test expression:
Body of elif
•The elif is short for else if. It allows us to else :
Body of else
check for multiple expressions.
•If all the conditions are False, body of else
is executed.
•Only one block among the
several if...elif...else blocks is executed
according to the condition.
•The if block can have only one else block.
But it can have multiple elif blocks
If..elif..else example
# In this program
# we check if the number is
#positive or
# negative or zero and
When variable num is positive, Positive # display an appropriate message
number is printed. num = 3.4
# Try these two variations as well
If num is equal to 0, Zero is printed. :# num = 0
# num = -4.5
If num is negative, Negative number is
printed if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Nested if statements
● We can have a if...elif...else statement
inside another if...elif...elsestatement.
This is called nesting in computer
programming.
Nested if example
# In this program, we input a
#number check if the number is
#positive or negative or zero and
Output 1 #display an appropriate message
# This time we use nested if
Enter a number: 7
num = float(input("Enter a
Positive number
number: "))
Output 2
if num >= 0:
Enter a number: -10 if num == 0:
print("Zero")
Negative number
else:
Output 3 print("Positive number")
Enter a number: 0
else:
Zero print("Negative number")
For …Loop
Copyright © TELCOMA. All Rights Reserved
For Val in sequence:
Syntax of for Loop Body of for
● Here, Val is the variable that 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.
for Loop example
● In this program, we take a list as
number.
● Sum of this list will be store in the
SUM
● After that we use a for loop to sum all
the numbers in the List.
● Sum of all the List number will be
store in the Sum variable.
The range () function
● We can generate a sequence of
numbers using range() function.
● We can also define the start, stop and
step size as range(start,stop,step size).
step size defaults to 1 if not provided.
● To force this function to output all the
items, we can use the function list().
The len () Function
● We can use the range() function in for
loops to iterate through a sequence of
numbers.
● It can be combined with
the len() function to iterate through a
sequence using indexing.
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.
While… Loop
Copyright © TELCOMA. All Rights Reserved
While test expression :
Syntax of While loop Body Of While
● In 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.
While loop example
● The test expression will
be True as long as our counter
variable i is less than or equal
to n (10 in our program).
While loop with else
● Same as that of for loop, we can have
an optional else block with while loop
as well.
● 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 case, the else part is ignored.
Hence, a while loop's else part runs if
no break occurs and the condition is
false.
Break …..Continue
Copyright © TELCOMA. All Rights Reserved
Python break statement
● The break statement terminates the
loop containing it. Control of the
program flows to the statement
immediately after the body of the
loop.
● If break statement is inside a nested
loop (loop inside another loop), break
will terminate the innermost loop.
break statement example
● In this program, we iterate through
the “I am jacksparrow " sequence.
● We check if the letter is “p", upon
which we break from the loop.
● Hence, we see in our output that all
the letters up till “p" gets printed. After
that, the loop terminates.
Python continue statement
● The continue statement is used to skip
the rest of the code inside a loop for
the current iteration only.
● Loop does not terminate but
continues on with the next iteration.
Continue statement
example
● This program is same as the above
example except the break statement
has been replaced with continue.
● We continue with the loop, if the string
is “p", not executing the rest of the
block. Hence, we see in our output
that all the letters except “p" gets
printed
Function
Copyright © TELCOMA. All Rights Reserved
What is Python Function?
● In Python, function is a group of
related statements that perform a
specific task.
● 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 code reusable.
Syntax Of Function
def function name(parameters) :
“” doc string “”
Statement (s)
● Keyword def marks the start of function header.
● A function name to uniquely identify it. 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 function header.
● Optional documentation string (docstring) to describe what the
function does.
Syntax Of Function
def function name(parameters) :
“” doc string “”
Statement (s)
● One or more valid python statements that make up the function
body. Statements must have same indentation level (usually 4
spaces).
● An optional return statement to return a value from the function.
Example Of a Function
Problem Statement :write a function which
gives you a morning Greeting .
Step 1:
>>Define a Function in new python file
Step 2:
>>Call a function from Python Idle shell
The Return Statement return [expression_list]
syntax
● This statement can contain
expression which gets evaluated and
the value is returned.
● 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.
● Here, None is the returned value.
Example Of Return
Problem Statement: Write a function for
the absolute number and return it’s
value.
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 is not visible
from outside. Hence, they have a
local scope.
● 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.
Scope and Lifetime Of
variables
● They are destroyed once we return
from the function. Hence, a function
does not remember the value of a
variable from its previous calls.