0% found this document useful (0 votes)
18 views20 pages

Python Notes

The document provides an introduction to Python programming, detailing its high-level nature and advantages over low-level languages. It covers the Python interpreter's modes, the concept of programs and debugging, and introduces variables, data types, and naming conventions. Additionally, it explains common programming errors and the importance of debugging in the programming process.

Uploaded by

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

Python Notes

The document provides an introduction to Python programming, detailing its high-level nature and advantages over low-level languages. It covers the Python interpreter's modes, the concept of programs and debugging, and introduces variables, data types, and naming conventions. Additionally, it explains common programming errors and the importance of debugging in the programming process.

Uploaded by

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

Python Programming [1BPLC105B] 2025-2026

Chapter 1.

The Way of the Program

1.1 The Python programming language

➢ Python is a high-level programming language, designed to be easy to read and write.


➢ Other examples of high-level languages include C++, PHP, Pascal, C#, and Java.
➢ Low-level languages (machine languages or assembly languages) are closer to the
computer's hardware and harder for humans to read.
➢ Computers can only execute low-level languages, so high-level programs must be
translated before running.

Advantages of High-Level Languages

➢ Easier to program: Code takes less time to write.


➢ More readable: Programs are shorter and easier to understand.
➢ Fewer errors: Easier to debug and more likely to be correct.
➢ Portability: Can run on different types of computers with little or no modification.

Python Interpreter:

➢ The Python Interpreter is the engine that translates and runs Python code.
➢ There are two modes to use the interpreter:

1. Immediate Mode:
▪ Type Python expressions directly into the interpreter window.
▪ Results are shown immediately.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

For Example: >>> 2 + 3

2. Script Mode:

▪ Write Python code in a .py file.


▪ Run the entire script at once.
▪ Ideal for longer programs and saving your work.

For Example

• Create a Python script file


o Save your code in a file with a .py extension, such as greeting.py.
• Write your Python code
o Example:

name = input("What is your name? ")


print("Hello, " + name + "! Welcome to Python script mode.")

• Run the script using a terminal or command prompt


o Type the following command:

python greeting.py

• Program interaction
o The script will prompt: What is your name?
o You enter your name, e.g., Inbalatha
• Output from the script
o It responds: Hello, Inbalatha! Welcome to Python script mode.
• Why use script mode?
o Ideal for writing complete programs
o Allows saving and reusing code
o Better suited for larger or more complex tasks

1.2 What is a Program?


• A program is a sequence of instructions that tells a computer how to perform a
computation.
• Computations can be:
o Mathematical: e.g., solving equations or finding polynomial roots.
o Symbolic: e.g., searching and replacing text or compiling another program.

Common Instructions in Most Programming Languages

• Input:

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

o Collect data from sources like the keyboard, files, or sensors.


• Output:
o Display results on the screen or send data to files or devices (e.g., motors).
• Math:
o Execute basic operations such as addition, subtraction, multiplication, and
division.
• Conditional Execution:
o Evaluate conditions and run specific instructions based on the outcome.
• Repetition (Loops):
o Repeat actions, often with changes each time (e.g., iterating through a list).

1.3 What Is Debugging?


• Debugging is the process of identifying and fixing errors (bugs) in a program.
• Programming is complex and prone to mistakes because it’s done by humans.
• The term "bug" has been used to describe engineering issues since at least 1889, when
Thomas Edison mentioned a bug in his phonograph.

1.4 Types of Programming Errors


1. Syntax Errors

➢ Mistakes in the structure or grammar of the code (e.g., missing


parentheses or misspelled keywords).

2. Runtime Errors

➢ Errors that occur while the program is running (e.g., dividing by zero or
accessing an invalid index).

3. Semantic Errors

➢ The program runs without crashing but produces incorrect results due to
flawed logic or meaning.

1.5 Experimental Debugging


• Debugging is a vital programming skill, often challenging but intellectually rewarding.
• It can be frustrating, yet it's one of the most interesting and enriching aspects of
programming.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

🕵️ Debugging as Detective Work

• Debugging involves analyzing clues (errors or unexpected behavior).


• You must infer the underlying causes based on observed results.

🔬 Debugging as Experimental Science

• Form a hypothesis about what might be wrong.


