0% found this document useful (0 votes)
58 views

Introduction of Python

This presentation helps the beginner's to learn the basics of Python Programing language. Dr.Gargishankar Verma Krishna's Vikash Institute of Technology , Raipur

Uploaded by

gargishankar
Copyright
© © All Rights Reserved
0% found this document useful (0 votes)
58 views

Introduction of Python

This presentation helps the beginner's to learn the basics of Python Programing language. Dr.Gargishankar Verma Krishna's Vikash Institute of Technology , Raipur

Uploaded by

gargishankar
Copyright
© © All Rights Reserved
You are on page 1/ 125

Python Overview

Python is a high-level, interpreted, interactive and


object oriented-scripting language.
Python was designed to be highly readable which uses
English keywords frequently where as other languages
use punctuation and it has fewer syntactical
constructions than other languages.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Installation of Python
1.Step 1: Check Your System. ...
2.Step 2: Download Python. ...
3.Step 3: Choose the Right Version. ...
4.Step 4: Download the Installer. ...
5.Step 5: Run the Installer. ...
6.Step 6: Verify the Installation. ...
7.Step 7: Install a Code Editor
(Optional) ...
Install PIP on Windows
PIP is a package management system used to
install and manage software packages/libraries
written in Python. PIP stands for Preferred
Installer Program or Pip Installs Packages.
Step 1: Download the get-pip.py (
https://bootstrap.pypa.io/get-pip.py)
file and store it in the same directory as
python is installed.
Step 2: Change the current path of the directory in
the command line to the path of the directory where
the above file exists.
Step 3: get-pip.py is a bootstrapping script that
enables users to install pip in Python environments.
Here, we are installing pip python3. Run the command
given below:
python get-pip.py

Step 4: Now wait through the installation


process. Voila! pip is now installed on your
system.
Verification of the Installation Process
One can easily verify if the pip has been installed
correctly by performing
a version check on the same.
Just go to the command line and execute the following
command:
pip -V
or
pip --version
Characteristics of Python
Python is Interpreted: This means that it is processed at
runtime by the interpreter and you do not need to compile your
program before executing it. This is similar to PERL and PHP.
Python is Interactive: This means that you can actually sit at a
Python prompt and interact with the interpreter directly to
write your programs.
Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
Python is Beginner's Language: Python is a great language for
the beginner programmers and supports the development of a
wide range of applications, from simple text processing to
WWW browsers to games.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Compiling and interpreting
Many languages require you to compile (translate) your program into a form
that the machine understands.

compile execute
source code byte code output
Hello.java Hello.class

Python is instead directly interpreted into machine instructions.

interpret
source code output
Hello.py

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


History of Python:
Python was developed by Guido van Rossum in the late eighties and
early nineties at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other
scripting languages.
Python is copyrighted, Like Perl, Python source code is now available
under the GNU General Public License (GPL).
Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing it's progress.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Features
Easy-to-learn: Python has relatively few keywords, simple structure,
and a clearly defined syntax.
Easy-to-read: Python code is much more clearly defined and visible to
the eyes.
Easy-to-maintain: Python's success is that its source code is fairly
easy-to-maintain.
A broad standard library: One of Python's greatest strengths is the
bulk of the library is very portable and cross-platform compatible on
UNIX, Windows, and Macintosh.
Interactive Mode: Support for an interactive mode in which you can
enter results from a terminal right to the language, allowing
interactive testing and debugging of snippets of code.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Features
(cont’d)
Portable: Python can run on a wide variety of hardware
platforms and has the same interface on all platforms.
Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial
databases.
GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable: Python provides a better structure and support for large
programs than shell scripting.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Environment
Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.)

Win 9x/NT/2000

Macintosh (PPC, 68K)

OS/2

DOS (multiple versions)

PalmOS

Nokia mobile phones

Windows CE

Acorn/RISC OS

BeOS

Amiga

VMS/OpenVMS

QNX

VxWorks

Psion

