You are on page 1of 26

Module 1: Programming with Python (18MCA32) Page |1

Module 1
Introduction to Python Programming
1.1 Introduction to Python
Python is an easy to learn, powerful programming language. It has efficient high-level data
structures and a simple but effective approach to object-oriented programming. Python’s elegant
syntax and dynamic typing, together with its interpreted nature, make it an ideal language for
scripting and rapid application development in many areas on most platforms. The following are
the unique features of Python programming.

 Simple and Easy to Learn  Interpreted and Object Oriented


 Free and Open Source  Extensible
 High-level Language  Network/Web interfaceable
 Portable  Embeddable

1.2 Brackets, Braces, and Parentheses


One of the pieces of terminology that causes confusion is what to call certain characters. The
Python style guide use these names, so this notes does too:

() Parentheses
[] Brackets
{} Braces (curly braces)

1.3 Installing and Running Python 3


Follow these instructions to install Python 3 on Microsoft Windows.
 Visit http://www.python.org/download/ and download the newest version of Python 3. You
have two choices: the X86
MSI Installer and the X86-
64 MSI Installer. If you know you
have a 64-bit system, choose
the X86-64 MSI Installer; otherwise,
choose the X86 MSI Installer.
 Double-click the
downloaded .msi file and follow the
instructions. All the default options Figure 1.1: Python Shell
should be fine.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |2

To test your installation, find Python 3 in your Start menu, click it, and then click IDLE. You
should see something like this window:

1.4 Simple Programming using Python


Programs are made up of commands that tell the computer what to do. These commands are called
statements, which the computer executes. This section describes the simplest of Python’s
statements and shows how they can be used to do arithmetic, which is one of the most common
tasks for computers and also a great place to start learning to program.

In order to understand what happens when you’re programming, you need to have a basic
understanding of how a computer executes a program. The computer is assembled from pieces of
hardware, including a processor that can execute instructions and do arithmetic, a place to store
data such as a hard drive, and various other pieces, such as a computer monitor, a keyboard, a card
for connecting to a network, and so on.

To deal with all these pieces, every computer runs some kind of operating system, such as
Microsoft Windows, Linux, or Mac OS X. An operating system, or OS, is a program; what makes
it special is that it’s the only program on the computer that’s allowed direct access to the hardware.
When any other application (such as your browser, a spreadsheet program, or a game) wants to
draw on the screen, find out what key was just pressed on the keyboard, or fetch data from the hard
drive, it sends a request to the OS.

Figure 1.2: Application programs interaction with operating system


Twenty-five years ago that’s how most programmers worked. Today, though, it is common to add
another layer between the programmer and the computer’s hardware. When we write a program in
Python, Java, or Visual Basic, it doesn’t run directly on top of the OS. Instead, another program,
called an interpreter or virtual machine, takes your program and runs it for you, translating your

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |3

commands into a language the OS understands. It’s a lot easier, more secure, and more portable
across operating systems than writing programs directly on top of the OS:

Figure 1.3: Python programs interaction with operating system


There are two ways to use the Python interpreter. One is to tell it to execute a Python program that
is saved in a file with a .py extension. Another is to interact with it in a program called a shell,
where you type statements one at a time. The interpreter will execute each statement when we type
it, do what the statement says to do, and show any output as text, all in one window.

1.5 Interactive Mode


When commands are read from the command prompt, the interpreter is said to be in interactive
mode. In this mode it prompts for the next command with the primary prompt, usually three
greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by default
three dots (...). The interpreter prints a welcome message stating its version number and a copyright
notice before printing the first prompt:

python
Python 3.2 (#1, Dec 28 2016, 00:02:06)
Type "help", "copyright", "credits" or "license" for more information.
>>>

Continuation lines are needed when entering a multi-line construct. As an example, take a look at
this print statement:

>>> the_world_is_flat = 1
>>> print "Hello world...!"
...
Hello world...!

1.6 Saved file Mode

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |4

One is to tell it to execute a Python program that is saved in a file with a .py extension. The python
program can be executed using python interpreter in the command prompt. The same can be done
using IDE by creating a project and storing the program in a file. Inside IDE the program can be
run by pressing RUN Botton on the tool bar. The output can be noticed in the output console
window.

Program
Window
Project
Window

Output
Window

Figure 1.4: Python IDE

1.7 Expressions and Values: Arithmetic in Python


Python can evaluate basic mathematical expressions. For example, the following expression adds
4 and 13:
>>> 4 + 13
17
Subtraction and multiplication are similarly unsurprising:
>>> 15 - 3
12
>>> 4 * 7
28
The following expression divides 5 by 2:
>>> 5 / 2
2.5
The result has a decimal point. In fact, the result of division always has a decimal point even if the
result is a whole number:
>>> 4 / 2
2.0
Values like 4 and 17 have type int, and values like 2.5 and 17.0 have type float. The word float is
short for floating point, which refers to the decimal point that moves around between digits of the
number. An expression involving two floats produces a float:

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |5

>>> 17.0 - 10.0


7.0
When an expression’s operands are an int and a float, Python automatically converts the int to a
float. This is why the following two expressions both return the same answer:
>>> 17.0 - 10
7.0
>>> 17 - 10.0
7.0
If you want, you can omit the zero after the decimal point when writing a floating-point number:
>>> 17 - 10.
7.0
>>> 17. - 10
7.0

1.8 Integer Division, Modulo, and Exponentiation


Every now and then, we want only the integer part of a division result. For example, we might
want to know how many 24-hour days there are in 53 hours (which is two 24-hour days plus another
5 hours). To calculate the number of days, we can use integer division:
>>> 53 // 24
2
We can find out how many hours are left over using the modulo operator, which gives the
remainder of the division:
>>> 53 % 24
5
Python doesn’t round the result of integer division. Instead, it takes the floor of the result of the
division, which means that it rounds down to the nearest integer:
>>> 17 // 10
1
The following expression calculates 3 raised to the 6th power:
>>> 3 ** 6
729
Be careful about using % and // with negative operands. Because Python takes the floor of the
result of an integer division, the result is one smaller than you might expect if the result is
negative:
>>> -17 // 10
-2

When using modulo, the sign of the result matches the sign of the divisor
(the second operand):

>>> -17 % 10
3
>>> 17 % -10
-3

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |6

Floating-point numbers can be operands for // and % as well. With //, the result is rounded down
to the nearest whole number, although the type is a floating-point number:
>>> 3.3 // 1
3.0
>>> 3 // 1.0
3.0
>>> 3 // 1.1
2.0
>>> 3.5 // 1.1
3.0
>>> 3.5 // 1.3
2.0
>>> 3.3 % 1.50
0.2999999999999998

Operators that have two operands are called binary operators. Negation is a unary operator because
it applies to one operand:
>>> -5
-5
>>> --5
5
>>> ---5
-5

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |7

1.9 Variables and Computer Memory: Remembering Values


Like mathematicians, programmers frequently name values so that they can use them later. A name
that refers to a value is called a variable. In Python, variable names can use letters, digits, and the
underscore symbol. For example, X, species5618, and degrees_celsius are all allowed, but 777
isn’t.

>>> degrees_celsius = 26.0

This statement is called an assignment statement; we say that degrees_celsius is assigned the value
26.0. That makes degrees_celsius refer to the value 26.0. We can use variables anywhere we can
use values. Whenever Python sees a variable in an expression, it substitutes the value to which the
variable refers:

>>> degrees_celsius = 26.0


>>> degrees_celsius
26.0
>>> 9 / 5 * degrees_celsius + 32
78.80000000000001
>>> degrees_celsius / degrees_celsius
1.0

Values, Variables, and Computer Memory


We’re going to develop a model of computer memory—a memory model—that will let us trace
what happens when Python executes a Python program. This memory model will help us accurately
predict and explain what Python does when it executes code, a skill that is a requirement for
becoming a good programmer. Every location in the computer’s memory has a memory address.

We’re going to mark our memory addresses with an id prefix (short for identifier) so that they look
different from integers: id1, id2, id3, and so on. Here is how we draw the floating-point value 26.0
using the memory model:

This picture shows the value 26.0 at the memory address id1. We will always show the type of the
value as well—in this case, float. We will call this box an object: a value at a memory address with
a type. During execution of a program, every value that Python keeps track of is stored inside an
object in computer memory.

In our memory model, a variable contains the memory address of the object to which it refers:

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |8

In order to make the picture easier to interpret, we will usually draw arrows from variables to their
objects.
Value 26.0 has the memory address id1.
• The object at the memory address id1 has type float and the value 26.0.
• Variable degrees_celsius contains the memory address id1.
• Variable degrees_celsius refers to the value 26.0

1.9.1 Assignment Statement


Here is the general form of an assignment statement:
«variable» = «expression»
This is executed as follows:
1. Evaluate the expression on the right of the = sign to produce a value. This value has a memory
address.
2. Store the memory address of the value in the variable on the left of the =. Create a new
variable if that name doesn’t already exist; otherwise, just reuse the existing variable, replacing
the memory address that it contains.

Consider this example:


>>> degrees_celsius = 26.0 + 5
>>> degrees_celsius
31.0
Reassigning to Variables Consider this code:
>>> difference = 20
>>> double = 2 * difference
>>> double
40
>>> difference = 5
>>> double
40
This code demonstrates that assigning to a variable does not change any other variable. We start
by assigning value 20 to variable difference, and then we assign the result of evaluating 2 *
difference (which produces 40) to variable double. Next, we assign value 5 to variable difference,

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) Page |9