• Modify the program and test your hypothesis.
o If correct: the program improves.
o If incorrect: revise your hypothesis and try again.
• Echoing Sherlock Holmes:

🔄 Programming as Iterative Debugging

• For many, programming is debugging—gradually refining a program until it works.


• Start with a basic working version and make small, testable changes.
• Always maintain a functional version of your program during development.

🐧 Real-World Example: Linux

• Linux, a powerful operating system kernel, began as a simple experiment.


• Linus Torvalds initially wrote a program to switch between displaying AAAA and
BBBB.
• This modest project evolved into the Linux kernel, now containing millions of lines of
code.

1.6 Glossary

algorithm A set of specific steps for solving a category of problems.


bug An error in a program.
comment Information in a program that is meant for other programmers (or anyone reading the source
code) and has no effect on the execution of the program.
debugging The process of finding and removing any of the three kinds of programming errors.
exception Another name for a runtime error.
formal language Any one of the languages that people have designed for specific purposes, such as
representing mathematical ideas or computer programs; all programming languages are formal
languages.
high-level language A programming language like Python that is designed to be easy for humans to read and
write.
immediate mode A style of using Python where we type expressions at the command prompt, and the
results are shown immediately. Contrast with script, and see the entry under Python shell.
interpreter The engine that executes your Python scripts or expressions.
low-level language A programming language that is designed to be easy for a computer to execute; also
called ma- chine language or assembly language.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

natural language Any one of the languages that people speak that evolved naturally.
object code The output of the compiler after it translates the program.
parse To examine a program and analyze the syntactic structure.
portability A property of a program that can run on more than one kind of computer.
print function A function used in a program or script that causes the Python interpreter to display a value
on its output device.

Problem solving The process of formulating a problem, finding a solution, and expressing the solution.
program a sequence of instructions that specifies to a computer actions and computations to be performed.
Python shell An interactive user interface to the Python interpreter. The user of a Python shell types
commands at the prompt (>>>), and presses the return key to send these commands immediately to
the interpreter for processing. The word shell comes from Unix.
runtime error An error that does not occur until the program has started to execute but that prevents
the program from continuing.
script A program stored in a file (usually one that will be interpreted).
semantic error An error in a program that makes it do something other than what the programmer intended.
semantics The meaning of a program.
source code A program in a high-level language before being compiled.
syntax The structure of a program.
syntax error An error in a program that makes it impossible to parse — and therefore impossible to interpret.
token One of the basic elements of the syntactic structure of a program, analogous to a word in a natural
language.

Chapter 2
Variables, Expressions and Statements

2.1 Values and data types

➢ A value is one of the fundamental things — like a letter or a number —


that a program manipulates.
➢ The values we have seen so far are 4(the result when we added 2 + 2),
and "Hello, World!”
➢ These values are classified into different classes, or data types: 4 is an
integer, and "Hello, World!" is a string, so-called because it contains a
string of letters.
➢ The interpreter can identify strings because they are enclosed in
quotation marks.
➢ If you are not sure what class a value falls into, Python has a function
called type which can tell you.

>>> type ("Hello, World!")

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

<class 'str'>
>>> type(17)
<class 'int'>

➢ strings belong to the class str and integers belong to the class int.
➢ Less obviously, numbers with a decimal point belong to a class called float,
because these numbers are represented in a format called floating-point.

>>> type(3.2)
<class 'float'>

➢ Also values like "17"and "3.2” look like numbers, but they are in quotation
marks like strings.

>>> type("17")
<class 'str'>
>>> type("3.2")
<class 'str'>

