SlideShare a Scribd company logo
1 of 67
Module 1
Programming Fundamentals
1
22MCSIT201 – Python Programming
Master of Science in Computer Science & Information Technology
[MSc-CSIT]
Unit 1
Programming
Fundamentals
• Python is an object-oriented programming language created by Guido
Rossum in 1989.
• It is ideally designed for rapid prototyping of complex applications.
• Many large companies use the Python programming language include
NASA, Google, YouTube, BitTorrent, etc.
• Python programming is widely used in Artificial Intelligence, Natural
Language Generation, Neural Networks and other advanced fields of
Computer Science.
• Python had deep focus on code readability & this class will teach you
python from basics.
Raghavendra R Assistant Professor School of CS & IT 2
Introduction
• A class is a virtual entity and can be seen as a blueprint of an
object.
Ex:
• Suppose a class is a prototype of a building. A building
contains all the details about the floor, doors, windows, etc. we
can make as many buildings as we want, based on these
details. Hence, the building can be seen as a class, and we can
create as many objects of this class.
• On the other hand, the object is the instance of a class. The
process of creating an object can be called as instantiation.
Raghavendra R Assistant Professor School of CS & IT 3
Class & Object
Unit 1
Programming
Fundamentals
• A class can be created by using the keyword class followed by
the class name.
Syntax
class ClassName:
#statement_suite
• We must notice that each class is associated with a
documentation string which can be accessed by using <class-
name>.__doc__.
• A class contains a statement suite including fields, constructor,
function, etc. definition.
• Consider the following example to create a class Employee
which contains two fields as Employee id, and name.
Raghavendra R Assistant Professor School of CS & IT 4
Creating classes
Unit 1
Programming
Fundamentals
• The class also contains a function display() which is used to
display the information of the Employee.
Example
class Employee:
id = 10;
name = "ayush"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable which refers to the
current class object. It is always the first argument in the function
definition. However, using self is optional in the function call.
Raghavendra R Assistant Professor School of CS & IT 5
Creating classes
Unit 1
Programming
Fundamentals
• A class needs to be instantiated if we want to use the class
attributes in another class or method.
• A class can be instantiated by calling the class using the class
name.
• The syntax to create the instance of the class is given below.
<object-name> = <class-name>(<arguments>)
• The following example creates the instance of the class
Employee defined in the above example.
Raghavendra R Assistant Professor School of CS & IT 6
Instance of the class
Unit 1
Programming
Fundamentals
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
myobjecty = MyClass()
myobjecty.variable = "yackity"
# Then print out both values
print(myobjectx.variable)
print(myobjecty.variable)
Raghavendra R Assistant Professor School of CS & IT 7
Instance of the class
Unit 1
Programming
Fundamentals
class MyClass:
variable = "blah"
id = 10
def function(self):
print("This is a message inside the class.")
print("ID: %d nName: %s"%(self.id,self.variable))
myobjectx = MyClass()
myobjectx.function()
Raghavendra R Assistant Professor School of CS & IT 8
Accessing Object Functions
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 9
Built-in Functions
Unit 1
Programming
Fundamentals
abs() Function
• The python abs() function is used to return the absolute value of a number.
all() Function
• The python all() function accepts an iterable object (such as list, dictionary,
etc.). It returns true if all items in passed iterable are true. Otherwise, it
returns False.
bin() Function
• The python bin() function is used to return the binary representation of a
specified integer.
compile() Function
• The python compile() function takes source code as input and returns a
code object which can later be executed by exec() function.
Raghavendra R Assistant Professor School of CS & IT 10
Built-in Functions
Unit 1
Programming
Fundamentals
format() Function
• The python format() function returns a formatted representation of the
given value.
object()
• The python object() returns an empty object. It is a base for all the classes
and holds the built-in properties and methods which are default for all the
classes.
slice() Function
• Python slice() function is used to get a slice of elements from the collection
of elements.
tuple() Function
• The python tuple() function is used to create a tuple object.
Raghavendra R Assistant Professor School of CS & IT 11
Built-in Functions
Unit 1
Programming
Fundamentals
• Number data types store numeric values.
• They are immutable data types, means that changing the value
of a number data type results in a newly allocated object.
• Number objects are created when you assign a value to them.
For example −
– var1 = 1
– var2 = 10
• You can delete a single object or multiple objects by using
the del statement. For example −
– del var
– del var_a, var_b
Raghavendra R Assistant Professor School of CS & IT 12
Numbers
Unit 1
Programming
Fundamentals
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
Raghavendra R Assistant Professor School of CS & IT 13
Numbers
Unit 1
Programming
Fundamentals
• Python converts numbers internally in an expression containing mixed
types to a common type for evaluation.
• But sometimes, you need to coerce a number explicitly from one type to
another to satisfy the requirements of an operator or function parameter.
• Type int(x) to convert x to a plain integer.
• Type long(x) to convert x to a long integer.
• Type float(x) to convert x to a floating-point number.
• Type complex(x) to convert x to a complex number with real part x and
imaginary part zero.
• Type complex(x, y) to convert x and y to a complex number with real part
x and imaginary part y. x and y are numeric expressions
Raghavendra R Assistant Professor School of CS & IT 14
Number Type Conversion
Unit 1
Programming
Fundamentals
• A string is a sequence of one or more characters (letters,
numbers, symbols) that can be either a constant or a variable.
• Strings exist within either single quotes ' or double quotes " in
Python, so to create a string, enclose a sequence of characters
in quotes:
'This is a string in single quotes.'
"This is a string in double quotes.“
• You can choose to use either single quotes or double quotes,
but whichever you decide on you should be consistent within a
program.
•
Raghavendra R Assistant Professor School of CS & IT 15
Strings
Unit 1
Programming
Fundamentals
• The simple program “Hello, World!” demonstrates how a string can be
used in computer programming, as the characters that make up the
phrase Hello, World! are a string.
print("Hello, World!")
• As with other data types, we can store strings in variables:
hw = "Hello, World!"
• And print out the string by calling the variable:
print(hw)
Ouput
Hello, World!
Raghavendra R Assistant Professor School of CS & IT 16
Strings
Unit 1
Programming
Fundamentals
• Strings can be created by enclosing characters inside a single
quote or double quotes.
• Even triple quotes can be used in Python but generally used to
represent multiline strings and docstrings.
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
Raghavendra R Assistant Professor School of CS & IT 17
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 18
access characters in a string
Unit 1
Programming
Fundamentals
• We can access individual characters using indexing and a range of
characters using slicing.
• Index starts from 0.
• Trying to access a character out of index range will raise an IndexError.
• The index must be an integer. We can't use float or other types, this will
result into TypeError.
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and so on.
• We can access a range of items in a string by using the slicing operator
(colon ).
• str = 'programiz'
• print('str = ', str)
•
• #first character
• print('str[0] = ', str[0])
•
• #last character
• print('str[-1] = ', str[-1])
•
• #slicing 2nd to 5th character
• print('str[1:5] = ', str[1:5])
•
• #slicing 6th to 2nd last character
• print('str[5:-2] = ', str[5:-2])).
Raghavendra R Assistant Professor School of CS & IT 19
access characters in a string
Unit 1
Programming
Fundamentals
• Joining of two or more strings into a single one is called concatenation.
• The + operator does this in Python. Simply writing two string literals
together also concatenates them.
• The * operator can be used to repeat the string for a given number of times.
str1 = 'Hello‘
str2 ='World!‘
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Raghavendra R Assistant Professor School of CS & IT 20
Concatenation of Two or More Strings
Unit 1
Programming
Fundamentals
• Various built-in functions that work with sequence, works with
string as well.
• Some of the commonly used ones are enumerate() and len().
• The enumerate() function returns an enumerate object.
• It contains the index and value of all the items in the string as
pairs. This can be useful for iteration.
• Similarly, len() returns the length (number of characters) of the
string.
Raghavendra R Assistant Professor School of CS & IT 21
Built-in functions to Work
Unit 1
Programming
Fundamentals
str = 'cold‘
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
Raghavendra R Assistant Professor School of CS & IT 22
Built-in functions to Work
Unit 1
Programming
Fundamentals
Escape Sequence
• If we want to print a text like -He said, "What's there?"- we
can neither use single quote or double quotes.
• This will result into SyntaxError as the text itself contains both
single and double quotes.
Raghavendra R Assistant Professor School of CS & IT 23
String Formatting
Unit 1
Programming
Fundamentals
One way to get
around this problem
is to use triple quotes.
Alternatively, we can
use escape
sequences.
• An escape sequence starts with a backslash and is interpreted
differently.
• If we use single quote to represent a string, all the single
quotes inside the string must be escaped.
• Similar is the case with double quotes.
• Here is how it can be done to represent the above text.
# using triple quotes
print('''He said, "What's there?"''')
# escaping single quotes
print('He said, "What's there?"')
# escaping double quotes
print("He said, "What's there?"")
Raghavendra R Assistant Professor School of CS & IT 24
String Formatting
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 25
Escape Sequence in Python
Unit 1
Programming
Fundamentals
• Sometimes we may wish to ignore the escape sequences inside
a string.
• To do this we can place r or R in front of the string.
• This will imply that it is a raw string and any escape sequence
inside it will be ignored.
Raghavendra R Assistant Professor School of CS & IT 26
Raw String to ignore escape sequence
Unit 1
Programming
Fundamentals
• The format() method that is available with the string object is
very versatile and powerful in formatting strings.
• Format strings contains curly braces {} as placeholders or
replacement fields which gets replaced.
• We can use positional arguments or keyword arguments to
specify the order.
Raghavendra R Assistant Professor School of CS & IT 27
format() Method for Formatting
Strings
Unit 1
Programming
Fundamentals
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('n--- Default Order ---')
print(default_order)
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('n--- Positional Order ---')
print(positional_order)
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('n--- Keyword Order ---')
print(keyword_order)
Raghavendra R Assistant Professor School of CS & IT 28
format() Method for Formatting
Strings
Unit 1
Programming
Fundamentals
if condition1:
code_block1
elif condition2:
code_block2
else:
code_block3
num = 42
if num == 42: # condition
print("number is 42") # direction
Raghavendra R Assistant Professor School of CS & IT 29
If condition
Unit 1
Programming
Fundamentals
num = 43
if num == 42:
print("number is 42")
else:
print("number if not 42“)
num = 44
if num == 42:
print("number is 42")
elif num == 44:
print("num is 44")
else:
print("num is neither 42 nor 44")
Raghavendra R Assistant Professor School of CS & IT 30
If condition
Unit 1
Programming
Fundamentals
Working on items of the iterable
• If you want to run an operation on a collection of items, then
you can do it using for loops.
• The skeleton for using the for loop is shown below.
• Note that the for statement line will end with a colon : and the
rest of the code block must be indented with a spacing of 4
spaces.
• An iterable is any object that can be looped on such as list,
tuple, string etc.
Raghavendra R Assistant Professor School of CS & IT 31
Loops
Unit 1
Programming
Fundamentals
>>> fruits = ["apples", "oranges", "mangoes"]
>>> for fruit in fruits:
... print(fruit)
apples
oranges
mangoes
Raghavendra R Assistant Professor School of CS & IT 32
Unit 1
Programming
Fundamentals
• In the previous section, index or the place value of the item in
the iterable was not considered.
• However, if you are interested in working with the index, then
you can call the enumerate function which returns a tuple of
the index and the item.
• Taking the example above, you can print the name of the fruit
and the index of the list of fruits.
fruits = ["apples", "oranges", "mangoes"]
>>> for index, fruit in enumerate(fruits):
print("index is %s" % index)
print("fruit is %s" % fruit)
print("###########################")
Raghavendra R Assistant Professor School of CS & IT 33
Looping on both indexes and items
Unit 1
Programming
Fundamentals
• The while statement will execute a block of code as long as the
condition is true.
• The skeleton of a while block is shown below.
while condition:
code_block
• Note that similar to the for loop, the while statement ends with
a colon : and the remaining code block is indented by 4 spaces.
• We can implement the fruit example in the while block as well,
although the logic becomes a bit complicated than the for
block.
Raghavendra R Assistant Professor School of CS & IT 34
While statement
Unit 1
Programming
Fundamentals
>>> fruits = ["apples", "oranges", "mangoes"] # get the list
>>> length = len(fruits) # get the length that will be needed for
the while condition
>>> i = 0 # initialise a counter
>>> while i < length: # give the condition
... print(fruits[i]) # the code block
... i += 1 # increment the counter
Raghavendra R Assistant Professor School of CS & IT 35
Unit 1
Programming
Fundamentals
• You can have one or more nested for loops. For example, look
at the following example where you can print the
multiplication table.
• The table is shown only for 1 and 2 to save space. You can try
for the remaining digits.
>>> for i in range(1,3):
for j in range(1,3):
print('%d x %d = %d' % (i, j, i*j))
Raghavendra R Assistant Professor School of CS & IT 36
Nested for loops
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 37
String Functions
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 38
String Functions
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 39
String Functions
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 40
String Functions
Unit 1
Programming
Fundamentals
len(string)
• len or length function is used to find the character length of any string.
• len returns a number and it takes a string as an argument.
For Example,
>>> s = "Hello"
>>> len(s)
string_name.lower()
• lower() function is used to convert all the uppercase characters present in a
string into lowercase.
• It takes a string as the function input, however the string is not passed as
argument. This function returns a string as well.
>>> print "Hello, World".lower()
hello, world
Raghavendra R Assistant Professor School of CS & IT 41
String Functions
Unit 1
Programming
Fundamentals
find(subString)
• In case you want to find the position of any character or of a subString
within any given string, you can use the find function.
• To find a subString in a string, we will have to provide both the main string
and the subString to be found, to the function. For Example,
>>> s = "Hello"
>>> ss = "He"
>>> print s.find(ss)
0
• Since, He is present at the beginning of the string Hello, hence index 0 is
returned as the result. It can be directly implemented/used as follows(in
case you hate useless typing; which every programmer do):
>>> print "Hello".find("He")
0
Raghavendra R Assistant Professor School of CS & IT 42
String Functions
Unit 1
Programming
Fundamentals
string_name.upper()
• upper() is used to turn all the characters in a string to uppercase.
>>> print "Hello, World".upper()
HELLO, WORLD
string_name.islower()
• islower() is used to check if string_name string is in lowercase or not.
• This functions returns a boolean value as result, either True or False.
>>> print "hello, world".islower()
True
>>> print "Hello, World".islower()
False
Raghavendra R Assistant Professor School of CS & IT 43
String Functions
Unit 1
Programming
Fundamentals
string_name.isupper()
• isupper() is used to check if the given string is in uppercase or not.
• This function also returns a boolean value as result, either True or False.
>>> print "HELLO, WORLD".isupper()
True
>>> print "Hello, World".isupper()
False
string_name.replace(old_string, new_string)
• replace() function will first of all take a string as input, and ask for some
subString within it as the first argument and ask for another string to
replace that subString as the second argument. For Example,
>>> print "Hello, World".replace("World", "India")
Hello, India
Raghavendra R Assistant Professor School of CS & IT 44
String Functions
Unit 1
Programming
Fundamentals
string_name.split(character, integer)
• Suppose you're having a string say,
>>> mystring = "Hello World! Welcome to the Python tutorial“
• Now we can use the split() function to split the above declared string.
• If we choose to split the string into two substring from the exclamation
mark !. We can do that by putting an exclamation mark ! in the character
argument.
• It will basically split the string into different parts depending upon the
number of exclamation marks ! in the string.
• All the sub-pieces of the string will be stored in a list. Like,
>>> print(mystring.split("!"))
['Hello World', ' Welcome to the Python tutorial']
Raghavendra R Assistant Professor School of CS & IT 45
String Functions
Unit 1
Programming
Fundamentals
• You can store these values to another variable and access each element of it
like this:
>>> myNEWstring = mystring.split("!")
>>> print myNEWstring[0]
>>> print myNEWstring[1]
Hello World
Welcome to the Python tutorial
Raghavendra R Assistant Professor School of CS & IT 46
String Functions
Unit 1
Programming
Fundamentals
• Python String join() function - returns a string that is the concatenation of
the strings in iterable with string object as a delimiter.
• Python String join() function syntax is:
str_object.join(iterable)
• The iterable elements must be a string, otherwise TypeError will be raised.
• The separator between elements is the string providing this method.
• The string object can have multiple characters too.
•
• s = 'abc'
• s1 = s.join('xyz')
• print(s1)
• Output: xabcyabcz
Raghavendra R Assistant Professor School of CS & IT 47
String Functions
Unit 1
Programming
Fundamentals
Trim String
• strip(): returns a new string after removing any leading and trailing
whitespaces including tabs (t).
• rstrip(): returns a new string with trailing whitespace removed. It’s easier
to remember as removing white spaces from “right” side of the string.
• lstrip(): returns a new string with leading whitespace removed, or
removing whitespaces from the “left” side of the string.
• All of these methods don’t accept any arguments to remove whitespaces. If
a character argument is provided, then they will remove that characters
from the string from leading and trailing places.
Raghavendra R Assistant Professor School of CS & IT 48
String Functions
Unit 1
Programming
Fundamentals
• s1 = ' abc '
• print(f'String ='{s1}'')
• print(f'After Removing Leading Whitespaces String ='{s1.lstrip()}'')
• print(f'After Removing Trailing Whitespaces String ='{s1.rstrip()}'')
• print(f'After Trimming Whitespaces String ='{s1.strip()}'')
Output:
• String =' abc '
• After Removing Leading Whitespaces String ='abc '
• After Removing Trailing Whitespaces String =' abc'
• After Trimming Whitespaces String ='abc'
Raghavendra R Assistant Professor School of CS & IT 49
String Functions
Unit 1
Programming
Fundamentals
• A Functions in Python are used to utilize the code in more than
one place in a program, sometimes also called method or
procedures.
• Python provides you many inbuilt functions like print(), but it
also gives freedom to create your own functions.
How to define and call a function in Python
• Function in Python is defined by the "def " statement
followed by the function name and parentheses ( () )
Raghavendra R Assistant Professor School of CS & IT 50
Function
Unit 1
Programming
Fundamentals
• Let us define a function by using the command " def func1():" and call the
function. The output of the function will be "I am learning Python
function".
•
• The function print func1() calls our def func1(): and print the command " I
am learning Python function None."
Raghavendra R Assistant Professor School of CS & IT 51
Function
Unit 1
Programming
Fundamentals
• There are set of rules in Python to define a function.
• Any args or input parameters should be placed within these parentheses
• The function first statement can be an optional statement- docstring or the
documentation string of the function
• The code within every function starts with a colon (:) and should be
indented (space)
• The statement return (expression) exits a function, optionally passing back
a value to the caller. A return statement with no args is the same as return
None.
Raghavendra R Assistant Professor School of CS & IT 52
Function
Unit 1
Programming
Fundamentals
• Python functions don't have any explicit begin or end like curly braces to
indicate the start and stop for the function, they have to rely on indentation.
• Here we take a simple example with "print" command. When we write
"print" function right below the def func 1 (): It will show an "indentation
error: expected an indented block".
Raghavendra R Assistant Professor School of CS & IT 53
Significance of Indentation (Space) in Python
Unit 1
Programming
Fundamentals
• Now, when you add the indent (space) in front of "print" function, it should
print as expected.
• At least, one indent is enough to make your code work successfully. But as
a best practice it is advisable to leave about 3-4 indent to call your function.
Raghavendra R Assistant Professor School of CS & IT 54
Significance of Indentation (Space) in Python
Unit 1
Programming
Fundamentals
• It is also necessary that while declaring indentation, you have to maintain
the same indent for the rest of your code.
• For example, in below screen shot when we call another statement "still in
func1" and when it is not declared right below the first print statement it
will show an indentation error "unindent does not match any other
indentation level.“
Raghavendra R Assistant Professor School of CS & IT 55
Significance of Indentation (Space) in Python
Unit 1
Programming
Fundamentals
• Now, when we apply same indentation for both the statements
and align them in the same line, it gives the expected output.
Raghavendra R Assistant Professor School of CS & IT 56
Significance of Indentation (Space) in Python
Unit 1
Programming
Fundamentals
• Return command in Python specifies what value to give back to the caller
of the function.
• Let's understand this with the following example
• Step 1) Here - we see when function is not "return". For example, we want
the square of 4, and it should give answer "16" when the code is executed.
Which it gives when we simply use "print x*x" code, but when you call
function "print square" it gives "None" as an output.
• This is because when you call the function, recursion does not happen and
fall off the end of the function. Python returns "None" for failing off the
end of the function.
Raghavendra R Assistant Professor School of CS & IT 57
How Function Return Value?
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 58
How Function Return Value?
Unit 1
Programming
Fundamentals
Step 2) To make this clearer we replace the print command with
assignment command. Let's check the output.
When you run the command "print square (4)" it actually returns
the value of the object since we don't have any specific function
to run over here it returns "None".
Raghavendra R Assistant Professor School of CS & IT 59
How Function Return Value?
Unit 1
Programming
Fundamentals
Step 3) Now, here we will see how to retrieve the output using "return"
command. When you use the "return" function and execute the code, it will
give the output "16."
Raghavendra R Assistant Professor School of CS & IT 60
How Function Return Value?
Unit 1
Programming
Fundamentals
• Step 4) Functions in Python are themselves an object, and an object has
some value. We will here see how Python treats an object. When you run
the command "print square" it returns the value of the object.
Raghavendra R Assistant Professor School of CS & IT 61
How Function Return Value?
Unit 1
Programming
Fundamentals
• The argument is a value that is passed to the function when it's called.
• In other words on the calling side, it is an argument and on the function
side it is a parameter.
• Let see how Python Args works -
Step 1) Arguments are declared in the function definition. While calling the
function, you can pass the values for that args as shown below
Raghavendra R Assistant Professor School of CS & IT 62
Arguments in Functions
Unit 1
Programming
Fundamentals
• Step 2) To declare a default value of an argument, assign it a value at
function definition.
• Example: x has no default values. Default values of y=0. When we supply
only one argument while calling multiply function, Python assigns the
supplied value to x while keeping the value of y=0. Hence the multiply of
x*y=0
Raghavendra R Assistant Professor School of CS & IT 63
Arguments in Functions
Unit 1
Programming
Fundamentals
• Step 3) This time we will change the value to y=2 instead of
the default value y=0, and it will return the output as (4x2)=8.
Raghavendra R Assistant Professor School of CS & IT 64
Arguments in Functions
Unit 1
Programming
Fundamentals
Step 4) You can also change the order in which the arguments can be passed in
Python. Here we have reversed the order of the value x and y to x=4 and y=2.
Raghavendra R Assistant Professor School of CS & IT 65
Arguments in Functions
Unit 1
Programming
Fundamentals
Step 5) Multiple Arguments can also be passed as an array. Here in the
example we call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the
(*args) function; it prints out the output as (1,2,3,4,5)
Raghavendra R Assistant Professor School of CS & IT 66
Arguments in Functions
Unit 1
Programming
Fundamentals
Raghavendra R Assistant Professor School of CS & IT 67
Unit 1
Programming
Fundamentals

