0% found this document useful (0 votes)
3 views33 pages

Python Unit 1

The document provides an introduction to computational problem solving using Python, covering essential concepts such as algorithms, representations, and the limits of computational problem solving. It discusses the importance of understanding computer hardware, software, and the number systems used in programming. Additionally, it outlines the process of programming, including syntax, semantics, debugging, and the differences between procedural and object-oriented programming paradigms.

Uploaded by

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

Python Unit 1

The document provides an introduction to computational problem solving using Python, covering essential concepts such as algorithms, representations, and the limits of computational problem solving. It discusses the importance of understanding computer hardware, software, and the number systems used in programming. Additionally, it outlines the process of programming, including syntax, semantics, debugging, and the differences between procedural and object-oriented programming paradigms.

Uploaded by

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

SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.

CA

PROBLEM SOLVING USING PYTHON

UNIT – I
Introduction: The essence of computational problem solving – Limits of computational problem
solving-Computer algorithms-Computer Hardware-Computer Software-The process of
computational problem solving-Python programming language - Literals - Variables and
Identifiers - Operators - Expressions and Data types.

The essence of computational problem solving:

Programming is certainly a primary activity of computer science, programming


languages and computers are only tools. It is fundamentally computational problem solving —
that is, solving problems by the use of computation. One characterization of computation is given
by the notion of an algorithm. An algorithm to be a series of steps that can be systematically
followed for producing the answer to a certain type of problem

In order to solve a problem computationally, two things are needed:

1. Representation
2. Algorithm

A representation that captures all the relevant aspects of the problem, and an algorithm
that solves the problem by use of the representation.

Let’s consider a problem known as the Man, Cabbage, Goat, Wolf problem (Figure 1-3). A
man lives on the east side of a river. He wishes to bring a cabbage, a goat, and a wolf to a village
on the west side of the river to sell. However, his boat is only big enough to hold himself, and
either the cabbage, goat, or wolf. In addition, the man cannot leave the goat alone with the
cabbage because the goat will eat the cabbage, and he cannot leave the wolf alone with the goat
because the wolf will eat the goat. How does the man solve this problem?

There is a simple algorithmic approach for solving this problem by simply trying all possible
combinations of items that may be rowed back and forth across the river. Trying all possible
solutions to a given problem is referred to as a brute force approach.

Only the relevant aspects of the problem need to be represented, all the irrelevant details
can be omitted. A representation that leaves out details of what is being represented is a form of
abstraction .

The use of abstraction is prevalent in computer science. In this case, is the color of the
boat relevant? The width of the river? The name of the man?

Page 1 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
No, the only relevant information is where each item is at each step. The collective
location of each item, in this case, refers to the state of the problem. Thus, the start state of the
problem can be represented as follows.

Man cabbage goat wolf


[ E, E, E, E]

In this representation, the symbol E denotes that each corresponding object is on the east
side of
the river. If the man were to row the goat across with him, for example, then the representation
of the new problem state would be

man cabbage goat wolf


[ W, E, W, E]

In which the symbol W indicates that the corresponding object is on the west side of the
river—in this case, the man and goat. (The locations of the cabbage and wolf are left
unchanged.) A solution to this problem is a sequence of steps that converts the initial state,

[ E, E, E, E]

In which all objects are on the east side of the river, to the goal state ,

[ W, W, W, W]

In which all objects are on the west side of the river. Each step corresponds to the man rowing a
particular object across the river (or the man rowing alone). As you will see, the Python
programming language provides an easy means of representing sequences of values

Limits of Computational Problem Solving:

Once an algorithm for solving a given problem is developed or found, an important


question is, “Can a solution to the problem be found in a reasonable amount of time?” If not,
then the particular algorithm is of limited practical use..
The Traveling Salesman problem is a classic computational problem in computer
science. The problem is to find the shortest route of travel for a salesman needing to visit a given
set of cities. In a brute force approach, the lengths of all possible routes would be calculated and
compared to find the shortest one.