but when we examine the value of double, it still refers to 40.

1.9.2 id() function


id() is a built-in function in Python 3, which returns the identity of an object. The identity is a
unique integer for that object during its lifetime. This is also the address of the object in memory.

a = 2
print(id(a)) #=> 140454723286976
# (Values returned by id() might be different for different users)

b = 3
print(id(b)) #=> 140454723287008

c = 2
print(id(c)) #=> 140454723286976
‘’’ (This is same as id(a) since they both contain the same
value and hence have same memory address)’’’

print(id(a) == id(b)) #=> False since a , b have different values


print(id(a) == id(c)) #=> True since a and c have same values stored

d = 1.1
e = 1.1
print(id(d) == id(e)) #=> True (since d and e have same values stored

str1 = 'hello'
str2 = 'hello'
print(id(str1) == id(str2))
#=> True (since str1 and str2 have same values stored in them)

1.9.2 Python Identifiers


A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 10

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.

Common Naming Conventions


Here are naming conventions for Python identifiers −
• Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that the identifier is private.
• Starting an identifier with two leading underscores indicates a strongly private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.

Reserved Words
The following list shows the Python keywords. These are reserved words and we cannot use them
as constant or variable or any other identifier names. All the Python keywords contain lowercase
letters only.

and exec Not

assert finally Or

break for pass

class from print

continue global raise

def if return

del import Try

elif in while

else is with

except lambda yield

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 11

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles, name)

Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously. For example

a = b = c = 1

• Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables. For
example −

a, b, c = 1, 2.5, "john"

• Here, two integer objects with values 1 and 2.5 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.

Deleting variables in Python


• The intent of the del function, known as the 'delete' function, in regards to the deletion of
a variable name, is to remove the bindings of the name from the local or global namespace.
Example:

>>> a =5
>>> print(a)
5
>>> del a
>>>print(a)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(a)
NameError: name 'a' is not defined