➢ They’re strings!
➢ Strings in Python can be enclosed in either single quotes (') or double
quotes ("), or three of each ('''or """)

>>> type('This is a string.')


<class 'str'>
>>> type("And so is this.")
<class 'str'>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str'>

➢ Double quoted strings can contain single quotes inside them, as in "Bruce's beard", and single
quoted 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

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')


"Oh no", she exclaimed, "Ben's bike is broken!"
>>>
contain either single or double quotes:

➢Triple quoted strings can even span multiple lines

>>> message = """This message will


... span several
... lines."""
>>> print(message)
This message will span
several lines.
>>>
➢ When the interpreter wants to display a string, it has to decide which quotes to use to make it look like a
string. So the Python language designers usually chose to surround their strings by single quotes.

>>> 'This is a string.'


'This is a string.'
>>> """And so is this."""
'And so is this.'

2.2 Variables

➢ A variable is a name that refers to a value.


➢ The assignment statement gives a value to a variable:

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159

➢ This example makes three assignments:


o The first assigns the string value "What's up, Doc?" to a variable named
message.
o The second gives the integer 17 to a variable n, and
o The third assigns the floating-point number 3.14159 to a variable called pi.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ The assignment token, =, should not be confused with equals, which uses the token
==.
➢ The assignment statement binds a name, on the left-hand side of the operator, to a
value, on the right-hand side.
➢ Basically, an assignment is an order, and the equals operator can be read as a question
mark. This is why you will get an error if you enter:

>>> 17 = n
File "<interactive input>", line 1
SyntaxError: can't assign to literal

➢ If you ask the interpreter to evaluate a variable, it will produce the value that is currently
linked to the variable:

>>> message
'What's up, Doc?'
>>> n
17
>>> pi
3.14159

➢ We use variables in a program to “remember” things, perhaps the current score at the
football game.
➢ But variables are variable.
➢ This means they can change over time, just like the scoreboard at a football game.
➢ We can assign a value to a variable, and later assign a different value to the same
variable. (This is different from maths. In maths, if you give ‘x‘ the value 3, it cannot
change to link to a different value half-way through your calculations!)

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ We changed the value of day three times, and on the third assignment we even made it
refer to a value that was of a different type.

>>> day = "Thursday"


>>> day
'Thursday'
>>> day = "Friday"
>>> day
'Friday'
>>> day = 21
>>> day
21

2.3 Variable Names and Keywords

➢ Variable names can be arbitrarily long.


➢ They can contain both letters and digits, but they have to begin with a letter or an
underscore.
➢ Although it is legal to use uppercase letters, by convention we don’t.
➢ If you do, remember that case matters.
➢ For example: Bruce & bruce are different variables.
➢ The underscore character (_) can appear in a name. It is often used in names with multiple
words, such as my_name or price_of_tea_in_china.
➢ There are some situations in which names beginning with an underscore have special
meaning, so a safe rule for beginners is to start all names with a letter.
➢ If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = "big parade"


Syntax Error: invalid syntax
>>> more$ = 1000000
Syntax Error: invalid syntax
>>> class = "Computer Science 101"
Syntax Error: invalid syntax

o 76trombones is illegal because it does not begin with a letter.

o More $ is illegal because it contains an illegal character, the dollar sign.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

o Class is illegal since It turns out that class is one of the Python keywords.
Keywords define the language’s syntax rules and structure, and they cannot be
used as variable names.
o Python has thirty-something keywords (and every now and again improvements
to Python introduce or eliminate one or two):

and as assert break class continue


def del elif else except exec
finally for from global if import
in is lambda nonlocal not or
pass raise return try while with
yield True False None

➢ Programmers generally choose names for their variables that are meaningful to the
human readers of the program — they help the programmer document, or remember,
what the variable is used for.

2.4 Statements

➢ A Statement is an instruction that the Python interpreter can execute.

➢ Other than assignment statements, some other kinds of statements are while statements,
for statements, if statements, and import statements. (There are other kinds too!)
➢ When you type a statement on the command line, Python executes it. Statements don’t
produce any result.

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

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ In this example, len is a built-in Python function that returns the number of characters
in a string.
➢ We’ve previously seen the print and the type functions, so this is our third example
of a function.
➢ The evaluation of an expression produces a value, which is why expressions can appear
on the right hand side of assignment statements.
➢ A value all by itself is a simple expression, and so is a variable.

>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14

2.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 following are all legal Python expressions whose meaning is more or less
clear:
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

➢ 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

➢ When a variable name appears in the place of an operand, it is replaced with its value
before the operation is performed. (Addition, subtraction, multiplication, and
exponentiation).

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ Example: Let us convert 645 minutes into hours:

>>> minutes = 645


>>> hours = minutes / 60
>>> hours
10.75

➢ In Python 3, the division operator / always yields a floating point result.


➢ What we might have wanted to know was how many whole hours there are, and how
many minutes remain.
➢ Python gives us two different flavors of the division operator.
➢ The second, called floor division uses the token //.
➢ Its result is always a whole number — and if it has to adjust the number it always
moves it to the left on the number line.
➢ So 6 // 4 yields 1.
>>> 7 / 4
1.75
>>> 7 // 4
1
>>> minutes = 645
>>> hours = minutes // 60
>>> hours
10

2.1 Type converter functions

➢ In Python three more 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 — a process
we call truncation towards zero on the number line. For Example:

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

>>> 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)
17 # It even works if arg is already an int
>>> int("23 bottles")