Any algorithm that correctly solves a given problem must solve the problem in a
reasonable amount of time, otherwise it is of limited practical use.

Computer Algorithms:

An algorithm is a fi nite number of clearly described, unambiguous “doable” steps that


can be systematically followed to produce a desired result for given input in a finite amount of
time.

Algorithms solve general problems, and not specific ones.

Page 2 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Algorithms, therefore, are general computational methods used for solving particular
problem instances.

The word “algorithm” is derived from the ninth-century Arab mathematician, Al-
Khwarizmi, who worked on “written processes to achieve some goal

Computer algorithms are central to computer science. They provide step-by-step methods
of computation that a machine can carry out. Having high-speed machines (computers) that can
consistently follow and execute a given set of instructions provides a reliable and effective
means of realizing computation. However, the computation that a given computer performs is
only as good as the underlying algorithm used. Understanding what can be effectively
programmed and executed by computers, therefore, relies on the understanding of computer
algorithms.

Computers can execute instructions very quickly and reliably without error , algorithms
and computers are a perfect match

Example: Day of the Week Algorithm

Page 3 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Computer Hardware:

Computer hardware comprises the physical part of a computer system. It includes the all-
important components of the central processing unit (CPU) and main memory. It also includes
peripheral components such as a keyboard, monitor, mouse, and printer.

It is essential that computer hardware be reliable and error free. If the hardware gives
incorrect results, then any program run on that hardware is unreliable. The key to developing
reliable systems is to keep the design as simple as possible. In digital computing, all information
is represented as a series of digits.

We are used to representing numbers using base 10 with digits 0–9. All information
within a computer system is represented by the use of only two digits, 0 and 1 , called binary
representation. Computer hardware, therefore, is based on the use of simple electronic “on/off”
switches called transistors that switch at very high speed. Integrated circuits (“chips”), the
building blocks of computer hardware, are comprised of millions or even billions of transistors.

Number System

The number system or the numeral system is the system of naming or representing
numbers.

There are various types of number system in mathematics. The four most common
number system types are:
1. Decimal number system (Base- 10)
2. Binary number system (Base- 2)
3. Octal number system (Base-8)
4. Hexadecimal number system (Base- 16)

Decimal Number System (Base 10 Number System)


Decimal number system has base 10 because it uses ten digits from 0 to 9. In the decimal number
system, the positions successive to the left of the decimal point represent units, tens, hundreds,
thousands and so on. This system is expressed in decimal numbers.
Every position shows a particular power of the base (10). For example, the decimal number 1457
consists of the digit 7 in the units position, 5 in the tens place, 4 in the hundreds position, and 1
in the thousands place whose value can be written as
(1×103) + (4×102) + (5×101) + (7×100)
(1×1000) + (4×100) + (5×10) + (7×1)
1000 + 400 + 50 + 7
1457

Binary Number System (Base 2 Number System)


The base 2 number system is also known as the Binary number system wherein, only two binary
digits exist, i.e., 0 and 1. Specifically, the usual base-2 is a radix of 2. The figures described

Page 4 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
under this system are known as binary numbers which are the combination of 0 and 1. For
example, 110101 is a binary number.
We can convert any system into binary and vice versa.
Example
Write (14)10 as a binary number.
Solution:

∴ (14)10 = 11102
Base 2 Number System Example

Octal Number System (Base 8 Number System)


In the octal number system, the base is 8 and it uses numbers from 0 to 7 to represent numbers.
Octal numbers are commonly used in computer applications. Converting an octal number to
decimal is the same as decimal conversion and is explained below using an example.
Example: Convert 2158 into decimal.
Solution:
2158 = 2 × 82 + 1 × 81 + 5 × 80
= 2 × 64 + 1 × 8 + 5 × 1
= 128 + 8 + 5
= 14110

Hexadecimal Number System (Base 16 Number System)


