Python Unit 1
Python Unit 1
CA
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.
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?
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
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
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:
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
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)
∴ (14)10 = 11102
Base 2 Number System Example
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
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.
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.
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.”
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 semantics of a language is the meaning associated with each syntactically correct
sequence of characters
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.
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.
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.
Problem Analysis
Once a problem is clearly understood, the fundamental computational issues for solving it
can be determined.
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
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.
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
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.
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.
n + 20 (5 + 20)
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.
Note that parentheses may be used to denote sub expressions. Finally, we see how to
input information from the user, and display program results.
In Python, input is used to request and get information from the user, and print is used to
display information on the screen.
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,
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,
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,
Python programs using IDLE, we will create a simple program that asks the user for their
Name and responds with a greeting.
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
If, however, you have mistyped part of the program resulting in a syntax error
Literals:
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.
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
>>>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.
String Literals
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.
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.
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
Example
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
2. print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
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(,).
Output:
{'guava', 'apple', 'papaya', 'grapes'}
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)
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.
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
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.
Comparison operator
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 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.
**= 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.
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
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
Identity Operators
The identity operators are used to decide whether an element certain class or type.
Operator Description
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
<= < > >= Comparison operators (less than, less than equal to, greater
than, greater then equal to).
Expression:
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.
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.
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.
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
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.
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