Python has also been ported to the Java and .NET virtual machines.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


2. Python - Basic
Syntax

Interactive Mode Programming:


>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Script Mode Programming :
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is finished.
When the script is finished, the interpreter is no longer active.

For example, put the following in one test.py, and run,


print "Hello, Python!";
print "I love COMP3050!";

The output will be:


Hello, Python!
I love COMP3050!

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Identifiers:
A Python identifier is a name used to identify a variable,
function, class, module, or other object. An identifier starts with
a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores, and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and
% within identifiers.
Python is a case sensitive programming language. Thus
Manpower and manpower are two different identifiers in
Python.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Rules for Naming Python
Identifiers
•It cannot be a reserved python
keyword.
•It should not contain white space.
•It can be a combination of A-Z, a-z, 0-
9, or underscore.
•It should start with an alphabet
character or an underscore ( _ ).
•It should not contain any special
character other than an underscore ( _
).
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Examples of Python
Identifiers
Valid identifiers:
•var1
•_var1
•_1_var
•var_1
Invalid Identifiers
•!var1
•1var
•1_var
•var#1
•var 1

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Keywords in Python

Python Keywords are some predefined and


reserved words in Python that have special
meanings. Keywords are used to define the syntax
of the coding. The keyword cannot be used as an
identifier, function, or variable name. All the
keywords in Python are written in lowercase except
True and False. There are 35 keywords in Python
3.11

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Reserved Words:
Keywords contain lowercase letters only.
and finally not
assert for or
break from pass
class global print
continue if raise
def import return
del in try
elif is while
else lambda with
except True Yield
as nonlocal False
None Await
async

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Indentation

 Indentation refers to the spaces at the beginning


of a code line.
 Where in other programming languages the
indentation in code is for readability only, the
indentation in Python is very important.
 Python uses indentation to indicate a block of
code.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Comments: Importance, Types
and Correct Way to Use
Comments in Python are the lines in the code that
are ignored by the interpreter during the execution
of the program.

Types of Comments in Python

There are three types of comments in


Python:

•Single line Comments


•Multiline Comments
•String Literals
•Docstring Comments
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
1. Single-Line Comments
•Python single-line comment starts with the hashtag
symbol (#) with no white spaces and lasts till the end
of the line.
•If the comment exceeds one line then put a hashtag
on the next line and continue the Python Comment.
•Python’s single-line comments are proved useful for
supplying short explanations for variables, function
declarations, and expressions. See the following code
snippet demonstrating single line comment:

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


2. Multi-Line Comments
Python does not provide the option for
multiline comments. However, there are different ways
through which we can write multiline comments.
a) Multiline comments using multiple hashtags
(#)
We can multiple hashtags (#) to write multiline
comments in Python. Each and every line will be
considered as a single-line comment.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


b) Comment Out Multiple Lines in Python using a
Multiline String as a Comment
Python multiline comments can also be enclosed in a
delimiter (“””). Again there should be no white space
between delimiters (“””). They are useful when the
comment text does not fit into one line, therefore needs
to span across lines. This type of string literal gets
ignored as it is not assigned to any variable.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


C) In this example, the comments starting
with # are extended to multiple lines using the
backslash (\) at the end of each line. The
backslash indicates that the comment
continues on the next line. This method can be
helpful for improving code readability when
you have lengthy comments

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Variables
Python Variable is containers that store values. Python
is not “statically typed”. We do not need to declare
variables before using them or declare their type. A
variable is created the moment we first assign a value
to it. A Python variable is a name given to a memory
location. It is the basic unit of storage in a program.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Variables do not need to be declared with any
particular type, and can even change type after they
have been set.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Variables Assignment in Python
we will define a variable in python. Here, clearly we
have assigned a number, a floating point number, and
a string to a variable such as age, salary, and name.
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string name = "John"
print(age)
print(salary)
print(name)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Assign Values to Multiple
Variables
Python allows assigning a single value to several
variables simultaneously with “=” operators.
For example:

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Global and Local Python Variables