In the hexadecimal system, numbers are written or represented with base 16. In the hex system,
the numbers are first represented just like in decimal system, i.e. from 0 to 9. Then, the numbers
are represented using the alphabets from A to F. The below-given table shows the representation
of numbers in the hexadecimal number system.

Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F

Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Number System Chart


In the number system chart, the base values and the digits of different number system can be
found. Below is the chart of the numeral system.

Page 5 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Fundamental Hardware Components

The central processing unit (CPU) is the “brain” of a computer system, containing
digital logic circuitry able to interpret and execute instructions.

Main memory is where currently executing programs reside, which the CPU can
directly and very quickly access.

Main memory is volatile; that is, the contents are lost when the power is turned off. In
contrast, secondary memory is nonvolatile, and therefore provides long-term storage of
programs and data.

This kind of storage, for example, can be magnetic (hard drive), optical (CD or DVD), or
nonvolatile flash memory (such as in a USB drive).

Input/output devices include anything that allows for input (such as the mouse and
keyboard) or output (such as a monitor or printer).

Finally, buses transfer data between components within a computer system, such as
between the CPU and main memory.

Operating Systems—Bridging Software and Hardware

An operating system is software that has the job of managing and interacting with the
hardware resources of a computer. Because an operating system is intrinsic to the operation a
computer, it is referred to as system software.

An operating system is software that has the job of managing the hardware resources of
a given computer and providing a Particular user interface.

Page 6 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Dig: Fundamental Hardware Components and Operating System

Computer Software:

The first computer programs ever written were for a mechanical computer designed by
Charles Babbage in the mid-1800s. The person who wrote these programs was a woman, Ada
Lovelace, who was a talented mathematician. Thus, she is referred to as “the first computer
programmer.”

Computer software is a set of program instructions, including related data and


documentation, that can be executed by computer. This can be in the form of instructions on
paper, or in digital form.
While system software is intrinsic to a computer system, application software fulfills
users’ needs, such as a photo-editing program.

Page 7 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Syntax, Semantics, and Program Translation

Programming languages (called “artifi cial languages”) are languages just as “natural
languages” such as English and Mandarin (Chinese). Syntax and semantics are important
concepts that apply to all languages.

The syntax of a language is a set of characters and the acceptable arrangements


(sequences) of those characters.

The semantics of a language is the meaning associated with each syntactically correct
sequence of characters

Program Translation, A central processing unit (CPU) is designed to interpret and


execute a specifi c set of instructions represented in binary form (i.e., 1s and 0s) called machine
code . Only programs in machine code can be executed by a CPU

Most programs are written in a “high-level” programming language such as Python.


Since the instructions of such programs are not in machine code that a CPU can execute, a
translator program must be used. There are two fundamental types of translators. One, called a
compiler , translates programs directly into machine code to be executed by the CPU

The other type of translator is called an interpreter , which executes program instructions in
place of (“running on top of”) the CPU,

Thus, an interpreter can immediately execute instructions as they are entered. This is referred to
as interactive mode . This is a very useful feature for program development. Python, as we shall
see, is executed by an interpreter.

Page 8 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Program Debugging: Syntax Errors vs. Semantic Errors

Program debugging is the process of fi nding and correcting errors ( “bugs” ) in a


computer program. Programming errors are inevitable during program development. Syntax
errors are caused by invalid syntax (for example, entering prnt instead of print). Since a
translator cannot understand instructions containing syntax errors, translators terminate when
encountering such errors indicating where in the program the problem occurred.

In contrast, semantic errors (generally called logic errors ) are errors in program logic.
Such errors cannot be automatically detected, since translators cannot understand the intent of a
given computation. For example, if a program computed the average of three numbers as
follows,
(num1 1 num2 1 num3) / 2.0

a translator would have no means of determining that the divisor should be 3 and not 2.
Computers do not understand what a program is meant to do, they only follow the instructions
given . It is up to the programmer to detect such errors. Program debugging is not a trivial task,
and constitutes much of the time of program development.