More Related Content

Similar to Module 1 - Programming Fundamentals.pptx

Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Introduction to phython programming
Introduction to phython programmingIntroduction to phython programming
Introduction to phython programmingASIT Education
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptxsangeeta borde
 
Python lab basics
Python lab basicsPython lab basics
Python lab basicsAbi_Kasi
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
Blueprints: Introduction to Python programming
Blueprints: Introduction to Python programmingBlueprints: Introduction to Python programming
Blueprints: Introduction to Python programmingBhalaji Nagarajan
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfKosmikTech1
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptxMohammedAlYemeni1
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfMichpice
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha BaliAkanksha Bali
 

Similar to Module 1 - Programming Fundamentals.pptx (20)

Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
C
CC
C
 
Introduction to phython programming
Introduction to phython programmingIntroduction to phython programming
Introduction to phython programming
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Blueprints: Introduction to Python programming
Blueprints: Introduction to Python programmingBlueprints: Introduction to Python programming
Blueprints: Introduction to Python programming
 
Python
PythonPython
Python
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
Python
PythonPython
Python
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
advance-dart.pptx
advance-dart.pptxadvance-dart.pptx
advance-dart.pptx
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
 
Python basics
Python basicsPython basics
Python basics
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Module 1 - Programming Fundamentals.pptx

  • 1. Module 1 Programming Fundamentals 1 22MCSIT201 – Python Programming Master of Science in Computer Science & Information Technology [MSc-CSIT]
  • 2. Unit 1 Programming Fundamentals • Python is an object-oriented programming language created by Guido Rossum in 1989. • It is ideally designed for rapid prototyping of complex applications. • Many large companies use the Python programming language include NASA, Google, YouTube, BitTorrent, etc. • Python programming is widely used in Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields of Computer Science. • Python had deep focus on code readability & this class will teach you python from basics. Raghavendra R Assistant Professor School of CS & IT 2 Introduction
  • 3. • A class is a virtual entity and can be seen as a blueprint of an object. Ex: • Suppose a class is a prototype of a building. A building contains all the details about the floor, doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the building can be seen as a class, and we can create as many objects of this class. • On the other hand, the object is the instance of a class. The process of creating an object can be called as instantiation. Raghavendra R Assistant Professor School of CS & IT 3 Class & Object Unit 1 Programming Fundamentals
  • 4. • A class can be created by using the keyword class followed by the class name. Syntax class ClassName: #statement_suite • We must notice that each class is associated with a documentation string which can be accessed by using <class- name>.__doc__. • A class contains a statement suite including fields, constructor, function, etc. definition. • Consider the following example to create a class Employee which contains two fields as Employee id, and name. Raghavendra R Assistant Professor School of CS & IT 4 Creating classes Unit 1 Programming Fundamentals
  • 5. • The class also contains a function display() which is used to display the information of the Employee. Example class Employee: id = 10; name = "ayush" def display (self): print(self.id,self.name) Here, the self is used as a reference variable which refers to the current class object. It is always the first argument in the function definition. However, using self is optional in the function call. Raghavendra R Assistant Professor School of CS & IT 5 Creating classes Unit 1 Programming Fundamentals
  • 6. • A class needs to be instantiated if we want to use the class attributes in another class or method. • A class can be instantiated by calling the class using the class name. • The syntax to create the instance of the class is given below. <object-name> = <class-name>(<arguments>) • The following example creates the instance of the class Employee defined in the above example. Raghavendra R Assistant Professor School of CS & IT 6 Instance of the class Unit 1 Programming Fundamentals
  • 7. class MyClass: variable = "blah" def function(self): print("This is a message inside the class.") myobjectx = MyClass() myobjecty = MyClass() myobjecty.variable = "yackity" # Then print out both values print(myobjectx.variable) print(myobjecty.variable) Raghavendra R Assistant Professor School of CS & IT 7 Instance of the class Unit 1 Programming Fundamentals
  • 8. class MyClass: variable = "blah" id = 10 def function(self): print("This is a message inside the class.") print("ID: %d nName: %s"%(self.id,self.variable)) myobjectx = MyClass() myobjectx.function() Raghavendra R Assistant Professor School of CS & IT 8 Accessing Object Functions Unit 1 Programming Fundamentals
  • 9. Raghavendra R Assistant Professor School of CS & IT 9 Built-in Functions Unit 1 Programming Fundamentals
  • 10. abs() Function • The python abs() function is used to return the absolute value of a number. all() Function • The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if all items in passed iterable are true. Otherwise, it returns False. bin() Function • The python bin() function is used to return the binary representation of a specified integer. compile() Function • The python compile() function takes source code as input and returns a code object which can later be executed by exec() function. Raghavendra R Assistant Professor School of CS & IT 10 Built-in Functions Unit 1 Programming Fundamentals
  • 11. format() Function • The python format() function returns a formatted representation of the given value. object() • The python object() returns an empty object. It is a base for all the classes and holds the built-in properties and methods which are default for all the classes. slice() Function • Python slice() function is used to get a slice of elements from the collection of elements. tuple() Function • The python tuple() function is used to create a tuple object. Raghavendra R Assistant Professor School of CS & IT 11 Built-in Functions Unit 1 Programming Fundamentals
  • 12. • Number data types store numeric values. • They are immutable data types, means that changing the value of a number data type results in a newly allocated object. • Number objects are created when you assign a value to them. For example − – var1 = 1 – var2 = 10 • You can delete a single object or multiple objects by using the del statement. For example − – del var – del var_a, var_b Raghavendra R Assistant Professor School of CS & IT 12 Numbers Unit 1 Programming Fundamentals
  • 13. int long float complex 10 51924361L 0.0 3.14j 100 -0x19323L 15.20 45.j -786 0122L -21.9 9.322e-36j 080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j -0490 535633629843L -90. -.6545+0J -0x260 -052318172735L -32.54e100 3e+26J 0x69 -4721885298529L 70.2-E12 4.53e-7j Raghavendra R Assistant Professor School of CS & IT 13 Numbers Unit 1 Programming Fundamentals
  • 14. • Python converts numbers internally in an expression containing mixed types to a common type for evaluation. • But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter. • Type int(x) to convert x to a plain integer. • Type long(x) to convert x to a long integer. • Type float(x) to convert x to a floating-point number. • Type complex(x) to convert x to a complex number with real part x and imaginary part zero. • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions Raghavendra R Assistant Professor School of CS & IT 14 Number Type Conversion Unit 1 Programming Fundamentals
  • 15. • A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. • Strings exist within either single quotes ' or double quotes " in Python, so to create a string, enclose a sequence of characters in quotes: 'This is a string in single quotes.' "This is a string in double quotes.“ • You can choose to use either single quotes or double quotes, but whichever you decide on you should be consistent within a program. • Raghavendra R Assistant Professor School of CS & IT 15 Strings Unit 1 Programming Fundamentals
  • 16. • The simple program “Hello, World!” demonstrates how a string can be used in computer programming, as the characters that make up the phrase Hello, World! are a string. print("Hello, World!") • As with other data types, we can store strings in variables: hw = "Hello, World!" • And print out the string by calling the variable: print(hw) Ouput Hello, World! Raghavendra R Assistant Professor School of CS & IT 16 Strings Unit 1 Programming Fundamentals
  • 17. • Strings can be created by enclosing characters inside a single quote or double quotes. • Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings. # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string) Raghavendra R Assistant Professor School of CS & IT 17 Unit 1 Programming Fundamentals
  • 18. Raghavendra R Assistant Professor School of CS & IT 18 access characters in a string Unit 1 Programming Fundamentals • We can access individual characters using indexing and a range of characters using slicing. • Index starts from 0. • Trying to access a character out of index range will raise an IndexError. • The index must be an integer. We can't use float or other types, this will result into TypeError. • Python allows negative indexing for its sequences. • The index of -1 refers to the last item, -2 to the second last item and so on. • We can access a range of items in a string by using the slicing operator (colon ).
  • 19. • str = 'programiz' • print('str = ', str) • • #first character • print('str[0] = ', str[0]) • • #last character • print('str[-1] = ', str[-1]) • • #slicing 2nd to 5th character • print('str[1:5] = ', str[1:5]) • • #slicing 6th to 2nd last character • print('str[5:-2] = ', str[5:-2])). Raghavendra R Assistant Professor School of CS & IT 19 access characters in a string Unit 1 Programming Fundamentals
  • 20. • Joining of two or more strings into a single one is called concatenation. • The + operator does this in Python. Simply writing two string literals together also concatenates them. • The * operator can be used to repeat the string for a given number of times. str1 = 'Hello‘ str2 ='World!‘ # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3) Raghavendra R Assistant Professor School of CS & IT 20 Concatenation of Two or More Strings Unit 1 Programming Fundamentals
  • 21. • Various built-in functions that work with sequence, works with string as well. • Some of the commonly used ones are enumerate() and len(). • The enumerate() function returns an enumerate object. • It contains the index and value of all the items in the string as pairs. This can be useful for iteration. • Similarly, len() returns the length (number of characters) of the string. Raghavendra R Assistant Professor School of CS & IT 21 Built-in functions to Work Unit 1 Programming Fundamentals
  • 22. str = 'cold‘ # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str)) Raghavendra R Assistant Professor School of CS & IT 22 Built-in functions to Work Unit 1 Programming Fundamentals
  • 23. Escape Sequence • If we want to print a text like -He said, "What's there?"- we can neither use single quote or double quotes. • This will result into SyntaxError as the text itself contains both single and double quotes. Raghavendra R Assistant Professor School of CS & IT 23 String Formatting Unit 1 Programming Fundamentals One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
  • 24. • An escape sequence starts with a backslash and is interpreted differently. • If we use single quote to represent a string, all the single quotes inside the string must be escaped. • Similar is the case with double quotes. • Here is how it can be done to represent the above text. # using triple quotes print('''He said, "What's there?"''') # escaping single quotes print('He said, "What's there?"') # escaping double quotes print("He said, "What's there?"") Raghavendra R Assistant Professor School of CS & IT 24 String Formatting Unit 1 Programming Fundamentals
  • 25. Raghavendra R Assistant Professor School of CS & IT 25 Escape Sequence in Python Unit 1 Programming Fundamentals
  • 26. • Sometimes we may wish to ignore the escape sequences inside a string. • To do this we can place r or R in front of the string. • This will imply that it is a raw string and any escape sequence inside it will be ignored. Raghavendra R Assistant Professor School of CS & IT 26 Raw String to ignore escape sequence Unit 1 Programming Fundamentals
  • 27. • The format() method that is available with the string object is very versatile and powerful in formatting strings. • Format strings contains curly braces {} as placeholders or replacement fields which gets replaced. • We can use positional arguments or keyword arguments to specify the order. Raghavendra R Assistant Professor School of CS & IT 27 format() Method for Formatting Strings Unit 1 Programming Fundamentals
  • 28. # default(implicit) order default_order = "{}, {} and {}".format('John','Bill','Sean') print('n--- Default Order ---') print(default_order) # order using positional argument positional_order = "{1}, {0} and {2}".format('John','Bill','Sean') print('n--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean') print('n--- Keyword Order ---') print(keyword_order) Raghavendra R Assistant Professor School of CS & IT 28 format() Method for Formatting Strings Unit 1 Programming Fundamentals
  • 29. if condition1: code_block1 elif condition2: code_block2 else: code_block3 num = 42 if num == 42: # condition print("number is 42") # direction Raghavendra R Assistant Professor School of CS & IT 29 If condition Unit 1 Programming Fundamentals
  • 30. num = 43 if num == 42: print("number is 42") else: print("number if not 42“) num = 44 if num == 42: print("number is 42") elif num == 44: print("num is 44") else: print("num is neither 42 nor 44") Raghavendra R Assistant Professor School of CS & IT 30 If condition Unit 1 Programming Fundamentals
  • 31. Working on items of the iterable • If you want to run an operation on a collection of items, then you can do it using for loops. • The skeleton for using the for loop is shown below. • Note that the for statement line will end with a colon : and the rest of the code block must be indented with a spacing of 4 spaces. • An iterable is any object that can be looped on such as list, tuple, string etc. Raghavendra R Assistant Professor School of CS & IT 31 Loops Unit 1 Programming Fundamentals
  • 32. >>> fruits = ["apples", "oranges", "mangoes"] >>> for fruit in fruits: ... print(fruit) apples oranges mangoes Raghavendra R Assistant Professor School of CS & IT 32 Unit 1 Programming Fundamentals
  • 33. • In the previous section, index or the place value of the item in the iterable was not considered. • However, if you are interested in working with the index, then you can call the enumerate function which returns a tuple of the index and the item. • Taking the example above, you can print the name of the fruit and the index of the list of fruits. fruits = ["apples", "oranges", "mangoes"] >>> for index, fruit in enumerate(fruits): print("index is %s" % index) print("fruit is %s" % fruit) print("###########################") Raghavendra R Assistant Professor School of CS & IT 33 Looping on both indexes and items Unit 1 Programming Fundamentals
  • 34. • The while statement will execute a block of code as long as the condition is true. • The skeleton of a while block is shown below. while condition: code_block • Note that similar to the for loop, the while statement ends with a colon : and the remaining code block is indented by 4 spaces. • We can implement the fruit example in the while block as well, although the logic becomes a bit complicated than the for block. Raghavendra R Assistant Professor School of CS & IT 34 While statement Unit 1 Programming Fundamentals
  • 35. >>> fruits = ["apples", "oranges", "mangoes"] # get the list >>> length = len(fruits) # get the length that will be needed for the while condition >>> i = 0 # initialise a counter >>> while i < length: # give the condition ... print(fruits[i]) # the code block ... i += 1 # increment the counter Raghavendra R Assistant Professor School of CS & IT 35 Unit 1 Programming Fundamentals
  • 36. • You can have one or more nested for loops. For example, look at the following example where you can print the multiplication table. • The table is shown only for 1 and 2 to save space. You can try for the remaining digits. >>> for i in range(1,3): for j in range(1,3): print('%d x %d = %d' % (i, j, i*j)) Raghavendra R Assistant Professor School of CS & IT 36 Nested for loops Unit 1 Programming Fundamentals
  • 37. Raghavendra R Assistant Professor School of CS & IT 37 String Functions Unit 1 Programming Fundamentals
  • 38. Raghavendra R Assistant Professor School of CS & IT 38 String Functions Unit 1 Programming Fundamentals
  • 39. Raghavendra R Assistant Professor School of CS & IT 39 String Functions Unit 1 Programming Fundamentals
  • 40. Raghavendra R Assistant Professor School of CS & IT 40 String Functions Unit 1 Programming Fundamentals
  • 41. len(string) • len or length function is used to find the character length of any string. • len returns a number and it takes a string as an argument. For Example, >>> s = "Hello" >>> len(s) string_name.lower() • lower() function is used to convert all the uppercase characters present in a string into lowercase. • It takes a string as the function input, however the string is not passed as argument. This function returns a string as well. >>> print "Hello, World".lower() hello, world Raghavendra R Assistant Professor School of CS & IT 41 String Functions Unit 1 Programming Fundamentals
  • 42. find(subString) • In case you want to find the position of any character or of a subString within any given string, you can use the find function. • To find a subString in a string, we will have to provide both the main string and the subString to be found, to the function. For Example, >>> s = "Hello" >>> ss = "He" >>> print s.find(ss) 0 • Since, He is present at the beginning of the string Hello, hence index 0 is returned as the result. It can be directly implemented/used as follows(in case you hate useless typing; which every programmer do): >>> print "Hello".find("He") 0 Raghavendra R Assistant Professor School of CS & IT 42 String Functions Unit 1 Programming Fundamentals
  • 43. string_name.upper() • upper() is used to turn all the characters in a string to uppercase. >>> print "Hello, World".upper() HELLO, WORLD string_name.islower() • islower() is used to check if string_name string is in lowercase or not. • This functions returns a boolean value as result, either True or False. >>> print "hello, world".islower() True >>> print "Hello, World".islower() False Raghavendra R Assistant Professor School of CS & IT 43 String Functions Unit 1 Programming Fundamentals
  • 44. string_name.isupper() • isupper() is used to check if the given string is in uppercase or not. • This function also returns a boolean value as result, either True or False. >>> print "HELLO, WORLD".isupper() True >>> print "Hello, World".isupper() False string_name.replace(old_string, new_string) • replace() function will first of all take a string as input, and ask for some subString within it as the first argument and ask for another string to replace that subString as the second argument. For Example, >>> print "Hello, World".replace("World", "India") Hello, India Raghavendra R Assistant Professor School of CS & IT 44 String Functions Unit 1 Programming Fundamentals
  • 45. string_name.split(character, integer) • Suppose you're having a string say, >>> mystring = "Hello World! Welcome to the Python tutorial“ • Now we can use the split() function to split the above declared string. • If we choose to split the string into two substring from the exclamation mark !. We can do that by putting an exclamation mark ! in the character argument. • It will basically split the string into different parts depending upon the number of exclamation marks ! in the string. • All the sub-pieces of the string will be stored in a list. Like, >>> print(mystring.split("!")) ['Hello World', ' Welcome to the Python tutorial'] Raghavendra R Assistant Professor School of CS & IT 45 String Functions Unit 1 Programming Fundamentals
  • 46. • You can store these values to another variable and access each element of it like this: >>> myNEWstring = mystring.split("!") >>> print myNEWstring[0] >>> print myNEWstring[1] Hello World Welcome to the Python tutorial Raghavendra R Assistant Professor School of CS & IT 46 String Functions Unit 1 Programming Fundamentals
  • 47. • Python String join() function - returns a string that is the concatenation of the strings in iterable with string object as a delimiter. • Python String join() function syntax is: str_object.join(iterable) • The iterable elements must be a string, otherwise TypeError will be raised. • The separator between elements is the string providing this method. • The string object can have multiple characters too. • • s = 'abc' • s1 = s.join('xyz') • print(s1) • Output: xabcyabcz Raghavendra R Assistant Professor School of CS & IT 47 String Functions Unit 1 Programming Fundamentals
  • 48. Trim String • strip(): returns a new string after removing any leading and trailing whitespaces including tabs (t). • rstrip(): returns a new string with trailing whitespace removed. It’s easier to remember as removing white spaces from “right” side of the string. • lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string. • All of these methods don’t accept any arguments to remove whitespaces. If a character argument is provided, then they will remove that characters from the string from leading and trailing places. Raghavendra R Assistant Professor School of CS & IT 48 String Functions Unit 1 Programming Fundamentals
  • 49. • s1 = ' abc ' • print(f'String ='{s1}'') • print(f'After Removing Leading Whitespaces String ='{s1.lstrip()}'') • print(f'After Removing Trailing Whitespaces String ='{s1.rstrip()}'') • print(f'After Trimming Whitespaces String ='{s1.strip()}'') Output: • String =' abc ' • After Removing Leading Whitespaces String ='abc ' • After Removing Trailing Whitespaces String =' abc' • After Trimming Whitespaces String ='abc' Raghavendra R Assistant Professor School of CS & IT 49 String Functions Unit 1 Programming Fundamentals
  • 50. • A Functions in Python are used to utilize the code in more than one place in a program, sometimes also called method or procedures. • Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions. How to define and call a function in Python • Function in Python is defined by the "def " statement followed by the function name and parentheses ( () ) Raghavendra R Assistant Professor School of CS & IT 50 Function Unit 1 Programming Fundamentals
  • 51. • Let us define a function by using the command " def func1():" and call the function. The output of the function will be "I am learning Python function". • • The function print func1() calls our def func1(): and print the command " I am learning Python function None." Raghavendra R Assistant Professor School of CS & IT 51 Function Unit 1 Programming Fundamentals
  • 52. • There are set of rules in Python to define a function. • Any args or input parameters should be placed within these parentheses • The function first statement can be an optional statement- docstring or the documentation string of the function • The code within every function starts with a colon (:) and should be indented (space) • The statement return (expression) exits a function, optionally passing back a value to the caller. A return statement with no args is the same as return None. Raghavendra R Assistant Professor School of CS & IT 52 Function Unit 1 Programming Fundamentals
  • 53. • Python functions don't have any explicit begin or end like curly braces to indicate the start and stop for the function, they have to rely on indentation. • Here we take a simple example with "print" command. When we write "print" function right below the def func 1 (): It will show an "indentation error: expected an indented block". Raghavendra R Assistant Professor School of CS & IT 53 Significance of Indentation (Space) in Python Unit 1 Programming Fundamentals
  • 54. • Now, when you add the indent (space) in front of "print" function, it should print as expected. • At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function. Raghavendra R Assistant Professor School of CS & IT 54 Significance of Indentation (Space) in Python Unit 1 Programming Fundamentals
  • 55. • It is also necessary that while declaring indentation, you have to maintain the same indent for the rest of your code. • For example, in below screen shot when we call another statement "still in func1" and when it is not declared right below the first print statement it will show an indentation error "unindent does not match any other indentation level.“ Raghavendra R Assistant Professor School of CS & IT 55 Significance of Indentation (Space) in Python Unit 1 Programming Fundamentals
  • 56. • Now, when we apply same indentation for both the statements and align them in the same line, it gives the expected output. Raghavendra R Assistant Professor School of CS & IT 56 Significance of Indentation (Space) in Python Unit 1 Programming Fundamentals
  • 57. • Return command in Python specifies what value to give back to the caller of the function. • Let's understand this with the following example • Step 1) Here - we see when function is not "return". For example, we want the square of 4, and it should give answer "16" when the code is executed. Which it gives when we simply use "print x*x" code, but when you call function "print square" it gives "None" as an output. • This is because when you call the function, recursion does not happen and fall off the end of the function. Python returns "None" for failing off the end of the function. Raghavendra R Assistant Professor School of CS & IT 57 How Function Return Value? Unit 1 Programming Fundamentals
  • 58. Raghavendra R Assistant Professor School of CS & IT 58 How Function Return Value? Unit 1 Programming Fundamentals
  • 59. Step 2) To make this clearer we replace the print command with assignment command. Let's check the output. When you run the command "print square (4)" it actually returns the value of the object since we don't have any specific function to run over here it returns "None". Raghavendra R Assistant Professor School of CS & IT 59 How Function Return Value? Unit 1 Programming Fundamentals
  • 60. Step 3) Now, here we will see how to retrieve the output using "return" command. When you use the "return" function and execute the code, it will give the output "16." Raghavendra R Assistant Professor School of CS & IT 60 How Function Return Value? Unit 1 Programming Fundamentals
  • 61. • Step 4) Functions in Python are themselves an object, and an object has some value. We will here see how Python treats an object. When you run the command "print square" it returns the value of the object. Raghavendra R Assistant Professor School of CS & IT 61 How Function Return Value? Unit 1 Programming Fundamentals
  • 62. • The argument is a value that is passed to the function when it's called. • In other words on the calling side, it is an argument and on the function side it is a parameter. • Let see how Python Args works - Step 1) Arguments are declared in the function definition. While calling the function, you can pass the values for that args as shown below Raghavendra R Assistant Professor School of CS & IT 62 Arguments in Functions Unit 1 Programming Fundamentals
  • 63. • Step 2) To declare a default value of an argument, assign it a value at function definition. • Example: x has no default values. Default values of y=0. When we supply only one argument while calling multiply function, Python assigns the supplied value to x while keeping the value of y=0. Hence the multiply of x*y=0 Raghavendra R Assistant Professor School of CS & IT 63 Arguments in Functions Unit 1 Programming Fundamentals
  • 64. • Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4x2)=8. Raghavendra R Assistant Professor School of CS & IT 64 Arguments in Functions Unit 1 Programming Fundamentals
  • 65. Step 4) You can also change the order in which the arguments can be passed in Python. Here we have reversed the order of the value x and y to x=4 and y=2. Raghavendra R Assistant Professor School of CS & IT 65 Arguments in Functions Unit 1 Programming Fundamentals
  • 66. Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the multiple args (1,2,3,4,5) by calling the (*args) function. Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function; it prints out the output as (1,2,3,4,5) Raghavendra R Assistant Professor School of CS & IT 66 Arguments in Functions Unit 1 Programming Fundamentals
  • 67. Raghavendra R Assistant Professor School of CS & IT 67 Unit 1 Programming Fundamentals