Local variables in Python are the ones that are


defined and declared inside a function. We can not call
this variable outside the function.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Global variables in Python are the ones that are
defined and declared outside a function, and we need
to use them inside a function.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Data Type

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Python Data types are the classification or categorization of
data items. It represents the kind of value that tells what
operations can be performed on a particular data. Since
everything is an object in Python programming,
Python data types are classes and variables are instances
(objects) of these classes.
The following are the standard or built-in data types in
Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Numbers
Numeric values are stored in numbers. The whole
number, float, and complex qualities have a place
with a Python Numbers datatype. Python offers the
type() function to determine a variable's data type.
The instance () capability is utilized to check whether
an item has a place with a specific class.
When a number is assigned to a variable, Python
generates Number objects. For instance,

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


•Int: Whole number worth can be any length, like
numbers 10, 2, 29, - 20, - 150, and so on. An integer
can be any length you want in Python. Its worth has
a place with int.
•Float: Float stores drifting point numbers like 1.9,
9.902, 15.2, etc. It can be accurate to within 15
decimal places.
•Complex: An intricate number contains an
arranged pair, i.e., x + iy, where x and y signify the
genuine and non-existent parts separately. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Sequence Type
String
The sequence of characters in the quotation marks can
be used to describe the string. A string can be defined
in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since
Python gives worked-in capabilities and administrators
to perform tasks in the string.
When dealing with strings, the operation "hello"+"
python" returns "hello python," and the operator + is
used to combine two strings.
Because the operation "Python" *2 returns "Python,"
the operator * is referred to as a repetition operator.
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
List
Lists in Python are like arrays in C, but lists can
contain data of different types. The things put away in
the rundown are isolated with a comma (,) and
encased inside square sections [].
To gain access to the list's data, we can use slice [:]
operators. Like how they worked with strings, the list
is handled by the concatenation operator (+) and the
repetition operator (*)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a
collection of items from various data types. A parenthetical space ()
separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is
a read-only data structure.

Let's look at a straightforward tuple in action.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Dictionary
A dictionary is a key-value pair set arranged in any
order. It stores a specific value for each key, like an
associative array or a hash table. Value is any Python
object, while the key can hold any primitive data type.
The comma (,) and the curly braces are used to
separate the items in the dictionary.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Boolean
True and False are the two default values for the Boolean
type. These qualities are utilized to decide the given
assertion valid or misleading. The class book indicates
this. False can be represented by the 0 or the letter "F,"
while true can be represented by any value that is not
zero.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Set
The data type's unordered collection is Python Set. It is
iterable, mutable(can change after creation), and has
remarkable components. The elements of a set have no
set order; It might return the element's altered
sequence. Either a sequence of elements is passed
through the curly braces and separated by a comma to
create the set or the built-in function set() is used to
create the set. It can contain different kinds of values.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Operators
The operator is a symbol that performs a specific
operation between two operands, according to one
definition. Operators serve as the foundation upon
which logic is constructed in a program in a particular
programming language. In every programming
language, some operators perform several tasks. Same
as other languages, Python also has some operators,
and these areoperators
•Arithmetic given below -
•Comparison operators
•Assignment Operators
•Logical Operators
•Bitwise Operators
•Membership Operators
•Identity Operators

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


Arithmetic Operators
Arithmetic operators used between two operands for a particular
operation. There are many arithmetic operators. It includes the exponent
(**) operator as well as the + (addition), - (subtraction), *
(multiplication), / (divide), % (reminder), and // (floor division) operators.
Consider the following table for a detailed explanation of arithmetic
operators.
Operator Description

+ (Addition) It is used to add two operands. For example, if a =


10, b = 10 => a+b = 20

- (Subtraction) It is used to subtract the second operand from the


first operand. If the first operand is less than the
second operand, the value results negative. For
example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first


operand by the second operand. For example, if a =
20, b = 10 => a/b = 2.0