Procedural vs. Object-Oriented Programming

Programming languages fall into a number of programming paradigms. The two major
programming paradigms in use today are procedural (imperative) programming and object-
oriented programming. Each provides a different way of thinking about computation. While
most programming languages only support one paradigm, Python supports both procedural and
object-oriented programming. We will start with the procedural aspects of Python.

COMPUTATIONAL PROBLEM SOLVING:

The Process of Computational Problem Solving


Computational problem solving does not simply involve the act of computer programming. It is a
process , with programming being only one of the steps. Before a program is written, a design
for the program must be developed. And before a design can be developed, the problem to be
solved must be well understood. Once written, the program must be thoroughly tested.

Problem Analysis

Understanding the Problem

Once a problem is clearly understood, the fundamental computational issues for solving it
can be determined.

Thus, a program may be stated as finding,


A solution
An approximate solution
A best solution
All solutions
Page 9 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Describing the Needed Algorithms

When solving a computational problem, either suitable existing algorithms may be found
or new algorithms must be developed. Algorithms that work well in general but are not
guaranteed to give the correct result for each specific problem are called heuristic algorithms .

Program Implementation

Design decisions provide general details of the data representation and the algorithmic
approaches for solving a problem. The details, however, do not specify which programming
language to use, or how to implement the program.

Program Testing

Writing computer programs is difficult and challenging. As a result, programming errors


are pervasive, persistent and inevitable.

However, the sense of accomplishment of developing software that can be of benefit to


hundreds, thousands, or even millions of people can be extremely gratifying

Page 10 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

The Python Programming Language:

Guido van Rossum is the creator of the Python programming language, first released in
the early 1990s. Its name comes from a 1970s British comedy sketch television show called
Monty Python’s Flying Circus.

The development environment IDLE provided with Python comes from the name of a
member of the comic group.

IDLE is an integrated development environment (IDE). An IDE is a bundled set of


software tools for program development. This typically includes an editor for creating and
modifying programs, a translator for executing programs, and a program debugger.

A debugger provides a means of taking control of the execution of a program to aid in


finding program errors.

Python is most commonly translated by use of an interpreter. Thus, Python provides the
Very useful ability to execute in interactive mode. The window that provides this interaction is
Referred to as the Python shell.

Interacting with the shell is much like using a calculator, except that, instead of being
limited to the operations built into a calculator (addition, subtraction, etc.), it allows the entry and
creation of any Python code
Example use of the Python shell is demonstrated

Page 11 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Here, the expression 2 1 3 is entered at the shell prompt ( >>> ), which immediately
responds with the result 5.

Although working in the Python shell is convenient, the entered code is not saved. Thus,
for program development, a means of entering, editing, and saving Python programs is provided
by the program editor in IDLE.

The Python Standard Library is a collection of built-in modules , each providing


specific functionality beyond what is included in the “core” part of Python. In order to utilize the
capabilities of a given module in a specific program, an import statement is used.

A Bit of Python:

A bit of Python just enough to begin writing some simple programs. Since all computer
programs input data, process the data, and output results, we look at the notion of a variable, how
to perform some simple arithmetic calculations, and how to do simple input and output

Variables

A variable is “a name that is assigned to a value.” One of the most fundamental concepts
in programming is that of a variable.

A simple description of a variable is “a name that is assigned to a value,” as shown


below,

N= 5 variable N is assigned the value 5

Thus, whenever variable n appears in a calculation, it is the current value that n is


assigned to that is used, as in the following,

n + 20 (5 + 20)

Page 12 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Basic Arithmetic Operators

The common arithmetic operators in Python are 1 (addition), 2 (subtraction), *


(multiplication), / (division), and ** (exponentiation).

Addition, subtraction, and division use the same symbols as standard mathematical
notation,

