0% found this document useful (0 votes)
1 views53 pages

Python 1

This document provides an introduction to Python, detailing its features, history, and basic programming concepts. Python is a versatile, high-level, interpreted language that supports multiple programming paradigms and is easy to learn. It covers topics such as variable declaration, data types, string manipulation, and comments, along with examples to illustrate these concepts.

Uploaded by

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

Python 1

This document provides an introduction to Python, detailing its features, history, and basic programming concepts. Python is a versatile, high-level, interpreted language that supports multiple programming paradigms and is easy to learn. It covers topics such as variable declaration, data types, string manipulation, and comments, along with examples to illustrate these concepts.

Uploaded by

storeweb555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖Python Introduction
➢ Python is a general purpose, dynamic, high level, and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy
to learn and provides lots of high-level data structures.
➢ Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development. Python's syntax and dynamic typing with its interpreted nature
make it an ideal language for scripting and rapid application development.
➢ Python supports multiple programming pattern, including object-oriented, imperative, and
functional or procedural programming styles.
➢ Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.
➢ We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.
➢ Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

❖ Python History
➢ Python laid its foundation in the late 1980s.
➢ The implementation of Python was started in the December 1989 by Guido Van Rossum at
CWI in Netherland.
➢ In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
➢ In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
➢ Python 2.0 added new features like: list comprehensions, garbage collection system.
➢ On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language.
➢ ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.
➢ Python is influenced by following programming languages:
o ABC language.

o Modula-3

PREPARED BY: DHABALIYA NIKITA 1


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖ Python Features
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.

2) Expressive Language
Python language is more expressive means that it is more understandable and readable.

3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.

4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So,
we can say that Python is a portable language.

5) Free and Open Source


Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.

6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into existence.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our python code.

8) Large Standard Library

Python has a large and broad library and prvides rich set of module and functions for
rapid application development.

9) GUI Programming Support

Graphical user interfaces can be developed using Python.

10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.

PREPARED BY: Dhabaliya Nikita 2


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖ First Python Program


In this Section, we will discuss the basic syntax of python by using which, we will run a
simple program to print hello world on the console.

Python provides us the two ways to run a program:

1. Using Interactive interpreter prompt


2. Using a script file

Let's discuss each one of them in detail.

1. Interactive interpreter prompt


➢ Python provides us the feature to execute the python statement one by one at the
interactive prompt. It is preferable in the case where we are concerned about the output
of each line of our python program.
➢ To open the interactive mode, open the terminal (or command prompt) and type python
(python3 in case if you have python2 and python3 both installed on your system).
➢ It will open the following prompt where we can execute the python statement and
check their impact on the console.

➢ Let's run a python statement to print the traditional hello world on the console. Python3
provides print() function to print some message on the console. We can pass the
message as a string into this function. Consider the following image.

Here, we get the message "Hello World !" printed on the console.

PREPARED BY: DHABALIYA NIKITA 3


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

2. Using a script file


➢ Interpreter prompt is good to run the individual statements of the code. However, we
can not write the code every-time on the terminal.
➢ We need to write our code into a file which can be executed later. For this purpose, open
an editor like notepad, create a file named first.py (python used .py extension) and write
the following code in it.

Print ("hello world"); #here, we have used print() function to print the message on the console.
To run this file named as first.py, we need to run the following command on the terminal.

$ python3 first.py

Hence, we get our output as the message Hello World ! is printed on the console.

❖ Python Variables
➢ Variable is a name which is used to refer memory location. Variable also known as identifier
and used to hold value.
➢ In Python, we don't need to specify the type of variable because Python is a type infer
language and smart enough to get variable type.
➢ Variable names can be a group of both letters and digits, but they have to begin with a
letter or an underscore.
➢ It is recomended to use lowercase letters for variable name. Rahul and rahul both are two
different variables.

❖ Identifier Naming Rules


o first character of the variable must be an alphabet or underscore ( _ ).
o All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*). o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive for example my name, and MyName is not the same.
o Examples of valid identifiers : a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
PREPARED BY: DHABALIYA NIKITA 4
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

➢ Declaring Variable and Assigning Values


✓ Python does not bound us to declare variable before using in the application. It allows us
to create variable at required time.
✓ We don't need to declare explicitly variable in Python. When we assign any value to the
variable that variable is declared automatically.
✓ The equal (=) operator is used to assign value to a variable.

Eg:

❖ String and Inputs


➢ There are hardly any programs without any input. Input can come in various ways, for
example from a database, another computer, mouse clicks and movements or from the
internet. Yet, in most cases the input stems from the keyboard. For this purpose, Python
provides the function input(). input has an optional parameter, which is the prompt string.

print('Enter your name:')


x = input()
print('Hello, ' + x)

Syntax :input(prompt)
Example:

Use the prompt parameter to write a message before the input:

x = input('Enter your name:')


print('Hello, ' + x)

PREPARED BY: DHABALIYA NIKITA 5


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖ Python Comments
➢ Comments in Python can be used to explain any program code. It can also be used to hide the
code as well.
➢ Comments are the most helpful stuff of any program. It enables us to understand the way, a
program works. In python, any statement written along with # symbol is known as a comment.
The interpreter does not interpret the comment.
➢ Comment is not a part of the program, but it enhances the interactivity of the program and
makes the program readable.
➢ Python supports two types of comments:

1) Single Line Comment:In case user wants to specify a single line comment, then comment
must start with ?#?

Eg:
# This is single line comment.
print "Hello Python"
Output:
Hello Python

2) Multi Line Comment:


Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multipline comment'''
eg:
#single line comment
print "Hello Python"
'''''This is
multiline comment'''
Output:
Hello Python

❖ Python Data Types


➢ Variables can hold values of different data types. Python is a dynamically typed language hence
we need not define the type of the variable while declaring it. The interpreter implicitly binds
the value with its type.
➢ Python enables us to check the type of the variable used in the program. Python provides us
the type() function which returns the type of the variable passed.
➢ Consider the following example to define the values of different data types and checking its
type.

PREPARED BY: DHABALIYA NIKITA 6


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

A=10
b="Hi Python"
c = 10.5
print(type(a));
print(type(b));
print(type(c));

Output:

<type 'int'>
<type 'str'>
<type 'float'>

❖Standard data types


➢ A variable can hold different types of values. For example, a person's name must be stored
as a string whereas its id must be stored as an integer.
➢ Python provides various standard data types that define the storage method on each of
them. The data types defined in Python are given below.

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

1. Numbers
➢ Number stores numeric values. Python creates Number objects when a number is assigned
to a variable. For example;
➢ a = 3 , b = 5 #a and b are number objects

Python supports 4 types of numeric data.

1. int (signed integers like 10, 2, 29, etc.)


2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

➢ Python allows us to use a lower-case L to be used with long integers. However, we must
always use an upper-case L to avoid confusion.

PREPARED BY: DHABALIYA NIKITA 7


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

➢ A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).

2. String
➢ The string can be defined as the sequence of characters represented in the quotation marks.
In python, we can use single, double, or triple quotes to define a string.
➢ String handling in python is a straightforward task since there are various inbuilt
functions and operators provided.
➢ In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
➢ The operator * is known as repetition operator as the operation "Python " *2 returns
"Python Python ".
➢ The following example illustrates the string handling in python.

str1 = 'hello javatpoint' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string print
(str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

✓ Strings indexing and splitting


➢ Like other languages, the indexing of the python strings starts from 0. For example, The
string "HELLO" is indexed as given in the below figure.

PREPARED BY: DHABALIYA NIKITA 8


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

➢ As shown in python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in python to access the substring. Consider the following
example.

➢ Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str =
'python' is given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and nothing else.

✓ String Operators

Operator Description

+ It is known as concatenation operator used to join the strings given either side of the
operator.

* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified
range.

In It is known as membership operator. It returns if a particular sub-string is present in the


specified string.

PREPARED BY: DHABALIYA NIKITA 9


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
prithe actual meaning of escape characters such as "C://python". To define any string as
a raw string, the character r or R is followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.

Example
Consider the following example to understand the real use of Python operators.

str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str print('wo'
not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello

✓ Python Formatting operator


➢ Python allows us to use the format specifiers used in C's printf statement. The format specifiers in
python are treated in the same way as they are treated in C. However, Python provides an additional
operator % which is used as an interface between the format specifiers and their values. In other words,
we can say that it binds the format specifiers to the values.

Consider the following example.

Integer = 10;
Float = 1.290
String = "Ayush"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string
... My value is %s"%(Integer,Float,String));
PREPARED BY: DHABALIYA NIKITA 10
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Ayush

✓ Built-in String functions


Python provides various in-built functions that are used for string handling. Many String fun

Method Description

capitalize() It capitalizes the first character of the String. This function is


deprecated in python3

center(width ,fillchar) It returns a space padded string with the original string
centred with equal number of left and right spaces.

count(string,begin,end) It counts the number of occurrences of a substring in a String


between begin and end index.

decode(encoding = 'UTF8', Decodes the string using codec registered for encoding.
errors = 'strict')

encode() Encode S using the codec registered for encoding. Default


encoding is 'utf-8'.

find(substring ,beginIndex, It returns the index value of the string where substring is
endIndex) found between begin index and end index.

format(value) It returns a formatted version of S, using the passed value.

index(subsring, beginIndex, It throws an exception if string is not found. It works same as


endIndex) find() method.

isalnum() It returns true if the characters in the string are alphanumeric


i.e., alphabets or numbers and there is at least 1 character.
Otherwise, it returns false.

PREPARED BY: DHABALIYA NIKITA 11


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

isalpha() It returns true if all the characters are alphabets and there is
at least one character, otherwise False.

isdecimal() It returns true if all the characters of the string are decimals.

isdigit() It returns true if all the characters are digits and there is at
least one character, otherwise False.

isidentifier() It returns true if the string is the valid identifier.

islower() It returns true if the characters of a string are in lower case,


otherwise false.

isnumeric() It returns true if the string contains only numeric characters.

isprintable() It returns true if all the characters of s are printable or s is


empty, false otherwise.

isupper() It returns false if characters of a string are in Upper case,


otherwise False.

isspace() It returns true if the characters of a string are white-space,


otherwise false.

istitle() It returns true if the string is titled properly and false


otherwise. A title string is the one in which the first character
is upper-case whereas the other characters are lower-case.

isupper() It returns true if all the characters of the string(if exists) is


true otherwise it returns false.

join(seq) It merges the strings representation of the given sequence.

len(string) It returns the length of a string.

lower() It converts all the characters of a string to Lower case.

lstrip() It removes all leading whitespaces of a string and can also be


used to remove particular character from leading.

PREPARED BY: DHABALIYA NIKITA 12


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

maketrans() It returns a translation table to be used in translate function.

replace(old,new[,count]) It replaces the old sequence of characters with the new


sequence. The max characters are replaced if max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward


direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward


direction.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the
backward direction. It returns the list of words in the string. If
Separator is not specified then the string splits according to
the white-space.

split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It
returns the list of substring concatenated with the delimiter.

splitlines(num=string.count('\n') It returns the list of strings at each line with newline removed.
)

startswith(str,beg=0,end=len(st It returns a Boolean value if the string starts with given str
r)) between begin and end.

strip([chars]) It is used to perform lstrip() and rstrip() on the string.

swapcase() It inverts case of all characters in a string.

title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.

upper() It converts all the characters of a string to Upper Case.


PREPARED BY: DHABALIYA NIKITA 13
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

3. List
➢ Lists are similar to arrays in C. However; the list can contain data of different types. The items
stored in the list are separated with a comma (,) and enclosed within square brackets [].
➢ We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings.
➢ Consider the following example.
l = [1, "hi", "python",
2] print (l[3:]);
print (l[0:2]);
print (l);
print (l + l);
print (l * 3);

Output:

[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

✓ Iterating a List
➢ A list can be iterated by using a for - in loop. A simple list containing four strings can
be iterated as follows.

List = ["John", "David", "James", "Jonathan"]


for i in List: #i will iterate over the elements of the List and contains each element in each itera
tion.
print(i);

Output:
John
David
James
Jonathan

PREPARED BY: DHABALIYA NIKITA 14


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Python List Built-in functions

SN Function Description

1 cmp(list1, list2) It compares the elements of both the lists.

2 len(list) It is used to calculate the length of the list.

3 max(list) It returns the maximum element of the list.

4 min(list) It returns the minimum element of the list.

5 list(seq) It converts any sequence to the list.

✓ Python List built-in methods

SN Function Description

1 list.append(obj) The element represented by the object obj is added to the list.

2 list.clear() It removes all the elements from the list.

3 List.copy() It returns a shallow copy of the list.

4 list.count(obj) It returns the number of occurrences of the specified object in the list.

5 list.extend(seq) The sequence represented by the object seq is extended to the list.

6 list.index(obj) It returns the lowest index in the list that object appears.

7 list.insert(index, obj) The object is inserted into the list at the specified index.

8 list.pop(obj=list[-1])It removes and returns the last object of the list.

9 list.remove(obj) It removes the specified object from the list.

10 list.reverse() It reverses the list.

11 list.sort([func]) It sorts the list by using the specified compare function if given.
PREPARED BY: DHABALIYA NIKITA 15
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

4. Tuple
➢ Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists
since the value of the items stored in the list can be changed whereas the tuple is immutable
and the value of the items stored in the tuple can not be changed.
➢ A tuple can be written as the collection of comma-separated values enclosed with the small
brackets. A tuple can be defined as follows.

T1 = (101, "Ayush", 22)


T2 = ("Apple", "Banana", "Orange")

Example

tuple1 = (10, 20, 30, 40, 50, 60)


print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i));

Output:

(10, 20, 30, 40, 50, 60)


tuple1[0] = 10
tuple1[0] = 20
tuple1[0] = 30
tuple1[0] = 40
tuple1[0] = 50
tuple1[0] = 60

Example 2(RUN TIME GET VALUE)

tuple1 = tuple(input("Enter the tuple elements ..."))


print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i));

Output:

Enter the tuple elements ...12345


('1', '2', '3', '4', '5')
tuple1[0] = 1
tuple1[0] = 2
tuple1[0] = 3
tuple1[0] = 4
tuple1[0] = 5
PREPARED BY: DHABALIYA NIKITA 16
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Consider the following image to understand the indexing and slicing in detail.

✓ Python Tuple inbuilt functions

SN Function Description

1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater
than tuple2 otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple.

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

List VS Tuple

List Tuple

The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().

The List is mutable. The tuple is immutable.

The List has the variable length. The tuple has the fixed length.
PREPARED BY: DHABALIYA NIKITA 17
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

The list provides more functionality than The tuple provides less functionality than the list.
tuple.

The list Is used in the scenario in which we The tuple is used in the cases where we need to
need to store the simple collections with no store the read-only collections i.e., the value of
constraints where the value of the items the items can not be changed. It can be used as
can be changed. the key inside the dictionary.

5. Python Dictionary
➢ Dictionary is used to implement the key-value pair in python. The dictionary is the data type in
python which can simulate the real-life data arrangement where some specific value exists for
some particular key.
➢ In other words, we can say that a dictionary is the collection of key-value pairs where the value
can be any python object whereas the keys are the immutable python object, i.e., Numbers,
string or tuple.
➢ Dictionary simulates Java hash-map in python.

✓ Creating the dictionary


➢ The dictionary can be created by using multiple key-value pairs enclosed with the small brackets
() and separated by the colon (:). The collections of the key-value pairs are enclosed within the
curly braces {}.
➢ The syntax to define the dictionary is given below.

Dict = {"Name": "Ayush","Age": 22}

In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.

Let's see an example to create a dictionary and printing its content.

Employee = {"Name": "John", "Age": 29,


"salary":25000,"Company":"GOOGLE"} print(type(Employee))
print("printing Employee data .... ")
print(Employee)

Output

<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}

PREPARED BY: DHABALIYA NIKITA 18


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Accessing the dictionary values


The dictionary values can be accessed in the following way.

Employee = {"Name": "John", "Age": 29,


"salary":25000,"Company":"GOOGLE"} print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary values.
It would give the same result as given by the indexing.

✓ Iterating Dictionary
A dictionary can be iterated using the for loop as given below.

Example 1
# for loop to print all the keys of a dictionary

Employee = {"Name": "John", "Age": 29,


"salary":25000,"Company":"GOOGLE"} for x in Employee:
print(x);

Output:

Name
Company
salary
Age

PREPARED BY: DHABALIYA NIKITA 19


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Properties of Dictionary keys


➢ In the dictionary, we can not store multiple values for the same keys. If we pass more than one
values for a single key, then the value which is last assigned is considered as the value of the
key.

Consider the following example.

Employee = {"Name": "John", "Age": 29, "Salary":25000,"Company":"GOOGLE","Name":"Johnn"}

for x,y in Employee.items():


print(x,y)

Output:
Salary 25000
Company GOOGLE
Name Johnn
Age 29

Built-in Dictionary functions

SN Function Description

1 cmp(dict1, dict2) It compares the items of both the dictionary and returns true if
the first dictionary values are greater than the second dictionary,
otherwise it returns false.

2 len(dict) It is used to calculate the length of the dictionary.

3 str(dict) It converts the dictionary into the printable string representation.

4 type(variable) It is used to print the type of the passed variable.

PREPARED BY: DHABALIYA NIKITA 20


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Built-in Dictionary methods

Method Description

dic.clear() It is used to delete all the items of the dictionary.

dict.copy() It returns a shallow copy of the dictionary.

dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values
None, /) equal to value.

dict.get(key, default = "None") It is used to get the value specified for the passed key.

dict.has_key(key) It returns true if the dictionary contains the specified key.

dict.items() It returns all the key-value pairs as a tuple.

dict.keys() It returns all the keys of the dictionary.

dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary

dict.update(dict2) It updates the dictionary by adding the key-value pair of


dict2 to this dictionary.

dict.values() It returns all the values of the dictionary.

len() Get length to dictionary

popItem() Remove particular item

pop() Remove last item

count() Count element in dictionary

index()
Get index of specifying element in dictionary

PREPARED BY: DHABALIYA NIKITA 21


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖ Python Branching statements


➢ Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular decision.
Here, the decisions are made on the validity of the particular conditions. Condition checking is
the backbone of decision making.

1. if statement
➢ The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical expression
which can be either evaluated to true or false.

syntax:
if expression:
statement

Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

Output:

enter the number?10


Number is even

PREPARED BY: DHABALIYA NIKITA 22


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Example 2 : Program to print the largest of the three numbers.


a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

2. if-else statement
➢ The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
➢ If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

PREPARED BY: DHABALIYA NIKITA 23


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Syntax:
if condition:

#block of statements

else:
#another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or


not.
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!

3. elif statement
➢ The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
➢ The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement

Syntax:

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

PREPARED BY: DHABALIYA NIKITA 24


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15


number is not equal to 10, 50 or 100

Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

PREPARED BY: DHABALIYA NIKITA 25


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖ Python Loops
➢ The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.
➢ For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times.

1. for loop
The for loop in Python is used to iterate the statements or a part of the program several times. It
is frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)

Example

i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')

Output:

0123456789

PREPARED BY: DHABALIYA NIKITA 26


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Python for loop example : printing the table of the given number

i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));

Output:

Enter a number:10
10X1=10
10X2=20
10X3=30
10X4=40
10X5=50
10X6=60
10X7=70
10X8=80
10X9=90
10X10=100

❖Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax of the nested for loop in python is
given below.

for iterating_var1 in sequence:


for iterating_var2 in sequence:
#block of statements
#Other statements

Example 1

n = int(input("Enter the number of rows you want to print?"))


i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")

Output:

Enter the number of rows you want to print?5


*
**
PREPARED BY: DHABALIYA NIKITA 27
UNIT-1 INTRODUCTION TO PYTHON BCA-2019

***
****
*****

2. while loop
➢ The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the
code to be executed as long as the given condition is true.
➢ It can be viewed as a repeating if statement. The while loop is mostly used in the case where
the number of iterations is not known in advance.

while expression:
statements

➢ Here, the statements can be a single statement or the group of statements. The expression
should be any valid python expression resulting into true or false. The true is any non-zero
value.

Example 1

i=1;
while i<=10:
print(i);
i=i+1;

Output:

12345678910

PREPARED BY: DHABALIYA NIKITA 28


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖ Python Functions
➢ Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
➢ Python allows us to divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the python program.
➢ In other words, we can say that the collection of functions creates a program. The function is
also known as procedure or subroutine in other programming languages.
➢ Python provide us various inbuilt functions like range() or print(). Although, the user can create
its functions which can be called user-defined functions.

Creating a function
➢ In python, we can use def keyword to define the function. The syntax to define a function
in python is given below.

def my_function():
function-suite
return <expression>

➢ The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.
➢ A function can accept any number of parameters that must be the same in the definition and
function calling.

Function calling
➢ In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python
prompt. To call the function, use the function name followed by the parentheses.
➢ A simple function that prints the message "Hello Word" is given below.

def hello_world():
print("hello world")

hello_world()

Output:

hello world

PREPARED BY: DHABALIYA NIKITA 29


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Parameters in function
The information into the functions can be passed as the parameters. The parameters are specified
in the parentheses. We can give any number of parameters, but we have to separate them with a
comma.

Consider the following example which contains a function that accepts a string as the
parameter and prints it.

Example 1

#defining the function


def func (name):
print("Hi ",name);

#calling the function


func("Ayush")

Example 2

#python function to calculate the sum of two


variables #defining the function
def sum (a,b):
return a+b;

#taking values from the user


a = int(input("Enter a: "))
b = int(input("Enter b: "))

#printing the sum of a and b


print("Sum = ",sum(a,b))

Output:

Enter a: 10
Enter b: 20
Sum = 30

PREPARED BY: DHABALIYA NIKITA 30


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Call by reference in Python


➢ In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference.
➢ However, there is an exception in the case of mutable objects since the changes made to the
mutable objects like string do not revert to the original string rather, a new string object is made,
and therefore the two different objects are printed.

Example 1 Passing Immutable Object (List)


#defining the function
def change_list(list1):
list1.append(20);
list1.append(30);
print("list inside function = ",list1)

#defining the list


list1 = [10,30,40,50]

#calling the function


change_list(list1);
print("list outside function = ",list1);

Output:

list inside function = [10, 30, 40, 50, 20, 30]

list outside function = [10, 30, 40, 50, 20, 30]

Example 2 Passing Mutable Object (String)

#defining the function


def change_string (str):
str = str +" Hows you";
print("printing the string inside function :",str);

string1 = "Hi I am there"

#calling the function


change_string(string1)

print("printing the string outside function :",string1)

PREPARED BY: DHABALIYA NIKITA 31


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Output:

printing the string inside function : Hi I am there Hows you


printing the string outside function : Hi I am there

❖Types of arguments
➢ There may be several types of arguments which can be passed at the time of function calling.

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

1. Required Arguments
➢ Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are concerned, these
are the arguments which are required to be passed at the time of function calling with the exact
match of their positions in the function call and function definition. If either of the arguments is
not provided in the function call, or the position of the arguments is changed, then the python
interpreter will show the error.

Consider the following example.

Example 1

#the argument name is the required argument to the function


func def func(name):
message = "Hi "+name;
return message;
name = input("Enter the name?")
print(func(name))

Output:

Enter the name?John


Hi John

PREPARED BY: DHABALIYA NIKITA 32


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Example2

the function simple_interest accepts three arguments and returns the simple interest accordingly

def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))

Output:

Enter the principle amount? 10000


Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0

2. Keyword arguments
➢ Python allows us to call the function with the keyword arguments. This kind of function call will
enable us to pass the arguments in the random order.
➢ The name of the arguments is treated as the keywords and matched in the function calling and
definition. If the same match is found, the values of the arguments are copied in the function
definition.

Example 1

#function func is called with the name and message as the keyword
arguments def func(name,message):
print("printing
the message with",name,"and ",message)
func(name = "John",message="hello") #name and message is copied with the values John and
h ello respectively

Output:

printing the message with John and hello

PREPARED BY: DHABALIYA NIKITA 33


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

3. Default Arguments
➢ Python allows us to initialize the arguments at the function definition. If the value of any of the
argument is not provided at the time of function call, then that argument can be initialized with
the value given in the definition even if the argument is not specified at the function call.

Example 1

def printme(name,age=22):
print("My
name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default
val ue of age is considered in the function

Output:

My name is john and age is 22

Example 2

def printme(name,age=22):
print("My
name is",name,"and age is",age)
printme(name = "john") #the variable age is not passed into the function however the default val
ue of age is considered in the function
printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as age

Output:

My name is john and age is 22


My name is David and age is 10

4.Variable length Arguments


➢ In the large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to provide the comma separated values
which are internally treated as tuples at the function call.
➢ However, at the function definition, we have to define the variable with * (star) as *<variable -
name >.

Example

def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")

PREPARED BY: DHABALIYA NIKITA 34


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

for name in names:


print(name)
printme("john","David","smith","nick")

Output:

type of passed argument is <class 'tuple'>

printing the passed arguments... john

David
smith
nick

❖Scope of variables
➢ The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
➢ In python, the variables are defined with the two types of scopes.

1. Global variables
2. Local variables

➢ The variable defined outside any function is known to have a global scope whereas the
variable defined inside a function is known to have a local scope.

Consider the following example.

Example 1

def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the functi
on itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.

Output:
hello !! I am going to print a message.
File "/root/PycharmProjects/PythonTest/Test1.py", line 5,
in print(message)
NameError: name 'message' is not defined

PREPARED BY: DHABALIYA NIKITA 35


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Example 2

def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed

Output:

The sum is 60
Value of sum outside the function: 0

❖ Recursion in python
➢ A function that calls itself is a recursive function. This method is used when a certain problem is
defined in terms of itself. Although this involves iteration, using an iterative approach to solve
such a problem can be tedious. The recursive approach provides a very concise solution to a
seemingly complex problem. It looks glamorous but can be difficult to comprehend!
➢ The most popular example of recursion is the calculation of the factorial. Mathematically the
factorial is defined as: n! = n * (n-1)!
➢ We use the factorial itself to define the factorial. Hence, this is a suitable case to write a
recursive function. Let us expand the above definition for the calculation of the factorial value of
5.

5!=5X4!
5X4X3!
5X4X3X2!
5X4X3X 2X1!
5X4X3X 2X1
= 120

➢ While we can perform this calculation using a loop, its recursive function involves successively
calling it by decrementing the number until it reaches 1. The following is a recursive function to
calculate the factorial.

Example: Recursive Function

def factorial(n):
if n == 1:
print(n)
return 1
else:
print (n,'*', end=' ')
return n * factorial(n-1)

PREPARED BY: DHABALIYA NIKITA 36


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

The above recursive function can be called as below.

>>> factorial(5)

5*4*3*2*1

120

➢ When the factorial function is called with 5 as argument, successive calls to the same function
are placed, while reducing the value of 5. Functions start returning to their earlier call after the
argument reaches 1. The return value of the first call is a cumulative product of the return values
of all calls.

❖ Python Modules
➢ A python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved
with the extension (.py) is treated as the module. We may have a runnable code inside the python
module.
➢ Modules in Python provides us the flexibility to organize the code in a logical way.
➢ To use the functionality of one module into another, we must have to import the specific
module.

Example
In this example, we will create a module named as file.py which contains a function func
that contains a code to print some message on the console.

Let's create the module named as file.py.

#displayMsg prints a message to the name being passed.


def displayMsg(name)
print("Hi "+name);

Here, we need to include this module into our main module to call the method displayMsg() defined
in the module named file.

PREPARED BY: DHABALIYA NIKITA 37


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ Loading the module in our python code


We need to load the module in our python code to use its functionality. Python provides two types
of statements as defined below.

1. The import statement


2. The from-import statement

1. The import statement


➢ The import statement is used to import all the functionality of one module into
another. Here, we must notice that we can use the functionality of any python source
file by importing that file as the module into another python source file.
➢ We can import multiple modules with a single import statement, but a module is
loaded once regardless of the number of times, it has been imported into our file.
➢ The syntax to use the import statement is given below.

import module1,module2,........ module n

➢ Hence, if we need to call the function displayMsg() defined in the file file.py, we have
to import that file as a module into our module as shown in the example below.

Example:

import file;
name = input("Enter the name?")
file.displayMsg(name)

Output:
Enter the name?John
Hi John

2. The from-import statement


➢ Instead of importing the whole module into the namespace, python provides the flexibility
to import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.

from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.

PREPARED BY: DHABALIYA NIKITA 38


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

calculation.py:

#place the code in the calculation.py


def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

Main.py:

from calculation import summation


#it will import only the summation() from
calculation.py a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing
su mmation()

Output:

Enter the first number10


Enter the second number20
Sum = 30

❖ Python File Handling


➢ Till now, we were taking the input from the console and writing it back to the console to
interact with the user.
➢ Sometimes, it is not enough to only display the data on the console. The data to be displayed
may be very large, and only a limited amount of data can be displayed on the console, and
since the memory is volatile, it is impossible to recover the programmatically generated data
again and again.
➢ However, if we need to do so, we may store it onto the local file system which is volatile and
can be accessed every time. Here, comes the need of file handling.
➢ In this section of the tutorial, we will learn all about file handling in python including,
creating a file, opening a file, closing a file, writing and appending the file, etc.

3. Opening a file
➢ Python provides the open() function which accepts two arguments, file name and access mode
in which the file is accessed. The function returns a file object which can be used to perform
various operations like reading, writing, etc.

Syntax:file object = open(<file-name>, <access-mode>, <buffering>)

PREPARED BY: DHABALIYA NIKITA 39


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

➢ The files can be accessed using various modes like read, write, or append. The following
are the details about the access mode to open a file.

Access Description
mode

R It opens the file to read-only. The file pointer exists at the beginning. The file is by
default open in this mode if no access mode is passed.

Rb It opens the file to read only in binary format. The file pointer exists at the beginning
of the file.

r+ It opens the file to read and write both. The file pointer exists at the beginning of the
file.

rb+ It opens the file to read and write both in binary format. The file pointer exists at the
beginning of the file.

W It opens the file to write only. It overwrites the file if previously exists or creates a
new one if no file exists with the same name. The file pointer exists at the beginning
of the file.

Wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists with the same name. The file pointer
exists at the beginning of the file.

w+ It opens the file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the previously
written file. It creates a new file if no file exists. The file pointer exists at the
beginning of the file.

wb+ It opens the file to write and read both in binary format. The file pointer exists at the
beginning of the file.

A It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with the
same name.

PREPARED BY: DHABALIYA NIKITA 40


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Ab It opens the file in the append mode in binary format. The pointer exists at the end
of the previously written file. It creates a new file in binary format if no file exists
with the same name.

a+ It opens a file to append and read both. The file pointer remains at the end of the file
if a file exists. It creates a new file if no file exists with the same name.

ab+ It opens a file to append and read both in binary format. The file pointer remains at
the end of the file.

Let's look at the simple example to open a file named "file.txt" (stored in the same directory) in read
mode and printing its content on the console.

Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")

if fileptr:
print("file is opened successfully")

Output:

<class '_io.TextIOWrapper'>
file is opened successfully

4. The close() method


➢ Once all the operations are done on the file, we must close it through our python script using the
close() method. Any unwritten information gets destroyed once the close() method is called on a
file object.
➢ We can perform any operation on the file externally in the file system is the file is opened
in python, hence it is good practice to close the file once all the operations are done.

SYNTAX:fileobject.close()

Consider the following example.

Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")

PREPARED BY: DHABALIYA NIKITA 41


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

if fileptr:
print("file is opened successfully")

#closes the opened file


fileptr.close()

5. Reading the file


➢ To read a file using the python script, the python provides us the read() method. The read() method
reads a string from the file. It can read the data in the text as well as binary format.

fileobj.read(<count>)

Here, the count is the number of bytes to be read from the file starting from the beginning of the file.
If the count is not specified, then it may read the content of the file until the end.

Consider the following example.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable


content content = fileptr.read(9);

# prints the type of the data stored in the


file print(type(content))

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Output:

<class 'str'>
Hi, I am

PREPARED BY: DHABALIYA NIKITA 42


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Read Lines of the file


Python facilitates us to read the file line by line by using a function readline(). The readline() method
reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can
get the first two lines of the file.

Consider the following example which contains a function readline() that reads the first line of our
file "file.txt" containing three lines.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");

#stores all the data of the file into the variable


content content = fileptr.readline();

# prints the type of the data stored in the


file print(type(content))

#prints the content of the file


print(content)

#closes the opened file


fileptr.close()

Output:

<class 'str'>
Hi, I am the file and being used as

Looping through the file


By looping through the lines of the file, we can read the whole file.

Example
fileptr = open("file.txt","r");

for i in fileptr:
print(i) # i contains each line of the file

PREPARED BY: DHABALIYA NIKITA 43


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

Output:

Hi, I am the file and being used as


an example to read a
file in python.

6. Writing the file


✓ To write some text to a file, we need to open the file using the open method with one of the
following access modes.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if
no file exists.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

Consider the following example.

Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");

#appending the content to the file


fileptr.write("Python is the modern day language. It makes things so simple.")

#closing the opened file


fileptr.close();

Now, we can see that the content of the file is modified.

File.txt:

Hi, I am the file and being used as


an example to read a
file in python.
Python is the modern day language. It makes things so simple.

Example 2
#open the file.txt in write mode.
fileptr = open("file.txt","w");

#overwriting the content of the file

PREPARED BY: DHABALIYA NIKITA 44


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

fileptr.write("Python is the modern day language. It makes things so simple.")

#closing the opened file


fileptr.close();

Now, we can check that all the previously written content of the file is overwritten with the new text
we have passed.

File.txt:

1. Python is the modern day language. It makes things so simple.

7. Creating a new file


The new file can be created by using one of the following access modes with the function open(). x: it
creates a new file with the specified name. It causes an error a file exists with the same name.

a: It creates a new file with the specified name if no such file exists. It appends the content to the file if
the file already exists with the specified name.

w: It creates a new file with the specified name if no such file exists. It overwrites the existing

file. Consider the following example.

Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x");

print(fileptr)

if fileptr:
print("File created successfully");

Output:

File created successfully

PREPARED BY: DHABALIYA NIKITA 45


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

✓ File Pointer positions


Python provides the tell() method which is used to print the byte number at which the file pointer exists.
Consider the following example.

Example
# open the file file2.txt in read
mode fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#reading the content of the file


content = fileptr.read();

#after the read operation file pointer modifies. tell() returns the location of the
file ptr.

print("After reading, the filepointer is at:",fileptr.tell())

Output:

The filepointer is at byte : 0


After reading, the filepointer is at 26

Modifying file pointer position


In the real world applications, sometimes we need to change the file pointer location externally since we
may need to read or write the content at various locations.

For this purpose, the python provides us the seek() method which enables us to modify the file
pointer position externally.

The syntax to use the seek() method is given below.

1. <file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

PREPARED BY: DHABALIYA NIKITA 46


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the current position of the file
pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the
reference position.

Consider the following example.

Example
# open the file file2.txt in read
mode fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.tell())

#changing the file pointer location to 10.


fileptr.seek(10);

#tell() returns the location of the fileptr.


print("After reading, the filepointer is at:",fileptr.tell())

Output:

The filepointer is at byte : 0


After reading, the filepointer is at 10

PREPARED BY: DHABALIYA NIKITA 47


UNIT-1 INTRODUCTION TO PYTHON BCA-2019

❖Python os module
The os module provides us the functions that are involved in file processing operations like
renaming, deleting, etc.

Let's look at some of the os module functions.

✓ Renaming the file


➢ The os module provides us the rename() method which is used to rename the specified file to a new
name. The syntax to use the rename() method is given below.

rename(?current-name?, ?new-name?)

Example
import os;

#rename file2.txt to file3.txt


os.rename("file2.txt","file3.txt")

✓ Removing the file


➢ The os module provides us the remove() method which is used to remove the specified file. The
syntax to use the remove() method is given below.

remove(?file-name?)

Example
import os;

#deleting the file named file3.txt


os.remove("file3.txt")

PREPARED BY: DHABALIYA NIKITA 48

You might also like