* (Multiplication) It is used to multiply one operand with the other.


For example, if a = 20, b = 4 => a * b = 80

% (reminder) It returns the reminder after dividing the first


operand by the second operand. For example, if a =
20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the


second operand, it is an exponent operator.

// (Floor division) It provides the quotient's floor value, which is


obtained by dividing the two operands.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Comparison operator
Comparison operators mainly use for comparison
purposes. Comparison operators compare the values of
the two operands and return a true or false Boolean
value in accordance. The example of comparison
operators are ==, !=, <=, >=, >, <. In the below
table, we explain the works of the operators.
Operator Description

== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second
operand.
>= The condition is met if the first operand is greater than or equal to the second
operand.
> If the first operand is greater than the second operand, then the condition
becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Assignment Operators
Using the assignment operators, the right expression's
value is assigned to the left operand. There are some
examples of assignment operators like =, +=, -=, *=,
%=, **=, //=. In the below table, we explain the works
of the operators.
Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left operand, the left operand
receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a =
a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be
equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the reminder
back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Bitwise Operators
The two operands' values are processed bit by bit by
the bitwise operators. The examples of Bitwise
operators are bitwise OR (|), bitwise AND (&), bitwise
XOR (^), negation (~), Left shift (<<), and Right shift
(>>). Consider
Operatorthe case below. Description
& (binary and) A 1 is copied to the result if both bits in
two operands at the same location are
1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the
bits are zero; otherwise, the resulting
bit will be 1.
^ (binary xor) If the two bits are different, the
outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as
their negations, so if one bit is 0, the
next bit will be 1, and vice versa.
<< (left shift) The number of bits in the right operand
is multiplied by the leftward shift of the
value of the left operand.
>> (right shift) The left operand is moved right by the
number of bits present in the right
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
operand.
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Logical Operators
The assessment of expressions to make decisions
typically uses logical operators. The examples of logical
operators are and, or, and not. In the case of logical
AND, if the first one is 0, it does not depend upon the
second one. In the case of logical OR, if the first one is
1, it does not depend on the second one. Python
supports the following logical operators. In the below
table, we explain the works of the logical operators.
Operator Description
and The condition will also be true if the expression is true. If the
two expressions a and b are the same, then a and b must
both be true.
or The condition will be true if one of the phrases is true. If a
and b are the two expressions, then an or b must be true if
and is true and b is false.
not If an expression a is true, then not (a) will be false and vice
versa.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Membership Operators
The membership of a value inside a Python data
structure can be verified using Python membership
operators.
The result is true if the value is in the data
structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the
second operand, it is evaluated to be true
(list, tuple, or dictionary).
not in If the first operand is not present in the
second operand, the evaluation is true (list,
tuple, or dictionary).

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR


COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Taking input in Python
Python input() function is used to take user
input.
By default, it returns the user input in form of a
string.
Syntax: input(prompt)
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")

Enter your name: GeeksforGeeks


Hello, GeeksforGeeks ! Welcome!

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Intger Numbers in Python
The code prompts the user to input an integer
representing the number of roses, converts the input
to an integer using typecasting, and then prints the
integer value.
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)

How many roses?: 8


8

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
How to Print Float/Decimal Number in
Python
# Taking input as float
# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)

Price of each rose?: 50.30


50.3

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Conditional Input from user in Python
In this example, the program prompts the user to enter
their age. The input is converted to an integer using the
int() function. Then, the program uses conditional
statements to check the age range and prints a message
based on whether the user is a minor, an adult, or a
senior citizen.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
# Prompting the user for input
age_input = input("Enter your age: ")

# Converting the input to an integer


age = int(age_input)

# Checking conditions based on user input


if age < 0:
print("Please enter a valid age.")
elif age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Take Multiple Input in Python
The code takes input from the user in a single line,
splitting the values entered by the user into separate
variables for each value using the split() method.
Then, it prints the values with corresponding labels,
either two or three, based on the number of inputs
provided by# taking
the user.
two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)