10 + 20 25 - 15 20 / 10

There is also the symbol // for truncated division. For multiplication and exponentiation,
the asterisk (*) is used.

5 * 10 (5 times 10) 2 ** 4 (2 to the 4th power)

Multiplication is never denoted by the use of parentheses as in mathematics, as depicted


below,

10 * (20 + 5) CORRECT 10(20 + 5) INCORRECT

Note that parentheses may be used to denote sub expressions. Finally, we see how to
input information from the user, and display program results.

Basic Input and Output

In Python, input is used to request and get information from the user, and print is used to
display information on the screen.

In Python, the input function is used for this purpose,

name = input('What is your name?: ')

Characters within quotes are called strings . This particular use of a string, for requesting
input from the user, is called a prompt . The input function displays the string on the screen to
prompt the user for input,

What is your name?: SUGUMAR

The underline is used here to indicate the user’s input. The print function is used to display
information on the screen in Python. This may be used to display a message,

>>> print('Welcome to My First Program!')


Welcome to My First Program!

Or
Used to output the value of a variable,

>>> n = 10
>>> print(n)
Page 13 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
10

Or
To display a combination of both strings and variables,

>>> name = input('What is your name?: ')


What is your name?: SUGUMAR

>>> print('Hello', name)


Hello SUGUMAR

How to Use IDLE:

Python programs using IDLE, we will create a simple program that asks the user for their
Name and responds with a greeting.

This program utilizes the following concepts:

♦ creating and executing Python programs


♦ input and print

A new, untitled program window will appear:

Type the following in the program window exactly as shown

Page 14 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

When finished, save the program file by selecting Save As under the File menu, and save in the
appropriate folder with the name MyFirstProgram.py.

To run the program, select Run Module from the Run menu (or simply hit function key F5).

If you have entered the program code correctly, the program should execute as shown in
Figure

Page 15 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

If, however, you have mistyped part of the program resulting in a syntax error

Literals:

A literal is a sequence of one of more characters that stands for itself.

Numeric Literals

A numeric literal is a literal containing only the digits 0–9, an optional sign character (1
or 2 ), and a possible decimal point. (The letter e is also used in exponential notation If a numeric
literal contains a decimal point, then it denotes a floating-point value , or “ float ” (e.g., 10.24);
otherwise, it denotes an integer value (e.g., 10). Commas are never used in numeric literals.

Figure 2-2 gives additional examples of numeric literals in Python.

Page 16 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Floating-point values, however, have both a limited range and a limited precision .
Python uses a double-precision standard format (IEEE 754) providing a range of 10 to 10 - 308 308

with 16 to 17 digits of precision. To denote such a range of values, floating-points can be


represented in scientific notation,

9.0045602e + 5 (9.0045602 * 10 5 , 8 digits of precision)


1.006249505236801e8 (1.006249505236801 * 10 8 , 16 digits of precision)
-
4.239e216 (4.239 * 10 16 , 4 digits of precision)

It is important to understand the limitations of fl oating-point representation. For


example, the multiplication of two values may result in arithmetic overfl ow , a condition that
occurs when a calculated result is too large in magnitude (size) to be represented,

>>>1.5e200 * 2.0e210
>>> inf

This results in the special value inf(“infinity”) rather than the arithmetically correct result
3.0e410, indicating that arithmetic overflow has occurred. Similarly, the division of two numbers
may result in arithmetic underflow, a condition that occurs when a calculated result is too small
in magnitude to be represented,

Arithmetic overflow occurs when a calculated result is too large in magnitude to be represented.

Arithmetic underflow occurs when a calculated result is too small in magnitude to be


represented.

String Literals

A String literal is a sequence of characters surrounded by quotes. We can use single,


double or triple quotes for a string.

A character literal is a single character surrounded by single or double quotes.

String=”This is Python”
Char=”C”

A string consisting of only a pair of matching quotes (with nothing in between) is called
the empty string, which is different from a string containing only blank characters. Both blank
strings and the empty string have their uses. Strings may also contain quote characters as long as
different quotes are used to delimit the string.

Boolean Literals

A Boolean literal can have any of the two values: True or False.

X= (1==True) B=False + 10
Y= (1==False)
A= True + 4 print(“X is”, X)
Page 17 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
print(“Y is”, Y) Output:
print(“A is “, A)
print(“B is “, B) X is True
Y is False
A is 5
B is 10

We can use the True and False in numeric expression as the value.

Special literals.
Python contains one special literal i.e., None. None is used to specify to that field that is
not created. It is also used for the end of lists in Python.

Example - Special Literals

1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
10
None

Literal Collections.

Python provides the four types of literal collection such as List literals, Tuple literals,
Dict literals, and Set literals.

List:
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square
brackets([]). We can store different types of data in a List.

Example - List literals


1. list=['John',678,20.4,'Peter']
2. list1=[456,'Andrew']
3. print(list)
4. print(list + list1)

Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']

Dictionary:
Page 18 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

o Python dictionary stores the data in the key-value pair.


o It is enclosed by curly-braces {} and each pair is separated by the commas(,).

Example
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
2. print(dict)

Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}

