UNIT-1
The way of the program
Introduction to Thinking Like a Computer Scientist
The goal of learning computer programming is not just to write code but to think like a computer scientist.
This approach combines elements from:
Mathematics: Using formal, logical reasoning to represent ideas clearly.
Engineering: Designing systems by assembling components and evaluating trade-offs.
Natural Science: Observing systems, forming hypotheses, and testing them.
The most important skill for a computer scientist is problem-solving, which involves:
1. Formulating problems clearly.
2. Thinking creatively about solutions.
3. Expressing solutions clearly and accurately.
Learning programming is a practical way to improve problem-solving skills. Writing code allows you to test
ideas, correct mistakes, and systematically solve problems.
The Python programming language
The programming language you will be learning is Python. Python is an example of a high-level language;
other high-level languages you might have heard of are C++, PHP, Pascal, C#, and Java.
As you might infer from the name high-level language, there are also low-level languages, sometimes referred
to as machine languages or assembly languages. Loosely speaking, computers can only execute programs written
in low- level languages. Thus, programs written in a high-level language have to be translated into something
more suitable before they can run.
Why High-Level Languages Are Used
Ease of Programming: Programs are shorter and faster to write.
Readability: Code is easier to read and maintain.
Portability: Can run on different computers with minimal changes.
Fewer Errors: High-level languages reduce chances of mistakes.
Features of python
Python is an example of a high-level language
Second, high-level languages are portable, meaning that they can run on different kinds of computers with few
or no modifications.
The engine that translates and runs Python is called the Python Interpreter
There are two ways to use it: immediate mode and script mode. In immediate mode, you type Python
expressions into the Python Interpreter window, and the interpreter immediately shows the result
The >>> is called the Python prompt. . The interpreter uses the prompt to indicate that it is ready for
instructions. You can write a program in a file and use the interpreter to execute the contents of the file. Such a file
is called a script.
What is a program?
A program is a sequence of instructions that specifies how to perform a computation. The computation might be
something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also
be a symbolic computation, such as searching and replacing text in a document or (strangely enough) compiling a
program
The details look different in different languages, but a few basic instructions appear in just about every language:
input Get data from the keyboard, a file, or some other device such as a sensor.
name = input("Enter your name: ")
output Display data on the screen or send data to a file or other device such as a motor.
print("Hello,", name)
math Perform basic mathematical operations like addition and multiplication.
result = 5 * 3
conditional execution Check for certain conditions and execute the appropriate sequence of statements
if age >= 18:
print("You are eligible to vote")
repetition Perform some action repeatedly, usually with some variation.
for i in range(5):
print(i)
Development Environments
A text editor or IDE (Integrated Development Environment) is used to write code:
Text Editors: Notepad, Notepad++, Vim, Sublime Text.
Python IDEs: IDLE, Thonny, Spyder, Jupyter Notebook
What is debugging?
Programming is a complex process, and because it is done by human beings, it often leads to errors
. Programming errors are called bugs and the process of tracking them down and correcting them is
called debugging.
Three kinds of errors can occur in a program:
syntax errors,
runtime errors, and
semantic errors
Syntax errors
Python can only execute a program if the program is syntactically correct; otherwise, the
processfails and returns an error message. Syntax refers to the structure of a program and the rules
about that structure. For example, in English, a sentence must begin with a capital letter and end
with a period. this sentence contains a syntax error. So does this one
print("Hello World" # Missing closing parenthesis
Runtime errors
The second type of error is a runtime error, so called because the error does not appear until you
run the program. These errors are also called exceptions because they usually indicate that
something exceptional (and bad) has happened.
x = 5 / 0 # Division by zer
Semantic errors
The third type of error is the semantic error. If there is a semantic error in your program, it will
run successfully, in the sense that the computer will not generate any error messages, but it will not
do the right thing.
area = length + width # Should be length * width
Experimental debugging
Debugging is also like an experimental science. Once you have an idea what is going wrong, you modify your
program and try again. If your hypothesis was correct, then you can predict the result of the modification, and
you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new on
Differences between High level language and Low level language:
Feature High-Level Language (HLL) Low-Level Language (LLL)
Programming language closer to human Programming language closer to machine
Definition
language, easy to read and write. code, harder to read for humans.
Assembly Language, Machine Code
Examples Python, Java, C++, C#, PHP, Pascal
(binary)
Feature High-Level Language (HLL) Low-Level Language (LLL)
Simple and easy to understand; uses English- Complex; requires understanding of
Syntax
like statements. hardware and processor instructions.
Portable across different computers; same
Machine-dependent; written for a specific
Portability code can run on multiple platforms with
processor or hardware.
minimal changes.
Directly executed by the CPU (machine
Needs a compiler or interpreter to translate
Execution language) or requires assembler (for
into machine language.
Assembly).
Faster to develop and debug; less prone to Slower development; more prone to
Development Time
errors. errors due to complexity.
Readability Easier to read, understand, and maintain. Hard to read and maintain.
Memory Mostly handled automatically (garbage Programmer must manage memory
Management collection in languages like Python). manually.
Application software, web development, System software, embedded systems,
Use Case
scientific computing. hardware programming.
Examples:
High-Level Language (Python):
sum = 5 + 3
print(sum)
Low-Level Language (Assembly - conceptual):
MOV A, 5
MOV B, 3
ADD A, B
STORE SUM, A
UNIT 2
Variables, expressions and statements
Values and data types: A value is one of the fundamental things — like a letter or a number — that a
program manipulates
These values are classified into different classes, or data types: 4 is an integer, and
"Hello ,World!"string, so-called because it contains a string of letters.
The integer, floating-point and String Data Types
The expressions are just values combined with operators, and they always evaluate down to a single value.
A data type is a category for values, and every value belongs to exactly one data type.
The integer (or int) data type indicates values that are whole numbers.
Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats).
Note that even though the value 42 is an integer, the value 42.0 would be a floating-point number.
Python programs can also have text values called strings, or strs and surrounded in single quote.
The string with no characters, '', called a blank string.
If the error message SyntaxError: EOL while scanning string literal, then probably the final single quote
character at the end of the string is missing.
If you are not sure what class a value falls into, Python has a function called type which can tell you.
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
Double quoted strings can contain single quotes inside them, as in "Bruce's beard", and single quote strings
can have double quotes inside them, as in 'The knights who say "Ni!"'.
Strings enclosed with three occurrences of either quote symbol are called triple quoted strings. They can
contain either single or double quotes:
>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
"Oh no", she exclaimed, "Ben's bike is broken
VARIABLE
A variable is essentially a name that refers to a value stored in memory. You can think of it as a labeled box where you can put
data and use it later.
Creating a Variable
You assign a value to a variable using the = operator:
x = 10 # x now holds the value 10
name = "Alice" # name holds the string "Alice"
Storing values inVariables
A variable is like a box in the computer’s memory where you can store a single value.
If we need to use variables later, then the result must be stored in variable.
Assignment Statements
You’ll store values in variables with an assignment statement.
An assignment statement consists of a variable name, an equal sign (called the assignment operator),
and the value to be stored.
Ex: spam = 42
Variable names
We can name a variable anything as long as it obeys the following three rules:
1. It can be only one word.
2. It can use only letters, numbers, and the underscore (_) character.
3. It can’t begin with a number.
Variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are four different
variables.
This book uses camelcase for variable names instead of underscores; that is,
variables lookLikeThis instead of looking_like_this.
A good variable name describes the data it contains
KEYWORDS
Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter.
Each keyword have aspecial meaningand a specific [Link] keywords can't be used as variable.
Following is the Listo fPython Keywords
Type converter functions
Python functions, int, float and str, which will (attempt to) convert their arguments into types int, float and str
respectively. We call these type converter functions. The int function can take a floating point number or a string,
and turn it into an int. For floating point numbers, it discards the decimal portion of the number
>>> int(3.14)
3
>>> int(3.9999) # This doesn't round to the closest int!
3
>>> int(3.0)
3
>>> int(-3.999) # Note that the result is closer to zero
-3
>>> int(minutes / 60)
10
>>> int("2345") # Parse a string to produce an int
2345
>>> int(17) # It even works if arg is already an int
17
>>> int("23 bottles")
The type converter float can turn an integer, a float, or a syntactically legal string into a float
>>> float(17)
17.0
>>> float("123.45")
123.45
The type converter str turns its argument into a string:
>>> str(17)
'17'
>>> str(123.45)
'123.45'
STATEMENT
A statement is an instruction that the Python interpreter can execute. We have only seen the assignment
statement so far. Some other kinds of statements that we’ll see shortly are while statements, for statements, if
statements, and import statement
Evaluating expressions
An expression is a combination of values, variables, operators, and calls to functions. If you type an expression
at the Python prompt, the interpreter evaluates it and displays the result
>>> 1 + 1
2
>>> len("hello")
5
Operators and operands
Operators are special tokens that represent computations like addition, multiplication and division. The values
the operator uses are called operands. The tokens +, -, and *, and the use of parenthesis for grouping, mean in
Python what they mean in mathematics. The asterisk (*) is the token for multiplication, and ** is the token for
exponentiation.
>>> 2 ** 3
8
>>> 3 ** 2
9
Order of operations
When more than one operator appears in an expression, the order of evaluation depends on the rules of
precedence. Python follows the same precedence rules for its mathematical operators that mathematics does.
The acronym PEM-DAS is a useful way to remember the order of operations:
1. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you
want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You
can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it
doesn’t change the result.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
3. Multiplication and both Division operators have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 5-2*2 is 1, not 6
4. Operators with the same precedence are evaluated from left-to-right. In algebra we say they are left-
associative.
So in the expression 6-3+2, the subtraction happens first, yielding 3. We then add 2 to get the result 5. If
the operations had been evaluated from right to left, the result would have been 6-(3+2), which is 1.
>>> 2 ** 3 ** 2 # The right-most ** operator gets done first! 512
>>> (2 ** 3) ** 2 # Use parentheses to force the order you want! 64
EXAMPLE
1. 2*(3-1) 3. 2**1 + 1
2*2=4 2+1=3
2. (1+1) **(5-2) 4. 3*1**3
2**3 3*1=3
LEFT ASSOCIATIVITY
1. 6-(3+2) 2. 2**3**2
6-5=1 8**2=64
Creating Strings
s1 = 'Hello'
s2 = "World"
s3 = """This is
a multi-line string"""
2. String Concatenation
Join (combine) two or more strings using +
a = "Hello"
b = "World"
c=a+""+b
print(c) # Output: Hello World
3. String Repetition
Repeat a string using *
x = "Hi! "
print(x * 3) # Output: Hi! Hi! Hi!
4. Length of String
s = "Python"
print(len(s)) # Output: 6
5. Indexing & Slicing
Access characters or parts of strings.
s = "Python"
print(s[0]) # P (first character)
print(s[-1]) # n (last character)
print(s[0:3]) # Pyt
print(s[2:]) # thon
print(s[:4]) # Pyth
6. String Slicing with Steps
s = "Python"
print(s[::2]) # Pto (every 2nd char)
print(s[::-1]) # nohtyP (reversed string)
String Case Operations
s = "python"
print([Link]()) # PYTHON
print([Link]()) # python
print([Link]()) # Python
print([Link]()) # Python
print([Link]()) # PYTHON -> python or vice versa
s = "Python3"
print([Link]()) # False (contains digit)
print([Link]()) # False
print([Link]()) # True (letters + numbers)
print([Link]()) # False
INPUT
There is a built-in function in Python for getting input from the user:
EX- name = input("Please enter your name: ")
The user of the program can enter the name and click OK, and when this happens the text that has been
entered is returned from the input function, and in this case assigned to the variable name.
Composition
One of the most useful features of programming languages is their ability to take small building blocks and
compose them into larger chunks.
Area = 𝜋𝑅2
Firstly, we’ll do the four steps one at a time:
response = input("What is your radius? ")
r = float(response)
area = 3.14159 * r**2
print("The area is ", area)
Now let’s compose the first two lines into a single line of code, and compose the second two lines into
another line of code
r = float( input("What is your radius? ") )
print("The area is ", 3.14159 * r**2)
The modulus operator
The modulus operator works on integers (and integer expressions) and gives the remainder when the first
number is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the
same as for other operators. It has the same precedence as the multiplication operator.
>>> q = 7 // 3 # This is integer division operator
>>> print(q)
2
>>> r = 7 % 3
>>> print(r)
1
So 7 divided by 3 is 2 with a remainder of 1
UNIT 3
ITERATIONS
Updating a variable
x=5
x = x + 1 # update x by adding 1
print(x) # Output: 6
Or, using a shorthand operator:
python
x=5
x += 1 # equivalent to x = x + 1
print(x) # Output: 6
Other shorthand operators:
python
x -= 2 # subtract 2 from x
x *= 3 # multiply x by 3
x /= 4 # divide x by 4
x %= 2 # remainder after division by 2
x **= 2 # raise x to the power of 2
Updating a Variable Inside a Loop
python
total = 0
for i in range(5):
total += i # keep updating total
print(total) # Output: 10 (0+1+2+3+4)
Updating Mutable Variables (like lists or dicts)
Python # Updating a list
numbers = [1, 2, 3]
[Link](4) # adds a new element
numbers[0] = 10 # updates first element
print(numbers) # Output: [10, 2, 3, 4]
# Updating a dictionary
person = {"name": "Alice", "age": 25}
person["age"] = 26
print(person) # Output: {'name': 'Alice', 'age': 26}
Basic Assignment
You use the = operator to assign a value:
x = 10
name = "Alice"
is_active = True
Here:
x stores an integer (10)
name stores a string ("Alice")
is_active stores a boolean (True)
🔁 Multiple Assignment
You can assign multiple variables in one line:
a, b, c = 1, 2, 3
print(a, b, c) # Output: 1 2 3
Or assign the same value to multiple variables:
x=y=z=0
print(x, y, z) # Output: 0 0 0
Compound Assignment (Updating a Variable)
Python supports compound assignment operators, which update and reassign at once:
x=5
x += 2 # same as x = x + 2
x -= 1 # same as x = x - 1
x *= 3 # same as x = x * 3
x /= 2 # same as x = x / 2
Assignment with Data Structures
You can unpack lists, tuples, and other iterables:
data = [10, 20, 30]
a, b, c = data
print(a, b, c) # Output: 10 20 30
s = "Hello"
s += " World"
print(s) # Output: Hello World
nums = [1, 2]
nums += [3, 4]
print(nums) # Output: [1, 2, 3, 4]
Special Cases
Assignment does not copy objects — it just creates a new reference:
python
a = [1, 2, 3]
b=a
[Link](4)
print(a) #
Output: [1, 2, 3, 4] (both a and b refer to same list)
FOR STATEMENT
for variable in sequence:
# code block
variable → gets each value from the sequence one by one.
sequence → the collection you’re looping through (e.g. list, range, string, etc.).
The code block inside the loop is indented.
Example 1: Looping Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Looping with range()
The range() function generates a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
Note: range(5) gives numbers from 0 to 4 (the end value is not included).
You can also specify a start, end, and step:
for i in range(2, 10, 2):
print(i)
Output:
2 8
4
6
Example 3: Looping Over a String
for letter in "Python":
print(letter)
Output:
P
y
t
h
o
n
Example 4: Looping Over a Dictionary
person = {"name": "Alice", "age": 25, "city": "Paris"}
for key, value in [Link]():
print(key, "→", value)
Output:
name → Alice
age → 25
city → Paris
while statement
The while statement in Python is used to repeat a block of code as long as a condition is true.
It’s ideal when you don’t know beforehand how many times you need to loop.
Basic Syntax
while condition:
# code block
condition → evaluated before each iteration.
If it’s True, the loop runs.
When it becomes False, the loop stops.
Example 1: Basic while Loop
count = 0
while count < 5:
print("Count is:", count)
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
The loop runs 5 times, stopping when count becomes 5.
Example 3: while with else
x=1
while x <= 3:
print(x)
x += 1
else:
print("Loop finished successfully!")
Output:
1
Loop finished successfully!
The break statement in Python is used to immediately exit a loop — whether it’s a for loop or a
while loop — even if the loop’s condition is still true.
It’s often used when a certain condition is met and you no longer need to continue looping.
BREAK STATEMENT
Basic Syntax
for item in sequence:
if condition:
break # exit the loop
or
while condition:
if condition_to_stop:
break
🔁 Example 1: Using break in a for loop
for i in range(10):
if i == 5:
break
print(i)
Output:
The loop stops as soon as i == 5.
Example 2: Using break in a while loop
count = 0
while True: # infinite loop
print(count)
count += 1
if count == 3:
break
Output:
CONTINUE STATEMENT
The continue statement in Python is used to skip the rest of the code inside a loop for the current
iteration — and move straight to the next iteration of the loop.
Basic Syntax
for variable in sequence:
if condition:
continue # skip the rest of this iteration
# rest of the code
or for a while loop:
while condition:
if condition_to_skip:
continue
# rest of the code
Example 1: Using continue in a for loop
for i in range(6):
if i == 3:
continue
print(i)
Output:
When i == 3, the loop skips the print(i) statement and jumps to the next iteration.
Example 2: Using continue in a while loop
x=0
while x < 5:
x += 1
if x == 2:
continue
print(x)
Output:
The loop skips printing 2.
TABLES
In Python, “tables” can mean different things depending on what you want to do —
you can create tables for displaying data, storing structured data, or analyzing datasets.
1. Using Lists of Lists (Basic Table)
You can represent a table as a list of rows, where each row is a list of columns:
table = [
["Name", "Age", "City"],
["Alice", 25, "London"],
["Bob", 30, "Paris"],
["Charlie", 28, "New York"]
]
# Display the table neatly
for row in table:
print(row)
Output:
['Name', 'Age', 'City']
['Alice', 25, 'London']
['Bob', 30, 'Paris']
['Charlie', 28, 'New York']
2. Using a List of Dictionaries
This format is more readable and easier to manipulate:
table = [
{"Name": "Alice", "Age": 25, "City": "London"},
{"Name": "Bob", "Age": 30, "City": "Paris"},
{"Name": "Charlie", "Age": 28, "City": "New York"}
]
for row in table:
print(row["Name"], "is", row["Age"], "years old from", row["City"])
Output:
Alice is 25 years old from London
Bob is 30 years old from Paris
Charlie is 28 years old from New York
TWO DIMENSIONAL TABLES
Using a List of Lists (2D List)
A 2D table can be represented as a list of lists, where each inner list is a row:
# 3x3 table
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements: table[row][column]
print(table[0][1]) # 2 (row 0, column 1)
Iterating over the table
for row in table:
for value in row:
print(value, end=" ")
print() # new line after each row
Output:
123
456
789
2. Using Nested Loops with Indices
If you need the row and column numbers:
for i in range(len(table)):
for j in range(len(table[i])):
print(f"table[{i}][{j}] = {table[i][j]}")
Output:
table[0][0] = 1
table[0][1] = 2
table[0][2] = 3
table[1][0] = 4
table[1][1] = 5
table[1][2] = 6
table[2][0] = 7
table[2][1] = 8
table[2][2] = 9