# taking three inputs at a time


x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Formatting the Output
Output formatting in Python with various techniques
including the format() method, manipulation of the
sep and end parameters, f-strings, and the versatile
% operator. These methods enable precise control
over how data is displayed, enhancing the readability
and effectiveness of your Python programs.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Example 1: Using Format()
amount = 150.75
print("Amount: ${:.2f}".format(amount))

Amount: $150.75

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Example 2:
Using sep
# end Parameter withand
'@' end parameter
print("Python", end='@') Python@GeeksforGee
print("GeeksforGeeks") ks
# Seprating with Comma
GFG
print('G', 'F', 'G', sep='') 09-12-2016
pratik@geeksforgee
# for formatting a date
ks
print('09', '12', '2016', sep='-')

# another example
print('pratik', 'geeksforgeeks', sep='@')

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Example 3: Using f-string

name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Hello, My name is Tushar and I'm 23 years old.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Example 4: Using % Operator
We can use ‘%’ operator. % values are replaced with
zero or more value of elements. The formatting using
% is similar to that of ‘printf’ in the C programming
language.
•%d –integer
•%f – float
•%s – string
•%x –hexadecimal
•%o – octal

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
# Taking input from the user
num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)

Enter a value: 50 The sum is 55

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
# Simple Python program to understand the arithmetical o
perator addition
# Here, we are storing the first input numbers in num1
num1 = input('Enter first number: ')
# Here, we are storing the second input numbers in num2

num2 = input('Enter second number: ')


# Here, we are declaring a variable sum to store the result

# Here, we are using the arithmetical operator to add the


two numbers
sum = float(num1) + float(num2)
# Here, we are printing the sum of the given two numbers

print('The sum of {0} and {1} is {2}'.format(num1, num


2, sum))
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Enter first number: 10
Enter second number: 20
The sum of 10 and 20 is
30.0

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Add Two Numbers in Python
There are many methods to add two number in
Python:
•Using “+” operator
•Defining a function that adds two number
•Using operator.add method
•Using lambda function
•Using Recursive function

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Add Two Numbers with “+” Operator
Here num1 and num2 are variables and we are going
to add both variables with the +
# Python3 program to add two numbers
num1 = 15
num2 = 12

# Adding two nos


sum = num1 + num2

# printing values
print("Sum of", num1, "and", num2 , "is", sum)

Sum of 15 and 12 is 27

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Add Two Numbers with User Input
In the below program to add two numbers in
Python, the user is first asked to enter two
numbers, and the input is scanned using the
Python input() function and stored in the variables
number1 and number2.
Then, the variable’s number1 and number2 are
added using the arithmetic operator +, and the
result is stored in the variable sum.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
# Python3 program to add two numbers

number1 = input("First number: ")


number2 = input("\nSecond number: ")

# Adding two numbers


# User might also enter float numbers
sum = float(number1) + float(number2)

# Display the sum


# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1, number2, sum))

First number: 13.5 Second number: 1.54


The sum of 13.5 and 1.54 is 15.04

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Add Two Numbers in Python Using Function
This program show adding two numbers in Python
using function. We can define a function that
accepts two integers and returns their sum.

#To define a function that take two integers


# and return the sum of those two numbers
def add(a,b):
return a+b
#initializing the variables
num1 = 10
num2 = 5
#function calling and store the result into sum_of_twonumbers
sum_of_twonumbers = add(num1,num2)
#To print the result
print("Sum of {0} and {1} is {2};" .format(num1,num2, sum_of_twonumbers))

Sum of 10 and 5 is 15;

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Add Two Numbers Using operator.add() Method
Initialize two variables num1, and num2. Find sum
using the operator.add() by passing num1, and num2
as arguments and assign to su. Display num1,num2
and sum program to add two numbers
# Python3
num1 = 15
num2 = 12
# Adding two nos
import operator
su = operator.add(num1,num2)
# printing values
print("Sum of {0} and {1} is {2}" .format(num1,num2, sum))