Tuple:

o Python tuple is a collection of different data-type. It is immutable which means it cannot


be modified after creation.
o It is enclosed by the parentheses () and each element is separated by the comma(,).

Example
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)

Output:
(10, 20, 'Dev', [2, 3, 4])

Set:
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the comma(,).

Example: - Set Literals


1. set = {'apple','grapes','guava','papaya'}
2. print(set)

Output:
{'guava', 'apple', 'papaya', 'grapes'}

Page 19 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Python Variables and Identifiers:


Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
o The first character of the variable must be an alphabet or underscore ( _ ).
o All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Object References
It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.
Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.
1. print("John")
Output:
John
The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-
in type() function.
1. type("John")
Output:
<class 'str'>
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables
are used to denote objects by that name.
Page 20 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Let's understand the following example
1. a = 50

In the above image, the variable a refers to an integer object.


Object Identity
In Python, every created object identifies uniquely in Python. Python provides the guaranteed
that no two objects will have the same identifier. The built-in id() function, is used to identify the
object identifier. Consider the following example.
1. a = 50 7. print(id(a))
2. b=a Output:
3. print(id(a)) 140734982691168
4. print(id(b)) 140734982691168
5. # Reassigned variable a 2822056960944
6. a = 500

We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to the new
object identifier.
Variable Names
Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the digit (0-9),
and underscore character(_). Consider the following example of valid variables names.
1. name = "Devansh" 7. print(marks)
2. age = 20 Output:
3. marks = 80.50 Devansh
4. 20
5. print(name) 80.5
6. print(age)

Consider the following valid variables name.


1. name = "A" 8. _name_ = "H"
2. Name = "B" 9. na56me = "I"
3. naMe = "C" 10.
4. NAME = "D" 11. print(name,Name,naMe,NAME,n_a_m_e, N
5. n_a_m_e = "E" AME, n_a_m_e, _name, name_,_name, na5
6. _name = "F" 6me)
7. name_ = "G"

Output:
ABCDEDEFGFI

In the above example, we have declared a few valid variable names such as name, _name_ , etc.
But it is not recommended because when we try to read code, it may create confusion.
The variable name should be descriptive to make code more readable.
Page 21 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
The multi-word keywords can be created by the following method.
o Camel Case - In the camel case, each word or abbreviation in the middle of begins with a
capital letter. There is no intervention of whitespace. For example – name Of Student,
value Of Variable, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For
example – Name Of Student, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is
also known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to
multiple variables or assigning multiple values to multiple variables.

Consider the following example.


1. Assigning single value to multiple variables
Eg: Output:
1. x=y=z=50 50
2. print(x) 50
3. print(y) 50
4. print(z)