Trace back (most recent call last):


File "<interactive input>", line 1, in <module>
Value Error: invalid literal for int() with base 10: '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'

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

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

• Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-


2) is 8.
• A l s o w e c a n u se 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.
• (The acronym PEDMAS could mislead you to thinking that division has higher
precedence than multiplication, and addition is done ahead of subtraction - don’t be
misled. Subtraction and addition are at the same precedence, and the left-to-right rule
applies.)
➢ Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation
operator **, so a useful hint is to always use parentheses to force exactly the order you want when
exponentiation is involved:

>>> 2 ** 3 ** 2 # The right-most ** operator gets done first!


512
>>> (2 ** 3) ** 2 # Use parentheses to force the order you want!
64

➢ The immediate mode command prompt of Python is great for exploring and experimenting with expressions
like this.

2.6 Operations on strings

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers.
The following are illegal (assuming that message has type string):

>>> message - 1 # Error


>>> "Hello" / 123 # Error
>>> message * "Hello" # Error
>>> "15" + 2 # Error

➢ The + operator does work with strings, but for strings, the + operator represents concatenation, not
addition. Concatenation means joining the two operands by linking them end-to-end.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ For example:

fruit1= "banana"
baked_good
2
= " nut bread"
3
print(fruit + baked_good)
➢ The output of this program is banana nut bread.

➢ The space before the word nut is part of the string, and is necessary to produce the space
between the concatenated strings.
➢ The * operator also works on strings; it performs repetition.
➢ For example, 'Fun'*3 is 'FunFunFun'.
➢ One of the operands has to be a string; the other has to be an integer.

2.1 Input

➢ There is a built-in function in Python for getting input from the user:

name
1
= 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.
➢ Even if you asked the user to enter their age, you would get back a string like "17".
➢ It would be your job, as the programmer, to convert that string into a int or a float, using the
int or float converter functions we saw earlier.

2.2 Composition

➢ So far, we have looked at the elements of a program — variables, expressions, statements, and
function calls — in isolation, without talking about how to combine them.
➢ One of the most useful features of programming languages is their ability to take small building
blocks and compose them into larger chunks.
➢ For example, we know how to get the user to enter some input, we know how to convert the
string we get into a float, we know how to write a complex expression, and we know how to
print values.
➢ Let’s put these together in a small four-step program that asks the user to input a value for the
radius of a circle, and then computes the area of the circle from the formula

Area = 𝜋𝑅2

➢ Firstly, we’ll do the four steps one at a time:


response
1 = input("What is your radius? ")
r = float(response)
2

3
area = 3.14159 * r**2
print("The area is ", area)

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ 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(
1
input("What is your radius? ") )
2
print("The area is ", 3.14159 * r**2)
➢ If we really wanted to be tricky, we could write it all in one statement:

print("The
1 area is ", 3.14159*float(input("What is your radius?"))**2)

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


➢ The modulus operator turns out to be surprisingly useful.
➢ For example, you can check whether one number is divisible by another—if x % y is zero,
then x is divisible by y.
➢ Also, you can extract the right-most digit or digits from a number.
➢ For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100
yields the last two digits.
➢ It is also extremely useful for doing conversions, say from seconds, to hours, minutes and seconds.
➢ For example, write a program to ask the user to enter some seconds, and to convert them
into hours, minutes, and remaining seconds.

1 total_secs = int(input("How many seconds, in total?"))


2
hours = total_secs // 3600
3

4
secs_still_remaining = total_secs % 3600
5 minutes = secs_still_remaining // 60
6 secs_finally_remaining = secs_still_remaining % 60
7

8 print("Hrs=", hours, " mins=", minutes,


"secs=", secs_finally_remaining)

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

Glossary

assignment statement A statement that assigns a value to a name (variable). To the left of the assignment
operator,
=, is a name. To the right of the assignment token is an expression which is evaluated by the Python
interpreter and then assigned to the name. The difference between the left and right hand sides of
the assignment statement is often confusing to new programmers. In the following assignment:

number = number + 1

number plays a very different role on each side of the =. On the right it is a value and makes up
part of the
expression which will be evaluated by the Python interpreter before assigning it to the name on the
left.
assignment token = is Python’s assignment token. Do not confuse it with equals, which is an operator for
comparing values.
composition The ability to combine simple expressions and statements into compound statements and
expressions in order to represent complex computations concisely.
concatenate To join two strings end-to-end.
data type A set of values. The type of a value determines how it can be used in expressions. So far,
the types you have seen are integers (int), floating-point numbers (float), and strings (str).
evaluate To simplify an expression by performing the operations in order to yield a single value.

expression A combination of variables, operators, and values that represents a single result value.
float A Python data type which stores floating-point numbers. Floating-point numbers are stored
internally in two parts: a base and an exponent. When printed in the standard format, they look like
decimal numbers. Beware of rounding errors when you use floats, and remember that they are
only approximate values.
floor division An operator (denoted by the token //) that divides one number by another and yields an
integer, or, if the result is not already an integer, it yields the next smallest integer.
int A Python data type that holds positive and negative whole numbers.
keyword A reserved word that is used by the compiler to parse program; you cannot use keywords like if,
def, and
while as variable names.
modulus operator An operator, denoted with a percent sign ( %), that works on integers and yields the
remainder when one number is divided by another.
operand One of the values on which an operator operates.
operator A special symbol that represents a simple computation like addition, multiplication, or string
concatenation.
rules of precedence The set of rules governing the order in which expressions involving multiple
operators and operands are evaluated.
state snapshot A graphical representation of a set of variables and the values to which they refer, taken at a

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

particular instant during the program’s execution.


statement An instruction that the Python interpreter can execute. So far we have only seen the
assignment statement, but we will soon meet the import statement and the for statement.
str A Python data type that holds a string of characters.
value A number or string (or other things to be named later) that can be stored in a variable or
computed in an expression.
variable A name that refers to a value.
variable name A name given to a variable. Variable names in Python consist of a sequence of letters (a..z,
A..Z, and
_) and digits (0..9) that begins with a letter. In best programming practice, variable names should
be chosen so that they describe their use in the program, making the program self documenting.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

3.1 Iteration

➢ Computers are often used to automate repetitive tasks.


➢ Repeating identical or similar tasks without making errors is something that computers do well
and people do poorly.
➢ Repeated execution of a set of statements is called iteration.
➢ Because iteration is so common, Python provides several language features to make it easier.

3.1.1 Assignment

➢ It is legal to make more than one assignment to the same variable.

➢ A new assignment makes an existing variable refer to a new value (and stop referring to the old value).

1
airtime_remaining = 15
2

3
print(airtime_remaining)
4 airtime_remaining = 7
print(airtime_remaining)

➢ The output of this program is:

15
7
➢ Because the first time airtime_remaining is printed, its value is 15, and the second time, its value is 7.
➢ It is especially important to distinguish between an assignment statement and a Boolean expression that
tests for equality.
➢ Because Python uses the equal token (=) for assignment, it is tempting to interpret a statement like a =
b as a Boolean test. Unlike mathematics, it is not!
➢ Remember that the Python token for the equality operator is ==.
➢ Note too that an equality test is symmetric, but assignment is not.
➢ For example, if a == 7 then 7 == a. But in Python, the statement a = 7 is legal and 7 = a is
not.
➢ In Python, an assignment statement can make two variables equal, but because further assignments can
change either of them, they don’t have to stay that way:

1 a=5
2 b = a # After executing this line, a and b are now equal
3
a = 3 # After executing this line, a and b are no longer equal

➢ The third line changes the value of a but does not change the value of b, so they are no longer equal.
➢ In some programming languages, a different symbol is used for assignment, such as <- or :=, to avoid
confusion.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1
Python Programming [1BPLC105B] 2025-2026

➢ Some people also think that variable was an unfortunae word to choose, and instead we should have
called them assignables.
➢ Python chooses to follow common terminology and token usage, also found in languages like C, C++,
Java, and C#, so we use the tokens = for assignment, == for equality, and we talk of variables.

Prof. Inbalatha .K, Dept. of CSE (AI & ML), Dr.TTIT, KGF 1

You might also like