Sum of 15 and 12 is 27

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
String upper()
# all alphabets should be lowercase
string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())
# example string
string = "this should be uppercase!"
print(string.upper())
# string with numbers

THIS SHOULD BE UPPERCASE!


TH!S SH0ULD B3 UPP3RCAS3!

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
# first string
firstString = "python is awesome!"

# second string
secondString = "PyThOn Is AwEsOmE!"

if(firstString.upper() == secondString.upper()):
print("The strings are same.")
else:
print("The strings are not same.")

The strings are same.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
String lower()

# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())
# string with numbers
# all alphabets should be lowercase
string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())

this should be lowercase!


th!s sh0uld b3 l0w3rcas3!

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
# first string
firstString = "PYTHON IS AWESOME!"

# second string
secondString = "PyThOn Is AwEsOmE!"

if(firstString.lower() == secondString.lower()):
print("The strings are same.")
else:
print("The strings are not same.")

The strings are same.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
String casefold()
he casefold() method converts all characters of the string int
owercase letters and returns a new string.
text = "pYtHon"

# convert all characters to lowercase


lowercased_string = text.casefold()

print(lowercased_string)

# Output: python

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
String swapcase()
sentence1 = "THIS SHOULD ALL BE LOWERCASE."

# converts uppercase to lowercase


print(sentence1.swapcase())

sentence2 = "this should all be uppercase."

# converts lowercase to uppercase


print(sentence2.swapcase())

sentence3 = "ThIs ShOuLd Be MiXeD cAsEd."

# converts lowercase to uppercase and vice versa


print(sentence3.swapcase())

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Implementing Switch in Python using elif ladder

day = input("Enter the day of the week: ").capitalize()

if day == "Saturday" or day == "Sunday":


print(f"{day} is a weekend.")
elif day in ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday"]:
print(f"{day} is a weekday.")
else:
print("That's not a valid day of the week.")

Saturday is a weekend

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
def num_in_words(no):
if(no==1):
print("One")
elif(no==2):
print("Two")
elif(no==3):
print("Three")
else:
print("Give input of numbers from 1 to 3")
num_in_words(3)
num_in_words(4.5)