Comments in Python
• Comments in Python start with the hash character # and extend to the end of the line.
• Multiple line comments can be written using ''' or " " ''

Multiple Lines Statements


• In order to split up a statement into more than one line, you need to do one of two things:
1. Make sure your line break occurs inside parentheses, or
2. Use the line-continuation character, which is a backslash, \.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 12

Note that the line-continuation character is a backslash (\)


Here are examples of both:
>>> (2 +
... 3)
5
>>> 2 + \
... 3
5

1.10 Designing and Using Functions


• A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.

• As you already know, Python gives you many built-in functions like print(), etc. but you
can also create your own functions. These functions are called user-defined functions.

• We can define functions to provide the required functionality. Here are simple rules to
define a function in Python.

• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
function_suite
return [expression]
Example :The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
print (str)
return

1.10.1 Calling a Function


• Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 13

• Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function

def printme( str ):


print (str)
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

1.10.2 Function Execution Sequence


• Consider an example program of that contains a function : Write a python program to convert
temperature from Fahrenheit to Celsius. Hint: C = F – 32 * 5 / 9

>>> def convert_to_celsius(fahrenheit):


... return (fahrenheit-32)*5/9
>>> convert_to_celsius(80)
26.666666666666668

Here is a quick overview of how Python executes the function code:

1. Python executes the function definition, which creates the function, but doesn’t execute it yet.
2. Next, Python executes function call convert_to_celsius(80). To do this, it assigns 80 to
fahrenheit (which is a variable). For the duration of this function call, fahrenheit refers to 80.
3. Python now executes the return statement. fahrenheit refers to 80, so the expression that appears
after return is equivalent to (80 - 32) * 5 / 9. When Python evaluates that expression,
26.666666666666668 is produced. We use the word return to tell Python what value to produce
as the result of the function call, so the result of calling convert_to_celsius(80) is
26.666666666666668.
4. Once Python has finished executing the function call, it returns to the place where the function
was originally called.

1.10.3 Tracing Function Calls in the Memory Model


Let us consider the following code for memory tracing of functions

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 14

>>> def f(x):


... x = 2 * x
... return x
...
>>> x = 1
>>> x = f(x + 1) + f(x + 2)

• From now on in our memory model, we will draw a separate box for each namespace to
indicate that the variables inside it are in a separate area of computer memory.
• The programming world calls this box a frame. We separate the frames from the objects by
a vertical dotted line:

• At the beginning, no variables have been created; Python is about to execute the function
definition. We have indicated this with an arrow.
• When Python executes that function definition, it creates a variable f in the frame for the
shell’s namespace plus a function object.

• Now we are about to execute the first assignment to x in the shell. Once that assignment
happens, both f and x are in the frame for the shell.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 15

Now we are about to execute the second assignment to x in the shell:

• we first evaluate the expression on the right of the =, which is f(x+ 1) + f(x + 2). Python
evaluates the left function call first: f(x + 1).
• Following the rules for executing a function call, Python evaluates the argument, x + 1. In
order to find the value for x, Python looks in the current frame. The current frame is the
frame for the shell, and its variable x refers to 1, so x + 1 evaluates to 2.

• Now we have evaluated the argument to f. The next step is to create a namespace for the
function call. We draw a frame, write in parameter x, and assign 2 to that parameter.
• We are now about to execute the first statement of function f:

• x = 2 * x is an assignment statement. The right side is the expression 2 * x. Python looks


up the value of x in the current frame and finds 2, so that expression evaluates to 4. Python
finishes executing that assignment statement by making x refer to that 4:

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 16

• This is a return statement, so we evaluate the expression, which is simply x. Python looks
up the value for x in the current frame and finds 4, so that is the return value:
• When the function returns, Python comes back to this expression: f(x + 1) + f(x + 2). Python
just finished executing f(x + 1), which produced the value 4. It then executes the right
function call: f(x + 2).
• Now we have evaluated the argument to f. The next step is to create a namespace for the
function call. We draw a frame, write in the parameter x, and assign 3 to that parameter:

• We are now about to execute the second statement of function f:

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 17

• When the function returns, Python comes back to this expression: f(x + 1) + f(x + 2). Python
just finished executing f(x + 2), which produced the value 6.
• Both function calls have been executed, so Python applies the + operator to 4 and 6, giving
us 10.

1.10.4 Keyword arguments


• Keyword arguments are related to the function calls. When you use keyword arguments in
a function call, the caller identifies the arguments by the parameter name.

• This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also
make keyword calls to the printme() function in the following ways −

# Function definition is here


def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )

1.10.5 Default arguments


A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it prints
default age if it is not passed −

def printinfo( name, age = 35 ):

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 18

print ("Name: ", name)


print ("Age ", age)
return;

printinfo( age=50, name="miki" )


printinfo( name="miki" )

1.10.6 Variable-length arguments


• We may need to process a function for more arguments than we specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is :

def functionname([formal_args,] *var_args_tuple ):


function_suite
return [expression]

• An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified
during the function call. Following is a simple example

def printinfo( arg1, *vartuple ):


print ("Output is: “)
print (arg1)
for var in vartuple:
print (var)
return;

printinfo( 10 )
printinfo( 70, 60, 50 )

1.10.7 The Anonymous Functions


• These functions are called anonymous because they are not declared in the standard manner
by using the def keyword. You can use the lambda keyword to create small anonymous
functions.

• Lambda forms can take any number of arguments but return just one value in the form of
an expression. They cannot contain commands or multiple expressions.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 19

• An anonymous function cannot be a direct call to print because lambda requires an


expression
• Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

1.10.8 The return Statement


• The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.

def sum( arg1, arg2 ):


total = arg1 + arg2
print "Inside the function : ", total
return total;

total = sum( 10, 20 );


print "Outside the function : ", total

1.10.9 Scope of Variables


• All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.

• The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −

• Global variables
• Local variables
• Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.

• This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 20

functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example

total = 0; # This is global variable.

# Function definition is here


def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


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

1.11 Working with Text in Python


• 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.
Creating strings is as simple as assigning a value to a variable. For example

var1 = 'Hello World!'


var2 = "Python Programming"

1.11.1 Accessing Values in Strings


• Characters are treated as strings of length one, thus also considered a substring.
• To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. For example

var1 = 'Hello World!'


var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]

1.11.2 Updating Strings


• We can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether. For
example

var1 = 'Hello World!'


var1 = var1[:6] + 'Python 3.4'

print ("Updated String :- ", var1)

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 21

1.11.3 String Special Operators

Operator Description Example

+ Concatenation - Adds values on either side of the operator a + b will give


HelloPython
* Repetition - Creates new strings, concatenating multiple a*2 will give -
copies of the same string HelloHello

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given H in a will give 1
string
not in Membership - Returns true if a character does not exist in M not in a will give 1
the given string

1.11.4 String Formatting Operator


• One of Python's coolest features is the string format operator %. This operator is unique to
strings and makes up for the pack of having functions from C's printf() family. Following
is a simple example

print ("My name is %s and weight is %d kg!" % ('Zara', 21) )

Output
My name is Zara and weight is 21 kg!

Triple Quotes
• Python's triple quotes comes to the rescue by allowing strings to span multiple lines,
including verbatim NEWLINEs, TABs, and any other special characters.
• The syntax for triple quotes consists of three consecutive single or double quotes.

para_str = """this is a long string that is made up of


several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up. """

print para_str

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 22

1.11.5 Built-in String Methods

capitalize() Capitalizes first letter of string

center(width, fillchar) Returns a space-padded string with the original string


centered to a total of width columns.

count(str, beg= 0, end=len(string)) Counts how many times str occurs in string or in a
substring of string if starting index beg and ending
index end are given.

endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting


index beg and ending index end are given) ends with
suffix; returns true if so and false otherwise.

find(str, beg=0 end=len(string)) 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.

index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.

capitalize() method : Capitalizes first letter of string


Example
str = "this is string example....wow!!!";
print ("str.capitalize() : ", str.capitalize())

center(width, fillchar) : Returns a space-padded string with the original string centered to a total
of width columns.
Example:

str = "this is string example....wow!!!";


print ("str.center() : ", str.center(40, 'a'))

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 23

count(str, beg= 0, end=len(string))


Counts how many times str occurs in string or in a substring of string if starting index beg and
ending index end are given.

str = "this is string example....wow!!!";


print ("str.count : ", str.count('i',0,20))
print ("str.count : ", str.count('wow'))

endswith() method : returns true if the string pattern ends with in the given string.

str = "this is string example....wow!!!";


suffix = "wow!!!";
print (str.endswith(suffix))
print (str.endswith(suffix,20))
suffix = "is";
print (str.endswith(suffix, 2, 4))
print (str.endswith(suffix, 2, 6))

find(str, beg=0 end=len(string)) : 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.

str1 = "this is string example....wow!!!";


str2 = "exam";
print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 20))

• index(str, beg=0, end=len(string)) : Same as find(), but raises an exception if str not
found.

str1 = "this is string example....wow!!!";


str2 = "exam";
print str1.index(str2)
print str1.index(str2, 10)
print str1.index(str2, 40)

isalnum() Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
isalpha() Returns true if string has at least 1 character and all characters are alphabetic
and false otherwise.
isdigit() Returns true if string contains only digits and false otherwise.
islower() Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.
isnumeric() Returns true if a unicode string contains only numeric characters and false
otherwise.

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 24

isspace() Returns true if string contains only whitespace characters and false otherwise.
istitle() Returns true if string is properly "title cased" and false otherwise.
isupper() Returns true if string has at least one cased character and all cased characters
are in uppercase and false otherwise.

• The method isalnum() checks whether the string consists of alphanumeric characters.
Example

str = "this2009"; # No space in this string


print (str.isalnum())
str = "this is string example..wow!!!";
print (str.isalnum())

• The method isdigit() checks whether the string consists of digits only.

str = "123456"; # Only digit in this string


print (str.isdigit())
str = "this is string example....wow!!!";
print (str.isdigit())

• The method islower() checks whether all the case-based characters (letters) of the string
are lowercase.
Example

str = "THIS is string example....wow!!!";


print (str.islower())
str = "this is string example....wow!!!";
print (str.islower())

• The method isspace() checks whether the string consists of whitespace.


Example

str = " ";


print (str.isspace())
str = "This is string example....wow!!!";
print (str.isspace())
• The method istitle() checks whether all the case-based characters in the string following
non-casebased letters are uppercase and all other case-based characters are lowercase.
• This method returns true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters and
lowercase characters only cased ones. It returns false otherwise.

str = "This Is String Example...Wow!!!";


print (str.istitle())
str = "This is string example....wow!!!";
print (str.istitle())

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 25

join(seq) Merges (concatenates) the string representations of elements in


sequence seq into a string, with separator string.
len(string) Returns the length of the string
lower() Converts all uppercase letters in string to lowercase.

max(str) Returns the max alphabetical character from the string str.

min(str) Returns the min alphabetical character from the string str.

replace(old, new [, Replaces all occurrences of old in string with new or at most
max]) max occurrences if max given.
split(str="", Splits string according to delimiter str (space if not provided)
num=string.count(str)) and returns list of substrings; split into at most num substrings
if given.
splitlines( Splits string at all (or num) NEWLINEs and returns a list of
num=string.count('\n')) each line with NEWLINEs removed.
startswith(str, Determines if string or a substring of string (if starting index
beg=0,end=len(string)) beg and ending index end are given) starts with substring str;
returns true if so and false otherwise.

1.12 Printing Information


• We will use print to print messages to the users of our program. Those messages may
include the values that expressions produce and the values that the variables refer to.

>>> print(1 + 1)
2
>>> print('by publishing "On the Origin of Species".')
by publishing "On the Origin of Species".
>>> print('one\ttwo\nthree\tfour')
one two
three four

>>> numbers = '''one