2. Assigning multiple values to multiple variables:


Eg:
1. a,b,c=5,10,15 Output:
2. print a 5
3. print b 10
4. print c 15
The values will be assigned in the order in
which variables appear.

Page 22 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

Python Operators:
The operator can be defined as a symbol which is responsible for a particular operation between
two operands. Operators are the pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators, which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+ (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) 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 = 20, b = 10 => a+b
= 30

- (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 = 10 => a - b = 10

/ (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

* It is used to multiply one operand with the other. For example, if a =


(Multiplication) 20, b = 10 => a * b = 200

% (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) It is an exponent operator represented as it calculates the first operand


power to the second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.

Comparison operator

Page 23 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly. The comparison operators are described in the following table.

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.

<= If the first operand is less than or equal to the second operand, then the
condition becomes true.

>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.

> 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.

Assignment Operators
The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.

Operator Description

= It assigns the value of the right expression to the left operand.

+= It increases 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 = 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.

Page 24 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

**= 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.

Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 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) The resulting bit will be 1 if both the bits are different; otherwise,
the resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is
0, the resulting bit will be 1 and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present in
the right operand.

>> (right The left operand is moved right by the number of bits present in the
shift) right operand.

Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.

Operato Description
r

Page 25 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

and If both the expression are true, then the condition will be true. If a and b are the
two expressions, a → true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are
the two expressions, a → true, b → false => a or b → true.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators
Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the


second operand (list, tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in


the second operand (list, tuple, or dictionary).

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point to


the same object.

is not It is evaluated to be true if the reference present at both sides do not


point to the same object.

Operator Precedence
The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given
below.

Operator Description

** The exponent operator is given priority over all the others


used in the expression.

~+- The negation, unary plus, and minus.

* / % // The multiplication, divide, modules, reminder, and floor


division.

Page 26 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater
than, greater then equal to).

<> == != Equality operators.

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator Precedence of Arithmetic Operators in Python

Expression:

An expression is a combination of symbols that evaluates to a value. Expressions, most


commonly, consist of a combination of operators and operands,

4 + (3 * k)

An expression can also consist of a single literal or variable. Thus, 4, 3, and k are each
expressions. This expression has two subexpressions, 4 and (3 * k). Subexpression (3 * k) itself
has two sub expressions, 3 and k.

Page 27 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Expressions that evaluate to a numeric type are called arithmetic expressions . A
subexpression is any expression that is part of a larger expression. Sub expressions may be
denoted by the use of parentheses, as shown above.

Thus, for the expression 4 + (3 * 2), the two operands of the addition operator are 4 and
(3 * 2), and thus the result it equal to 10. If the expression were instead written as (4 + 3) * 2,
then it would evaluate to 14.

Since a subexpression is an expression, any subexpression may contain subexpressions of


its own,

4 + (3 * (2 - 1)) ➝ 4 + (3 * 1) ➝ 4 + 3 ➝ 7
If no parentheses are used, then an expression is evaluated according to the rules of operator
precedence in Python.

Python Data Types:


Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it.
The interpreter implicitly binds the value with its type.
1. a=5
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


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

1. Numbers
2. Sequence Type
3. Boolean
Page 28 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
4. Set
5. Dictionary

Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.


1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.

Page 29 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
The following example illustrates the string in Python.
Example - 1
1. str = "string using double quotes"
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
string using double quotes
A multiline
string
Consider the following example of string handling.

List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
Consider the following example.
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
Page 30 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,
SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Let's see a simple example of the tuple.

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Page 31 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
Traceback (most recent call last):
File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type, whereas
value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Consider the following example.
1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return

Page 32 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,


SRCAS , DEPT. OF COMPUTER SCIENCE PYTHON UNIT – I NOTES FOR I B.SC(CS) & I B.CA
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.
1. # Creating Empty set
2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Page 33 of 33 S.SUGUMAR MCA., M.Phil., B.Ed.,

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy