WHAT IS PROGRAMMING
LANGUAGE?
A programming language is a formal
computer language or constructed language
designed to communicate instructions to a
machine, particularly a computer.
Programming languages can be used to create
programs to control the behavior of a machine or
to express algorithms.
COMPILER VS INTERPRETER
An interpreter is a program that reads and executes
code. This includes source code, pre-compiled code,
and scripts.
Common interpreters include Perl, Python, and Ruby
interpreters, which execute Perl, Python, and Ruby
code respectively.
Interpreters and compilers are similar, since they
both recognize and process source code.
However, a compiler does not execute the code like
and interpreter does.
Instead, a compiler simply converts the source code
into machine code, which can be run directly by the
operating system as an executable program.
Interpreters bypass the compilation process and
execute the code directly.
interpreters are commonly installed on Web
servers, which allows developers to run executable
scripts within their webpages. These scripts can be
easily edited and saved without the need to
recompile the code.
without an interpreter, the source code serves as a
plain text file rather than an executable program.
INTRODUCTION OF PYTHON
Python is an object-oriented, high level
language, interpreted, dynamic and
multipurpose programming language.
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 in many
areas.
Python supports multiple programming pattern,
including object oriented programming, imperative
and functional programming or procedural styles.
Python is not intended to work on special area such
as web programming. That is why it is known as
multipurpose 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 declare an integer value in a
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.
It is used for GUI and database programming,
client- and server-side web programming, and
application testing.
It is used by scientists writing applications for the
world's fastest supercomputers and by children
first learning to program.
HISTORY OF PYTHON
Python was conceptualized by Guido Van Rossum in
the late 1980s.
Rossum published the first version of Python code
(0.9.0) in February 1991 at the CWI (Centrum
Wiskunde & Informatica) in the Netherlands ,
Amsterdam.
Python is derived from ABC programming language,
which is a general-purpose programming language that
had been developed at the CWI.
Rossum chose the name "Python", since he was a big
fan of Monty Python's Flying Circus.
Python is now maintained by a core development team
at the institute, although Rossum still holds a vital role
in directing its progress.
PYTHON VERSIONS
Release dates for the major and minor versions:
Python 1.0 - January 1994
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000
Python 2.0 - October 16, 2000
Python 2.1 - April 17, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
PYTHON VERSIONS
Release dates for the major and minor versions:
Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python 3.6- December 23,2017
Python 3.7.3- March 25, 2019
Python 3.7.4- July 8, 2019
Python 3.9.4 April 4, 2021
Python 3.10.0 January 14, 2022
Python 3.11.0 October 24,2022
PYTHON FEATURES
Easy to learn, easy to read and easy to maintain.
Portable: It can run on various hardware platforms and has the same
interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter.
Scalable: Python provides a good structure and support for large
programs.
Python has support for an interactive mode of testing and debugging.
Python has a broad standard library cross-platform.
Everything in Python is an object: variables, functions, even code.
Every object has an ID, a type, and a value.
MORE FEATURES ..
Python provides interfaces to all major commercial databases.
Python supports functional and structured programming methods as well
as OOP.
Python provides very high-level dynamic data types and supports
dynamic type checking.
Python supports GUI applications
Python supports automatic garbage collection.
Python can be easily integrated with C, C++, and Java.
INTERNAL WORKING OF PYTHON
We know that computers understand only
machine code that comprises 1s and 0s.
Since computer understands only machine code, it is
imperative that we should convert any program
into machine code before it is submitted to the
computer for execution.
For this purpose, we should take the help of a
compiler.
A compiler normally converts the program
source code into machine code.
The role of Python Virtual Machine (PVM) is to
convert the byte code instructions into machine code
so that the computer can execute those machine
code instructions and display the final output.
To carry out this conversion, PVM is equipped with an
interpreter.
The interpreter converts the byte code into machine
code and sends that machine code to the computer
processor for execution.
Since interpreter is playing the main role, often the
Python Virtual Machine is also called an interpreter.
The Basic Elements of Python
A Python program, sometimes called a script, is a
sequence of definitions and commands.
These definitions are evaluated and the commands
are executed by the Python interpreter in something
called the shell.
Typically, a new shell is created whenever execution
of a program begins. In most cases, a window is
associated with the shell.
A command, often called a statement, instructs the
interpreter to do something.
For example, the statement print 'Yankees rule!'
instructs the interpreter to output the string Yankees
rule! to the window associated with the shell.
The sequence of commands
print ('Yankees rule!‘)
print ('But not in Boston!' )
print ('Yankees rule,', 'but not in Boston!' )
causes the interpreter to produce the output
Yankees rule!
But not in Boston!
Yankees rule, but not in Boston!
Notice that two values were passed to print in the
third statement.
The print command takes a variable number of
values and prints them, separated by a space
character, in the order in which they appear.
Objects, Expressions, and
Numerical Types
Objects are the core things that Python
programs manipulate.
Every object has a type that defines the kinds of
things that programs can do with objects of that
type.
Python has four types of scalar objects:
int is used to represent integers. Literals of type int are written in
the way we typically denote integers (e.g., -3 or 5 or 10002).
float is used to represent real numbers. Literals of type float
always include a decimal point (e.g., 3.0 or 3.17 or -28.72). (It is
also possible to write literals of type float using scientific notation.
For example, the literal 1.6E3 stands for 1.6 * 10 , i.e., it is the
same as 1600.0.) You might wonder why this type is not called
real.
Within the computer, values of type float are stored in the
computer as floating point numbers. This representation,
which is used by all modern programming languages, has many
advantages. However, under some situations it causes floating
point arithmetic to behave in ways that are slightly different from
arithmetic on real numbers.
• bool is used to represent the Boolean values True and False.
• None is a type with a single value.
The == operator is used to test whether two expressions
evaluate to the same value, and the != operator is used to
test whether two expressions evaluate to different values.
The symbol >>> is a shell prompt indicating that the
interpreter is expecting the user to type some Python code
into the shell.
The line below the line with the prompt is produced when the
interpreter evaluates the Python code entered at the prompt,
as illustrated by the following interaction with the interpreter:
>>> 3 + 2 5
>>> 3.0 + 2.0 5.0
>>> 3 != 2 True
The built-in Python function type can be used
to find out the type of an object:
>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>
Variables and Assignment
Variables provide a way to associate names with
objects. Consider the code.
In Python, a variable is just a name, nothing more.
An assignment statement associates the name to
the left of the = symbol with the object denoted by
the expression to the right of the =.
Remember this too. An object can have one, more
than one, or no name associated with it.
In Python, variable names can contain uppercase and
lowercase letters, digits (but they cannot start
with a digit), and the special character _.
Python variable names are case-sensitive e.g.,
Sankul and sankul are different names.
Finally, there are a small number of reserved words
(sometimes called keywords) in Python that have
built-in meanings and cannot be used as variable
names.
Different versions of Python have slightly different
lists of reserved words.
The reserved words in Python 2.7 are and, as,
assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or,pass, print, raise,
return, try, with, while, and yield. (31).
PYTHON KEYWORDS
Total 35 Reserved Keywords in python 3.10.2.
Python allows multiple assignment.
The statement
x, y = 2, 3
binds x to 2 and y to 3.
All of the expressions on the right-hand side of the
assignment are evaluated before any bindings are
changed. This is convenient since it allows you to
use multiple assignment to swap the bindings of
two variables.
For example, the code
x, y = 2, 3
x, y = y, x
print( 'x =', x)
print('y =', y)
will print
x = 3 y = 2
OPERATORS IN PYTHON
Operators in Python are special symbols used to
perform operations on values or variables.
Arithmetic, Comparison, Logical, and
Assignment operators are the most commonly
used.
Objects and operators can be combined to form
expressions, each of which evaluates to an
object of some type. We will refer to this as the
value of the expression.
For example, the expression 3 + 2 denotes the
object 5 of type int, and the expression 3.0 + 2.0
denotes the object 5.0 of type float.
ARITHMETIC OPERATORS
Arithmetic operators are used for mathematical
computations like addition, subtraction,
multiplication, etc.
They generally operate on numerical values and
return a numerical value.
They’re also referred to as mathematical operators.
Operato Description Syntax
r
+ Addition – Adds two operands. x+y
Subtraction – Subtracts the right operand
– x-y
from the the left operand.
* Multiplication – Multiplies two operands. x*y
Division – Divides the left operand by the
/ x/y
right one. Results in a float value.
Integer Division – Divides the left operand
// x//y
by the right one. Results in an integer value.
Modulus – Gives the remainder on dividing
% x%y
the left operand by the right one.
Exponent – Raises the left operand to the
** x**y
power of the right one.
COMPARISON OPERATORS
Comparison operators are used for comparing two
values. As an output, they return a boolean
value, either True or False.
Operator Description Syntax
== Equal to – True if both operands are equal x==y
!= Not equal to – True if operands are not equal x!=y
Greater than – True if the left operand is
> x>y
greater than the right operand.
Less than – True if the left operand is less
< x<y
than the right operand.
Greater than equal to – True if the left
>= operand is greater than or equal to the right x>=y
one.
== Equal to – True if both operands are equal x==y
!= Not equal to – True if operands are not equal x!=y
LOGICAL OPERATORS
These operators are used to perform
logical and, or, and not operations.
They operate on boolean values and return a
boolean value.
Operator Description Syntax
Logical AND – True if both the operands are
and x and y
true
Logical OR – True if either of the operands are
or x or y
true
not NOT – Boolean compliment of the operand not x
print(x>3 and x<10)
ASSIGNMENT OPERATORS
Python has an assignment operator that helps to
assign values or expressions to the left-hand-side
variable.
The assignment operator is represented as the "="
symbol used in assignment statements and
assignment expressions.
In the assignment operator, the right-hand side value
or operand is assigned to the left-hand operand.
Following are the examples of the assignment
operators:
x = 8 # here 8 is assigned to the x (left side operand)
y = 20 # here 20 is assigned to the x (left side operand)
c = a + b - 5 # here the value of expression a + b -
5 is assigned to c
Operato Description Syntax
r
= Assigns values from right side operands c = a + b assigns
to left side operand value of a + b into
c
+= It adds right operand to the left operand c += a is
and assign the result to left operand equivalent to c = c
+a
-= It subtracts right operand from the left c -= a is
operand and assign the result to left equivalent to c = c
operand -a
*= It multiplies right operand with the left c *= a is
operand and assign the result to left equivalent to c = c
operand *a
/= It divides left operand with the right c /= a is
operand and assign the result to left equivalent to c = c
operand /a
%= It takes modulus using two operands c %= a is
and assign the result to left operand equivalent to c = c
%a
IDENTITY OPERATORS
Identity operators are special operators in python which are
used to compare two operands based on the memory
location they refer to.
is and is not are the two identity operators used in python.
Operato Description Syntax
r
True if the two operands refer to the same
is x is y
memory location
True if the two operands do not refer to the
is not x is not y
same memory location
MEMBERSHIP OPERATORS
Membership operators are also special operators in
python which are used to determine whether a
value or variable is present in a sequence (string,
list, tuple, set, and dictionary).
in and not in are the membership operators used
in Python.
x = 2
y = [1, 2, 3]
Operato Description Syntax
r
True if the value or variable is present in the
in x in y
sequence
True if the value or variable is not present in
not in x not in y
the sequence
BITWISE OPERATORS
Bitwise operators operate on the binary values of the operands
bit-by-bit.
The values are first converted to binary, and then manipulations
are done bit by bit, hence the phrase "bitwise operators." The
outcome is then displayed in decimal numbers.
Operato Description Syntax
r
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right
shift and let the leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost
shift bit in from the left, and let the rightmost bits
fall off
A B A&B A|B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
IDLE
Typing programs directly into the shell is highly inconvenient.
Most programmers prefer to use some sort of text editor that
is part of an integrated development environment (IDE).
The IDE that comes as part of the standard Python installation
package.
IDLE is an application, just like any other application on your
computer.
Start it the same way you would start any other application,
e.g., by double-clicking on an icon.
IDLE provides
a text editor with syntax highlighting, auto completion, and
smart indentation,
a shell with syntax highlighting, and
an integrated debugger, which you should ignore for now.
When IDLE starts it will open a shell window into
which you can type Python commands.
It will also provide you with a file menu and an edit
menu (as well as some other menus, which you can
safely ignore for now).
The file menu includes commands to
create a new editing window into which you can type a
Python program,
open a file containing an existing Python program, and
save the contents of the current editing window into a
file (with file extension .py).
The edit menu includes standard text-editing
commands (e.g., copy, paste, and find) plus some
commands specifically designed to make it easy to
edit Python code (e.g., indent region and comment
out region).
Basic Syntax
Indentation is used in Python to delimit blocks. The
number of spaces is variable, but all statements within the
same block must be indented the same amount.
The header line for compound statements, such as if, while,
def, and class should be terminated with a colon ( : ) Error!
The semicolon ( ; ) is optional at the end of statement.
Printing to the Screen:
Reading Keyboard Input:
Comments
Single line:
Multiple lines:
Python files have extension .py
Branching Programs
Python programming language provides following
types of decision making or branching statements in
Python.
if statement
An if statement consists of a boolean expression followed by
one or more statements .
if else statement
An if statement can be followed by an optional else
statement , which executes when the boolean expression is
false .
if elif else statement (nested if statement)
You can use one if elif else statements as nested if
statements in other programming languages.
IF CONDITION
This statement is used to test the condition
only.
EXAMPLE
a=int(input("enter a number : "))
if a>0:
print('postive values')
password = "qwerty"
attempt = input("Enter password: ")
if attempt == password:
print("Welcome")
IF ELSE CONDITION
This statement is used to test the condition.
When the condition is true, then a true statement
is executed.
When the condition is false, then a false statement
is executed.
EXAMPLE
num=int(input("enter the age : "))
if (num>18):
print('you can vote')
else:
print('you are not eligible')
mark1 = int(input("\nEnter First mark : "))
mark2 = int(input("Enter Second mark : "))
mark3 = int(input("Enter Third mark : "))
if (mark1 == mark2) and (mark2 == mark3):
print("All marks are same")
else:
print("NOT all Three are same")
PYTHON IF...ELIF...ELSE STATEMENT
The elif is short for else if. It allows us to check for
multiple expressions.
If the condition for if is False, it checks the
condition of the next elif block and so on.
If all the conditions are False, the body of else is
executed.
Only one block among the several if...elif...else
blocks is executed according to the condition.
The if block can have only one else block. But it
can have multiple elif blocks.
SYNTAX OF IF...ELIF...ELSE
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
FLOWCHART OF IF...ELIF...ELSE
EXAMPLE
age=int(input('enter the age is : '))
if age <= 5:
print("free ticket")
elif age <=18:
print("ticket Rs: 10")
elif age <=30:
print("ticket Rs: 20")
else:
print("ticket Rs:30")
age=int(input("Enter your age : "))
if age < 6:
print('Hello little one')
elif age >= 6 and age < 10:
print('Are you enjoying school?')
elif age >= 10 and age < 13:
print('You are a Tween now')
elif age >= 13 and age < 20:
print('Now you are officially a teenager')
else:
print('Welcome to the real world')
Finger exercise: Write a program that
examines three variables—x, y, and z— and
prints the largest odd number among them.
If none of them are odd, it should print a
message to that effect.
Strings and Input
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"
Objects of type str are used to represent strings of characters.11 Literals
of type str can be written using either single or double quotes, e.g., 'abc'
or "abc".
The literal '123' denotes a string of characters, not the number one
hundred twenty-three.
Try typing the following expressions in to the Python interpreter
(remember that the >>> is a prompt, not something that you type):
>>> 'a'
>>> 3*4
>>> 3*'a'
>>> 3+4
>>> 'a'+'a'
The operator + is said to be overloaded: It has different meanings
depending upon the types of the objects to which it is applied.
For example, it means addition when applied to two numbers and
concatenation when applied to two strings. The operator * is also
overloaded. It means what you expect it to mean when its operands are
both numbers. When applied to an int and a str, it duplicates the str. For
'JohnJohn'. There is a logic to this. Just as the
expression 3*2 is equivalent to
2+2+2, the expression 3*'a' is equivalent to 'a'+'a'+'a'.
Now try typing
>>> a
>>> 'a'*'a'
Each of these lines generates an error message.
The first line produces the message
NameError: name 'a' is not defined
Because a is not a literal of any type, the interpreter
treats it as a name.
However, since that name is not bound to any
object, attempting to use it causes a runtime error.
The code 'a'*'a' produces the error message
TypeError: can't multiply sequence by non-int of type 'str'
Escape Characters
An escape character lets you use characters that are
otherwise impossible to put into a string.
An escape character consists of a backslash (\) followed by
the character you want to add to the string. (Despite
consisting of two characters, it is commonly referred to as a
singular escape character.)
For example, the escape character for a single quote is \'.
You can use this inside a string that begins and ends with
single quotes. To see how escape characters work, enter
the following into the interactive shell:
>>> spam = 'Say hi to shubham\'s mother.'
Python knows that since the single quote in shubham\'s has
a backslash, it is not a single quote meant to end the string
value.
The escape characters \' and \" let you put single quotes
and double quotes inside your strings, respectively.
`
>>> print("Hello there!\nHow are you?\
nI\'m doing fine.")
Hello there!
How are you?
I'm doing fine.
Raw Strings
You can place an r before the beginning quotation
mark of a string to make it a raw string.
A raw string completely ignores all escape
characters and prints any backslash that
appears in the string.
For example, type the following into the interactive
shell:
>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.
Because this is a raw string, Python considers the
backslash as part of the string and not as the
start of an escape character.
Raw strings are helpful if you are typing string values
that contain many backslashes, such as the strings
used for regular expressions described in the next
chapter.
Multiline Strings with Triple
Quotes
While you can use the \n escape character to put a
newline into a string, it is often easier to use
multiline strings.
A multiline string in Python begins and ends with
either three single quotes or three double quotes.
Any quotes, tabs, or newlines in between the
“triple quotes” are considered part of the string.
Python’s indentation rules for blocks do not apply
to lines inside a multiline string.
print('''Dear Alice, Eve's cat has been
arrested for catnapping, cat burglary, and
extortion. Sincerely, Bob''')
Indexing and Slicing Strings
Strings use indexes and slices the same way lists
do. You can think of the string 'Hello world!' as a list
and each character in the string as an item with a
corresponding index.
' H e l l o w o r l d ! '
0 1 2 3 4 5 6 7 8 9 10 11
The space and exclamation point are included in the
character count, so 'Hello world!' is 12 characters
long, from H at index 0 to ! at index 11.
>>> spam = 'Hello If you specify an index, you’ll
world!' get the character at that
>>> spam[0] position in the string. .
'H‘ If you specify a range from
>>> spam[4] one index to another, the
'o‘ starting index is included and
>>> spam[-1] the ending index is not.
'!' That’s why, if spam is 'Hello
>>> spam[0:5] world!', spam[0:5] is 'Hello'.
'Hello' The substring you get from
>>> spam[:5] spam[0:5] will include
'Hello' everything from spam[0] to
>>> spam[6:] spam[4], leaving out the
'world!' space at index 5.
Note that slicing a string does not modify the
original string. You can capture a slice from one
variable in a separate variable.
Try typing the following into the interactive shell:
>>> spam = 'Hello world!‘
>>> fizz = spam[0:5]
>>> fizz 'Hello'
By slicing and storing the resulting substring in
another variable, you can have both the whole
string and the substring handy for quick, easy
access.
The in and not in Operators with Strings
The in and not in operators can be used with strings just like
with list values.
An expression with two strings joined using in or not in will
evaluate to a Boolean True or False.
Enter the following into the interactive shell:
>>> 'Hello' in 'Hello World'
True
>>> 'Hello' in 'Hello'
True
>>> 'HELLO' in 'Hello World'
False
>>> '' in 'spam'
True
>>> 'cats' not in 'cats and dogs'
False
These expressions test whether the first string (the exact string,
case sensitive) can be found within the second string.
upper(), lower(), isupper(), and islower()
String Methods
The upper() and lower() string Note that these methods do not
methods return a new string change the string itself but return
where all the letters in the new string values.
original string have been If you want to change the original
converted to uppercase or
lower-case, respectively. string, you have to call upper() or
lower() on the string and then
Nonletter characters in the
assign the new string to the
string remain unchanged.
variable where the original was
Enter the following into the stored.
interactive shell:
This is why you must use spam =
>>> spam = 'Hello world!'
spam.upper() to change the string
>>> spam = spam.upper() in spam instead of simply
>>> spam 'HELLO WORLD!' spam.upper(). (This is just like if a
>>> spam = spam.lower() variable eggs contains the value
>>> spam 'hello world!' 10.
Writing eggs + 3 does not change
the value of eggs, but eggs =
eggs + 3 does.)
The upper() and lower() The isupper() and islower()
methods will return a Boolean
methods are helpful if True value if the string has at
you need to make a least one letter and all the letters
case-insensitive are uppercase or lowercase,
comparison. The strings respectively. Otherwise, the
method returns False. Enter the
'great' and 'GREat' are following into the interactive
not equal to each other. shell, and notice what each
But in the following method call returns:
small program, it does >>> spam = 'Hello world!'
not matter whether the >>> spam.islower()
user types Great, False
GREAT, or grEAT, >>> spam.isupper()
because the string is False
first converted to >>> 'HELLO'.isupper()
True
lowercase.
print('How are you?')
>>> 'abc12345'.islower()
True
feeling = input()
if feeling.lower() == >>> '12345'.islower()
'great': False
print('I feel great too.') >>> '12345'.isupper()
else: False
print('I hope the rest of
The isX String Methods
Along with islower() and isupper(), there are several
string methods that have names beginning with the
word is. These methods return a Boolean value that
describes the nature of the string. Here are some
common isX string methods:
isalpha() returns True if the string consists only of
letters and is not blank.
isalnum() returns True if the string consists only of
letters and numbers and is not blank.
isdecimal() returns True if the string consists only of
numeric characters and is not blank.
isspace() returns True if the string consists only of
spaces, tabs, and new-lines and is not blank.
istitle() returns True if the string consists only of
words that begin with an uppercase letter followed by
only lowercase letters.
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
>>> 'This Is Title Case 123'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case Either'.istitle()
False
The startswith() and endswith() String
Methods
The startswith() and endswith() methods return True if the
string value they are called on begins or ends (respectively)
with the string passed to the method; otherwise, they return
False. Enter the following into the interactive shell:
>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
>>> 'Hello world!'.startswith('Hello world!')
True
>>> 'Hello world!'.endswith('Hello world!')
True
The join() and split() String Methods
The join() method is useful when you have a list of strings that
need to be joined together into a single string value.
The join() method is called on a string, gets passed a list
of strings, and returns a string.
The returned string is the concatenation of each string
in the passed-in list.
For example, enter the following into the interactive shell:
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats' `
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon‘
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
Notice that the string join() calls on is inserted between each
string of the list argument. For example, when join(['cats',
'rats', 'bats']) is called on the ', ' string, the returned string is
‘cats, rats, bats’.
The split() method does the opposite: It’s
called on a string value and returns a list of
strings. Enter the following into the
interactive shell:
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
The length of a string can be found using
the len function.
For example,
the value of len('abc') is 3.
Input
Used to get input directly from a user.
Each takes a string as an argument and displays it as a
prompt in the shell. It then waits for the user to type
something, followed by hitting the enter key.
For input, the input line is treated as a string and
becomes the value returned by the function;
input treats the typed line as a Python expression and infers a
type.
>>> name = input(“Enter your name: “)
Enter your name: George Washington
Iteration
This kind of a for loop iterates over an enumeration
of a set of items.
It is usually characterized by the use of an implicit
or explicit iterator.
In each iteration step a loop variable is set to a
value in a sequence or other data collection.
Syntax of the For Loop
the Python for loop is an iterator based for loop. It
steps through the items of lists, tuples, strings, the
keys of dictionaries and other iterables.
The Python for loop starts with the keyword "for"
followed by an arbitrary variable name, which will
hold the values of the following sequence object,
which is stepped through.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first.
Then, the first item in the sequence is assigned to the iterating
variable iterating_var. Next, the statements block is executed.
Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is
exhausted.
Example
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset
into the sequence itself. Following is a simple example −
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print (“Current fruit :”, fruits[index] )
print ("Good bye!" )
The len() built-in function, which provides the total number of
elements in the tuple as well as the range() built-in function to give
us the actual sequence to iterate over.
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print (x)
for x in range(3, 6):
print (x)
for x in range(3, 8, 2):
print (x)
Using else Statement with Loops
Python supports to have an else statement
associated with a loop statement
If the else statement is used with a for loop,
the else statement is executed when the loop
has exhausted iterating the list.
If the else statement is used with a while loop,
the else statement is executed when the
condition becomes false.
while Loop
A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.
Syntax
The syntax of a while loop in Python programming language is
−
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of
statements. The condition may be any expression, and true is
any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to
the line immediately following the loop.
In Python, all the statements indented by the same number of
character spaces after a programming construct are considered
to be part of a single block of code.
Python uses indentation as its method of grouping statements.
Here, key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.
count = 0
while (count < 9):
print ('The count is:', count)
count=count + 1
print ("Good bye!" )
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
"break" and "continue" statements
break is used to exit a for loop or a while loop, whereas
continue is used to skip the current block, and return to
the "for" or "while" statement.
# Prints out 0,1,2,3,4
count = 0
while True:
print (count)
count += 1
if count >= 5:
break
for x in range(10):
if x % 2 == 0:
continue
print (x)
"else" clause for loops
# Prints out 0,1,2,3,4 and # Prints out 1,2,3,4
then it prints "count for i in range(1,10):
value reached 5"
if(i%5==0):
count=0
break
while(count<5):
print (i)
print (count)
else:
count +=1
print ("this is not printed
else: because for loop is
print ("count value reached terminated because of
%d" %(count) ) break but not due to fail in
condition")
Python nested loops
A final note on loop
Python programming language nesting is that you can
allows to use one loop inside put any type of loop
another loop. inside of any other type
for iterating_var in of loop. For example a
sequence: for loop can be inside a
for iterating_var in while loop or vice versa.
sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
Tuples
Tuple is a sequence of immutable Python objects. Tuples are
sequences, just like lists.
The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing
nothing
tup1 = ();
To write a tuple containing a single value you have to include
a comma, even though there is only one value −
tup1 = (50,);
Updating Tuples
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
tup1[0] = 100; #Error
print(tup1[0])
tup3 = tup1 + tup2;
print (tup3)
Delete Tuple Elements
Removing individual tuple tup = ('physics',
elements is not possible. 'chemistry', 1997, 2000);
There is, of course, nothing
wrong with putting print (tup)
together another tuple
with the undesired
elements discarded. del (tup)
To explicitly remove an
entire tuple, just use the print ("After deleting tup :
del statement. ")
print (tup)
Basic Tuples Operations
Tuples respond to the + and * operators much
like strings; they mean concatenation and
repetition here too, except that the result is a
new tuple, not a string.
Indexing & Slicing
Because tuples are sequences, indexing and slicing
work the same way for tuples as they do for strings.
Assuming following input −
L = ('spam', 'Spam', 'SPAM!')
TUPLE METHODS
List
A list is a data structure that holds an ordered
collection of items i.e. you can store a sequence of
items in a list.
This is easy to imagine if you can think of a shopping
list where you have a list of items to buy, except that
you probably have each item on a separate line in
your shopping list whereas in Python you put commas
in between them.
The list of items should be enclosed in square
brackets so that Python understands that you are
specifying a list.
Once you have created a list, you can add, remove or
search for items in the list.
Since we can add and remove items, we say that a list
is a mutable data type i.e. this type can be altered.
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Accessing Values in Lists
To access values list1 = ['physics',
in lists, use the 'chemistry', 1997, 2000];
square brackets list2 = [1, 2, 3, 4, 5, 6, 7 ];
for slicing along
with the index or
indices to obtain print ("list1[0]: ", list1[0])
value available print ("list2[1:5]: ",
at that index. list2[1:5])
a[start:end] # items start through end-1
a[start:] # items start through the rest
of the array
a[:end] # items from the beginning
through end-1
a[:] # a copy of the whole array
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two
items
Updating Lists
You can update list = ['physics', 'chemistry',
single or multiple 1997, 2000];
elements of lists
by giving the slice print ("Value available at index
2 : “)
on the left-hand
side of the
assignment print (list[2])
operator, and you
can add to list[2] = 2001;
elements in a list
with the append() print ("New value available at
method. index 2 : “)
print (list[2])
Delete List Elements
To remove a list list1 = ['physics', 'chemistry',
element, you can 1997, 2000];
use either the del
statement if you
print (list1)
know exactly which
element(s) you are
deleting or the del list1[2];
remove() method if
you do not know. print ("After deleting value at
index 2 : “)
print (list1)
List Comprehension
List comprehension provides a clearly way to
apply an operation to the values in a sequence.
It creates a new list in which each element is the
result of applying a given operation to a value from
a sequence (e.g., the elements in another list).
The Syntax
newlist = [expression for item in iterable if condition ==
True]
The return value is a new list, leaving the old list
unchanged.
Condition
The condition is like a filter that only accepts the items
that valuate to True.
#Example-1
L = [x**2 for x in range(1,7)]
print (L)
#Example-2
mixed = [1, 2, 'a', 3, 4.0]
print ([x**2 for x in mixed if type(x) == int])
CONVERT LIST TO TUPLE
•Convert list to a tuple
listNumbers = [6,3,7,4]
x = tuple(listNumbers)
print(x)
•Convert tuple to list
x = (4,5)
listNumbers = list(x)
print(listNumbers)
•Convert tuple to string
•person = ('Diana','Canada','CompSci')
s = ' '.join(person)
print(s)
Python Dictionary
Each key is separated from its value by a
colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces.
An empty dictionary without any items is written
with just two curly braces, like this: {}.
Keys are unique within a dictionary while values
may not be.
The values of a dictionary can be of any
type, but the keys must be of an
immutable data type such as strings,
numbers, or tuples.
ACCESSING VALUES IN DICTIONARY
To access dictionary elements, you can use
the familiar square brackets along with the
key to obtain its value.
Example.
dict = {'Name': 'Zara', 'Age': 7, 'Class':
'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
UPDATING DICTIONARY
You can update a dictionary by adding a new
entry or a key-value pair, modifying an existing
entry, or deleting an existing entry.
Example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
DELETE DICTIONARY ELEMENTS
You can either remove individual dictionary
elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in
a single operation.
To explicitly remove an entire dictionary, just use
the del statement.
PROPERTIES OF DICTIONARY
KEYS
Dictionary values have no restrictions. They can
be any arbitrary Python object, either standard
objects or user-defined objects. However, same is
not true for the keys.
There are two important points to remember
about dictionary keys −
(a) More than one entry per key not allowed.
Which means no duplicate key is allowed. When
duplicate keys encountered during assignment,
the last assignment wins.
dict = {'Name': 'Zara', 'Age': 7, 'Name':
'Manni'}
print "dict['Name']: ", dict['Name']
(b) Keys must be immutable. Which means
you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is
not allowed. Following is a simple example:
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
FUNCTIONS AND SCOPING,
SPECIFICATIONS,
FUNCTIONS AS OBJECTS
GLOBAL VARIABLES,
RECURSION,
MODULES,
FILES
FUNCTION
Function is block of code that is also called by its name.
(independent)
The function can have different parameters or may not
have any at all.
If any data (parameters) are passed, they are passed
explicitly.
It may or may not return any data.
Function does not deal with Class and its instance concept.
METHOD
Method is called by its name, but it is associated
to an object (dependent).
A method is implicitly passed the object on
which it is invoked.
It may or may not return any data.
A method can operate on the data (instance
variables) that is contained by the
corresponding class
DIFFERENCE BETWEEN METHOD AND
FUNCTION
Simply, function and method both look similar as
they perform in almost similar way, but the key
difference is the concept of ‘Class and its
Object‘.
Functions can be called only by its name, as it
is defined independently.
But methods can’t be called by its name only,
we need to invoke the class by a reference of that
class in which it is defined, i.e. method is defined
within a class and hence they are dependent on
that class.
Python 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.
Defining a Function
You 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. You can also define
parameters inside these parentheses.
The first statement of a function can be an
optional statement - the documentation string of the
function or docstring.
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.
FUNCTION ARGUMENTS
You can call a function by using the
following types of formal arguments:
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Arbitrary Arguments
Required arguments (positional arguments)
Required arguments are the arguments
passed to a function in correct positional
order.
Here, the number of arguments in the
function call should match exactly with the
function definition.
To call the function printme(), you definitely
need to pass one argument, otherwise it
gives a syntax error as follows:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
def add(a, b):
print(a - b)
add(50, 10)
# Output 40
add(10, 50)
# Output -40
Keyword arguments
Keyword arguments are those arguments
where values get assigned to the
arguments by their keyword
(name) when the function is called.
It is preceded by the variable name and an
(=) assignment operator.
The Keyword Argument is also called a
named argument.
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.
# function with 2 keyword arguments
def student(name, age):
print('Student Details:', name, age)
# default function call
student('Jessa', 14)
# both keyword arguments
student(name='Jon', age=12)
# 1 positional and 1 keyword
student('Donald', age=13)
Default arguments
Thedefault value of an argument will be
used inside a function if we do not pass a
value to that argument at the time of the
function call.
Dueto this, the default arguments
become optional during the function call.
# function with 2 keyword arguments grade and school
def student(name, age, grade="Five", school="ABC
School"):
print('Student Details:', name, age, grade, school)
# without passing grade and school
# Passing only the mandatory arguments
student('Jon', 12)
Variable-length argument
You may need to process a function for more arguments than
you 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
this.
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
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.
THERE ARE TWO TYPES OF VARIABLE-
LENGTH ARGUMENTS IN PYTHON-
Non - Keyworded Arguments denoted as
(*args)
Keyworded Arguments denoted as (**kwargs)
The *args and **kwargs allow you to pass multiple
positional arguments or keyword arguments to a
function.
ARBITRARY ARGUMENTS, *ARGS
If you do not know how many arguments that will
be passed into your function, add a * before the
parameter name in the function definition.
This way the function will receive a tuple of
arguments, and can access the items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
ARBITRARY KEYWORD ARGUMENTS,
**KWARGS
If you do not know how many keyword arguments that will be
passed into your function, add two asterisk: ** before the
parameter name in the function definition.
This way the function will receive a dictionary of arguments,
and can access the items accordingly:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = “Raviraj", lname = “Shubham")
# function with variable-length keyword arguments
def percentage(**kwargs):
for sub in kwargs:
# get argument name
sub_name = sub
# get argument value
sub_marks = kwargs[sub]
print(sub_name, "=", sub_marks)
# pass multiple keyword arguments
percentage(java=56, DW=61, python=73)
return statement
The return statement is used to return from a function i.e.
break out of the function. We can optionally return a value
from the function as well.
Every function implicitly contains a return None statement.
You can see this by running print someFunction() where the
function someFunction does not use the return statement
OBJECTS
First class objects in a language are handled
uniformly throughout.
They may be stored in data structures, passed as
arguments, or used in control structures.
A programming language is said to support first-class
functions if it treats functions as first-class objects.
Python supports the concept of First Class functions.
Properties of first class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another
function.
You can return the function from a function.
You can store them in data structures such as hash tables,
lists, …
Functions are objects:
Python functions are first class objects.
In the example below, we are assigning function to
a variable.
This assignment doesn’t call the function.
It takes the function object referenced by shout and
creates a second name pointing to it, yell.
# Python program to illustrate functions
# can be treated as objects
def shout(text):
return text.upper()
print (shout('Hello'))
yell = shout
print (yell('Hello'))
Functions can be passed as arguments to other functions:
Because functions are objects we can pass them as arguments to
other functions.
Functions that can accept other functions as arguments are also
called higher-order functions.
In the example below, we have created a function greet which
takes a function as an argument.
def shout(text):
return text.upper()
def disp(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an
argument.")
print (greeting)
greet(shout)
greet(disp)
Functions can return another function:
Because functions are objects we can return a function
from another function. In the below example, the
create_adder function returns adder function.
# Python program to illustrate functions
# Functions can return another function
def create_adder(x):
def adder(y):
return x+y
return adder
add_15 = create_adder(15)
print add_15(10)
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
functions.
When you call a function, the variables declared inside
it are brought into scope.
GLOBAL KEYWORD
In Python, global keyword allows you to modify the
variable outside of the current scope.
It is used to create a global variable and make
changes to the variable in a local context.
Rules of global Keyword
The basic rules for global keyword in Python are:
When we create a variable inside a function, it’s local by
default.
When we define a variable outside of a function, it’s
global by default. You don’t have to use global keyword.
We use global keyword to read and write a global
variable inside a function.
Use of global keyword outside a function has no effect
ACCESSING GLOBAL VARIABLE
FROM INSIDE A FUNCTION
c = 1 # global variable
def add():
print(c)
add()
MODIFYING GLOBAL VARIABLE
FROM INSIDE THE FUNCTION
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
CHANGING GLOBAL VARIABLE
FROM INSIDE A FUNCTION USING
GLOBAL
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print("Inside add():", c)
add()
print("In main:", c)
Recursion
A function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as
recursive functions.
Following is an example of recursive function to find the
factorial of an integer.
Factorial of a number is the product of all the integers from 1 to
that number. For example, the factorial of 6 (denoted as 6!) is
1*2*3*4*5*6 = 720.
Advantages of recursion
Recursive functions make the code look clean and stylish.
A complex task can be broken down into simpler sub-problems using
recursion.
Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of recursion
Sometimes the logic behind recursion is hard to follow through.
Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
Recursive functions are hard to debug.
CREATING OUR OWN MODULES IN
PYTHON
A module allows you to logically organize your
Python code. Grouping related code into a module
makes the code easier to understand and use.
A module is a Python object with arbitrarily named
attributes that you can bind and reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and
variables. .
A module can also include runnable code.
The import Statement
You can use any Python source file as a
module by executing an import statement
in some other Python source file.
The import has the following syntax:
import module1[, module2[,...
moduleN]
When the interpreter encounters an
import statement, it imports the module if
the module is present in the search path.
A search path is a list of directories that
the interpreter searches before importing
a module.
The from...import Statement
Python's from statement lets you import specific
attributes from a module into the current
namespace. The from...import has the following
syntax −
from modname import name1[, name2[, ...
nameN]]
The from...import * Statement:
It is also possible to import all names from
a module into the current namespace by
using the following import statement −
from modname import *
This provides an easy way to import all the
items from a module into the current
namespace; however, this statement
should be used carefully.
Second.py
first.py import first
import sys
def welcome(x): import os
#name=input("Enter Name:")
print("Welcome:",x) #first.welcome(name)
r="sankul" print(first.r)
v=10.20 print(first.v)
print(first.__name__)
#print(first.__dict__)
print(type(first))
print(__name__)
print(sys.path)
print(os.getcwd())
EXCEPTIONS
•Errors in a Python Program (Compile-Time
Errors, Runtime Errors, Logical Errors),
•Exceptions,
•Exception Handling,
•Types of Exceptions,
•The Except Block,
•The assert Statement,
•User-Defined Exceptions,
•Logging the Exceptions
ERRORS IN A PYTHON PROGRAM
1. Compile time errors – usually the easiest to
spot, compile time errors occur when you make
a mistake.
Not ending an if statement with the colon is an
example of an compile time error, as is
misspelling a Python keyword (e.g.
using whille instead of while).
Syntax error usually appear at compile time
and are reported by the interpreter.
Runtime errors:
Runtime error refers to an error that takes place
while executing a program.
As opposed to the compilation errors that occur
during a program compilation, runtime errors
occur only during the execution of the program.
Runtime errors imply bugs in the program or
issues that the developers had expected but were
unable to correct.
For example, insufficient memory can often
trigger a runtime error.
Logical errors –
also called semantic errors, logical errors
cause the program to behave incorrectly, but
they do not usually crash the program.
Unlike a program with syntax errors, a program
with logic errors can be run, but it does not
operate as intended.
WHAT IS EXCEPTION?
An exception is an event, which occurs during the
execution of a program that disrupts the normal flow
of the program's instructions.
Python has many built-in exceptions which forces
your program to output an error when something in
it goes wrong.
In general, when a Python script encounters a
situation that it cannot cope with, it raises an
exception.
An exception is a Python object that represents an
error.
When a Python script raises an exception, it must
either handle the exception immediately otherwise it
terminates and quits.
HANDLING AN EXCEPTION
If you have some suspicious code that may raise an
exception, you can defend your program by placing
the suspicious code in a try: block. After the try:
block, include an except: statement, followed by a
block of code which handles the problem as smartly
as possible.
If an error is encountered, a try block code execution
is stopped and transferred down to the except block.
In addition to using an except block after the try
block, you can also use the finally block.
The code in the finally block will be executed
regardless of whether an exception occurs.
Raising an exception breaks current code execution
and returns the exception back until it is handled.
RAISING AN EXCEPTIONS
You can raise exceptions in several ways by using
the raise statement. The general syntax for the
raise statement is as follows.
Syntax
raise [Exception as args [, traceback]]]
Here, Exception is the type of exception (for
example, NameError) and argument is a value for
the exception argument. The argument is
optional; if not supplied, the exception argument
is None.
The final argument, traceback, is also optional
(and rarely used in practice), and if present, is
the traceback object used for the exception
WHAT IS A FILE?
File is a named location on disk to store related
information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile
which loses its data when computer is turned off, we
use files for future use of the data.
When we want to read from or write to a file we
need to open it first. When we are done, it needs
to be closed, so that resources that are tied with
the file are freed.
Hence, in Python, a file operation takes place in the
following order.
Open a file
Read or write (perform operation)
Close the file
TYPES OF FILES IN PYTHON
In Python, a file is categorized as either text or
binary, and the difference between the two file types
is important.
Text files are structured as a sequence of lines, where
each line includes a sequence of characters. This is
what you know as code or syntax.
Each line is terminated with a special character, called
the EOL or End of Line character. There are several
types, but the most common is the comma {,} or
newline character. It ends the current line and tells the
interpreter a new one has begun.
A binary file is any type of file that is not a text file.
Because of their nature, binary files can only be
processed by an application that know or understand
the file’s structure. In other words, they must be
applications that can read and interpret binary.
Opening and Closing Files
Python provides basic functions and methods
necessary to manipulate files by default. You can
do most of the file manipulation using a file
object.
The open Function
Before you can read or write a file, you have to
open it using Python's built-in open() function.
This function creates a file object, which would be
utilized to call other support methods associated
with it.
Syntax
file object = open(file_name [, access_mode]
[, buffering])
Here are parameter details:
file_name: The file_name argument is a string value
that contains the name of the file that you want to
access.
access_mode: The access_mode determines the mode
in which the file has to be opened, i.e., read, write,
append, etc. A complete list of possible values is given
below in the table. This is optional parameter and
the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering
takes place. If the buffering value is 1, line buffering is
performed while accessing a file. If you specify the
buffering value as an integer greater than 1, then
buffering action is performed with the indicated buffer
size. If negative, the buffer size is the system
default(default behavior).
Example.1
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
Output
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
The close() Method
he close() method of a file # Open a file
object flushes any unwritten fo = open("foo.txt", "w")
information and closes the
print ("Name of the file: ",
file object, after which no
fo.name)
more writing can be done.
Python automatically closes
a file when the reference
# Close opend file
object of a file is reassigned fo.close()
to another file. It is a good
practice to use the close()
method to close a file.
Syntax
fileObject.close();
Reading and Writing Files
The write() Method # Open a file
The write() method
fo = open("foo.txt",
writes any string to an
"wb")
open file. It is important
to note that Python fo.write( "Python is a
strings can have binary great language.\nYeah
data and not just text. its great!!\n");
The write() method
does not add a newline # Close opend file
character ('\n') to the
fo.close()
end of the string −
Syntax
fileObject.write(string);
The read() Method
The read() method reads a
string from an open file. It is
important to note that Python # Open a file
strings can have binary data. fo = open("foo.txt",
apart from text data.
"r+")
Syntax
fileObject.read([count]);
str = fo.read(10);
Here, passed parameter is the print ("Read String is : ",
number of bytes to be read str)
from the opened file. This # Close opend file
method starts reading from
the beginning of the file and if fo.close()
count is missing, then it tries
to read as much as possible,
maybe until the end of file.
KNOWING WHETHER A FILE EXISTS OR NOT
In Python, there are several ways to verify a file or
directory exists using functions built into the core
language and the Python standard library.
The most common way to check for the existence of
a file in Python is using the exists() and isfile()
methods from the os.path module in the standard
library.
calling os.path.exists() will return True for files and
directories.
If you want to ensure that a given path points to
a file and not to a directory, you can use
the os.path.isfile() function
THE WITH STATEMENT
It is hard to remember to close the file once we are
done with the file.
Python offers an easy solution for this.
We can use with statement in Python such that we
don’t have to close the file handler.
The with statement creates a context manager and
it will automatically close the file handler for you
when you are done with it.
We can also use with statement to open more than
one file.
File Positions
The tell() method tells you the current position within
the file; in other words, the next read or write will
occur at that many bytes from the beginning of the
file.
The seek(offset[,start_from]) method changes the
current file position.
The offset argument indicates the number of bytes
to be moved.
start_from is optional, it tells from which place we
want to start.
There are three possible values for start_from --
0 :beginning of file
1 :current position of file
2 :end of file
If the argument start_from is not specified, by default it
is 0.
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print ("Read String is : ", str)
# Check current position
position = fo.tell();
print ("Current file position : ", position)
# Reposition pointer at the beginning once
again
position = fo.seek(0, 0);
str = fo.read(10);
print ("Again read String is : ", str)
# Close opend file
fo.close()