... two
... three'''
>>> print(numbers)
one
two
three
>>> print(1, 2, 3)
1 2 3
>>> print()
>>>

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]


Module 1: Programming with Python (18MCA32) P a g e | 26

• Here, we separate each value with a comma and a space instead of just a space by
including sep=', ' as an argument. Often we want to print information but not start a new
line. To do this, use the keyword argument end='' to tell Python to end with an empty
string instead of a new line:

>>> print('a', 'b', 'c') # The separator is a space by default


a b c
>>> print('a', 'b', 'c', sep=', ')
a, b, c
>>> print('a', 'b', 'c', sep=', ', end='')
a, b, c>>>

Note: print() does not return any value. Formatting of output can be achieved either
using % modifier and .format()modifier. Visit http://pyformat.info for details

1.13 Getting Information from the Keyboard


• Built-in function that you will find useful is input, which reads a single line of text from
the keyboard. It returns whatever the user enters as a string, even if it looks like a number:

>>> population = input()


6973738433
>>> population
'6973738433'
>>> type(population)
<class 'str'>
>>> population = int(population)
>>> population
6973738433
>>> population = population + 1
>>> population
6973738434
>>> species = input("Please enter a species: ")
Please enter a species: Python curtus
>>> print(species)
Python curtus

Prepared By: Rama Satish K V, Asst Professor, RNSIT, Bengaluru. [www.google.com/+ramasatishkv]

You might also like