Three
Give input of numbers from 1 to 3

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Implementing Python Switch using Dictionary
We can use a dictionary to implement the switch case.
We know that the dictionary holds the key-value pairs.
It can have the keys as the condition/ element to be
checked and the values as the elements to be printed
or the
deffunctions to be executed.
vowel(num):
switch={
1:'a',
2:'e',
3:'i',
4:'o',
5:'u'
}
return switch.get(num,"Invalid input")
vowel(3)
vowel(0)
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
‘i’
‘Invalid input’

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
implementing switch case using the dictionary
with functions as values:
def add():
return n+m
def subs():
return n-m
def prod():
return n*m
def div():
return m/n
def rem():
return m%n
def operations(op):
switch={
'+': add(),
'-': subs(),
'*': prod(),
'/': div(),
'%': rem(), }
return switch.get(op,'Choose one of the following operator:+,-,*,/,%')
operations('*')
operations('^')
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
36
‘Choose one of the following
operator:+,-,*,/,%’

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Implementing Python Switch using
Class

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
class Month(object):
def month_1(self):
print("January")
def month_2(self):
print("February")
def month_3(self):
print("March")
def month_4(self):
print("April")
def month_5(self):
print("May")
def month_6(self):
print("June")
def month_7(self):
print("July")
def month_8(self):
print("August")
def month_9(self):
print("September")
def month_10(self):
print("October")
def month_11(self):
print("November")
def month_12(self):
print("December")
def getMonth(self,no):
name_of_method="month_"+str(no)
method=getattr(self,name_of_method,lambda :'Give an input as an integer from 1 to 12')
return method()
)
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
mo=Month()
mo.getMonth(5)
mo.getMonth(0.5

May
‘Give an input as an integer from 1 to 12’

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Match and Case in Python
day = input("Enter the day of the week: ").capitalize()

match day:
case "Saturday" | "Sunday":
print(f"{day} is a weekend.")
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" |
"Friday":
print(f"{day} is a weekday.")
case _:
print("That's not a valid day of the week.")

Monday is a weekday.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Advanced Use Cases of Match and Case in
Python
animal = "Eagle"
match animal:
case "Eagle" | "Parrot":
print("Bird")
case "Lion" | "Tiger":
print("Mammal")
case "Python" | "Crocodile":
print("Reptile")
case _:
print("Unknown Class")

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Program to Find the Roots of
print("Equation: ax^2 + bx + c ")
a Quadratic Equation
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
d=b**2-4*a*c
d1=d**0.5
if(d<0):
print("The roots are imaginary. ")
else: r1=(-b+d1)/2*a r2=(-b-d1)/2*a
print("The first root:
",round(r1,2))
print("The second root:
",round(r2,2))

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Case 1: Equation: ax^2 + bx + c
Enter a: 1
Enter b: -5
Enter c: 6
The first root: 3.0
The second root: 2.0
Case 2: Equation: ax^2 + bx + c
Enter a: 1
Enter b: 5
Enterc: 10
The roots are imaginary.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python File Handling

Python supports the file-handling process. Till now, we


were taking the input from the console and writing it
back to the console to interact with the user. Users can
easily handle the files, like read and write the files in
Python. In another programming language, the file-
handling process is lengthy and complicated. But we
know Python is an easy programming language. So,
like other things, file handling is also effortless and
short in Python.

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Hence, a file operation can be done in the following order.
•Open a file
•Read or write - Performing operation
•Close the file

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Opening a file
A file operation starts with the file opening. At first, open
the File then Python will start the operation. File opening
is done with the open() function in Python.
This function will accepts two arguments, file name and
access mode in which the file is accessed.
When we use the open() function, that time we must be
specified the mode for which the File is opening.
The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:
The syntax for opening a file in Python is given below -
file object = open(<file-name>, <access
mode>, <buffering>)
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
SN Access Description
mode
1 r r means to read. So, it opens a file for read-only
operation. The file pointer exists at the beginning. The
file is by default open in this mode if no access mode is
passed.
2 rb It opens the file to read-only in binary format. The file
pointer exists at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer
exists at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format.
The file pointer exists at the beginning of the file.
5 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.
6 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. The file pointer exists at the
beginning of the file.
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
7 w+ It opens KRISHNA
the VIKASH
fileINSTITUTE
to write and read both. It is different
OF TECHNOLOGY, RAIPUR
8 wb+ It opens the file to write and read both in
binary format. The file pointer exists at the
beginning of the file.
9 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.
10 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.
11 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.
12 ab+ It opens a file to append and read both in
binary format. The file pointer remains at
the end of the file.
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Program to Read
the Contents of the File
a=str(input("Enter the name of the file with .txt
extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()
1.User must enter a file name.
2. The file is opened using the open() function in the read
mode.
3.The readline() outside the while loop is used to read
the first line of the file.
4. Inside the loop, the first line is first printed and then
the remaining lines are read and subsequently printed.
5. This continues this the end of file.
6. The file is then closed.
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
Python Program to Append the
Content of One File to the End of
Another File
name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
1. User must enter the name of the file to be read from
and the file to append into.
2. The file to be read is opened using open() function
in the read mode.
3. The contents of the file read using read() function is
stored in a variable and then the file is closed.
3. The file to append the data to is opened in the
append mode and the data stored in the variable is
written into the file.
4. The second file is then closed..

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
def rename_file(filename, new_filename):
try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + "
successfully.")
except IOError:
print("Error: could not rename file " + filename)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename

COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR


KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR
COPYRIGHT © DR.GARGISHANKAR VERMA , PROFESSOR
KRISHNA VIKASH INSTITUTE OF TECHNOLOGY, RAIPUR

You might also like