1BPLC105B Python Programming
Module -1
Chapter 2:Variables, Expressions and Statements
Values and Data Types
What is a Value?
A Value is one of the fundamental pieces of data that a program manipulates.
Examples: The number 4 (result of 2 + 2) or the text "Hello, World!".
What is a Data Type (or Class)?
Values are organized into distinct categories called Data Types (or classes).
This classification tells Python how to store the value in memory and what operations can be
performed on it.
The terms 'class' and 'type' can be used interchangeably at this foundational stage.
Primary Data Types
Integer (int):
Represents whole numbers (no fractional or decimal part).
Used for counting and discrete quantities.
Example: 17, 4
Float (float):
Represents numbers that contain a decimal point.
These numbers are stored using a floating-point format.
Used for precise measurements and continuous values.
Example: 3.2, 3.14159
String (str):
Represents a sequence of characters (text).
Strings are always identified and delimited by quotation marks (single, double, or
triple).
Any value enclosed in quotes, even numbers like "17", is classified as a string.
Example: "Hello, World!", 'This is text.'
How to Determine a Data Type
Python provides the built-in function type() to explicitly check the class of any value.
Example:
String Definition and Quoting Rules
Strings are defined by their enclosure in quotation marks. This is a critical distinction:
Quoted Numbers are Strings: Values that look numerical but are enclosed in quotes are
treated as strings.
Example: type("17") returns <class 'str'>, even though 17 is a number.
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Quote Options: Strings can be enclosed using three different styles:
1. Single quotes ( ' )
2. Double quotes ( " )
3. Triple quotes (' ' ' or " " ")
Example:
Nesting Quotes for Clarity: Use single quotes for a string containing double quotes, and vice-
versa, to avoid confusion.
Example: 'The knights who say "Ni!"'
Example:
Triple Quotes for Structure: Triple-quoted strings are useful because they can span multiple
lines and safely contain both single and double quotes within the text.
Example:
Note:The Python language designers usually chose to surround displayed strings with single quotes (')
when representing them back to the user (like in the interpreter's output).
Example:
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Strict Notation Rules (Avoiding Commas)
Commas are Illegal in Numbers: When typing large numbers, you must not use
commas as digit separators (e.g., 42,000).
Commas Create Pairs: Python interprets the comma in 42,000 not as a separator,
but as a structure used to create a pair of values (which are covered later).
Example:
Rule: For integers, regardless of size, enter only the digits (e.g., 42000). This reinforces
the strictness of formal programming languages.
Variables
A variable is a powerful feature in programming.
It's a name that acts as a label or reference, allowing the computer to refer to a value
stored in memory.
Variables are used to hold and track dynamic information throughout a program's
execution.
The Assignment Statement
The process of giving a value to a variable is done using the assignment statement.
Example:
Token: The assignment token is the single equals sign, =.
Syntax and Direction: The statement binds the name on the Left-Hand Side (LHS) of
the = operator to the value on the Right-Hand Side (RHS).
Example 1: n = 17 means "n is assigned the value 17."
Example 2: greeting = "Good Morning" (The variable greeting is assigned the string
value "Good Morning.")
Distinction from Equality: The assignment token = should not be confused with the
equality operator == (which is used to ask if two values are equal).
Syntax Error: You cannot assign a value to a literal (a raw value). The variable name
must always be on the LHS.
Example:
Variable State and Evaluation
State Snapshot: On paper, variables are often represented with an arrow pointing from
the name to its current value (a "state snapshot") .
Example:
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Evaluation: When you ask the interpreter to evaluate a variable, it produces the value
currently linked to that variable.
Example:
Variables are Changeable (Variable)
Unlike algebraic variables in mathematics, variables in programming can change their
value over time, this is the defining characteristic that makes them variable.
Reassignment: You can assign a new value to an existing variable at any point.
Example:
Type Change: A variable can even be reassigned a value of a different data type.
Example:
Programming frequently involves using variables to store data (like a score or a counter)
and then updating or changing those variables as the program runs.
Example:
Variable Names and Keywords
1. Rules for Creating Valid Variable Names (The Syntax)
Variable names must adhere to the following strict rules:
Allowed Characters: Names can contain letters (A-Z, a-z) and digits (0-9). The
underscore character (_) is also permitted.
Starting Character: A name must begin with a letter or an underscore (_). It cannot
start with a digit.
Example: 76trombones = "parade" -> Syntax Error (Starts with a digit).
Forbidden Symbols: Names cannot include special characters such as dollar sign ( $), @,
or spaces.
Example: more$ = 1000000 ->Syntax Error (Contains $).
Length: Variable names can be arbitrarily long.
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
2. Keywords (The Forbidden List)
Keywords are reserved words in Python that have fixed meanings, defining the language's
syntax and structure. They cannot be used as variable names.
Example: class = "CS 101" -> Syntax Error (Because class is a keyword).
3. Case Sensitivity
Python is a case-sensitive [Link] means capitalization matters:
Example:Bruce and bruce are treated as two distinct and separate variables in memory.
4. Naming Conventions (For Readability)
While the syntax rules make a name legal, conventions make it good.
Use Lowercase (Convention): By standard convention, variable names should
generally use lowercase letters.
Underscores for Separation: Use the underscore character ( _) to separate words in multi-
word variable names (known as snake_case).
Example: price_of_tea_in_china
Beginner Safety: It's safest for beginners to start all names with a letter. Names starting with an
underscore (e.g., _secret) sometimes have special meanings in Python.
5. Importance of Meaningful Names (Programmer's Job)
The most important convention is choosing names that are meaningful to human readers.
Readability: Meaningful names serve as documentation, making the code much easier for others (and
your future self) to understand.
Example Comparison:
Poor: e = 3.1415, ray = 10, size = e * ray ** 2
Good: pi = 3.1415, radius = 10, area = pi * radius ** 2
Computer Ignorance (Caution): Remember that the computer does not understand your [Link]
a variable the name pi does not automatically assign it the value 3.14159. You, the programmer, must
write the assignment statement (pi = 3.14159) for the computer to associate that name with that value.
Statements
A Statement is a complete instruction that the Python interpreter executes. Statements are the
fundamental commands that make a program do something.
Function: Statements are executed for their effect they change the program's state (e.g.,
creating a variable, displaying output).
Result: A statement does not produce a value when executed.
Examples:
Assignment Statement: Assigns a value to a variable. (e.g., n = 17)
Control Flow Statements: Directs the program flow. (e.g., while, for, if)
Module Statements: Loads external code. (e.g., import math)
Output Statements: (e.g., print("Done"))
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Evaluating Expressions
An Expression is a combination of values, variables, operators, and function calls that the
interpreter evaluates to produce a single value.
Function: The goal of an expression is to calculate or represent a value.
Result: An expression always produces a value.
Example: If you type an expression at the prompt, the interpreter calculates and displays the result.
Simple Expressions: Even a single value or a variable is a simple expression:
Because expressions produce a value, they are always found on the Right-Hand
Side (RHS) of an assignment statement, where the calculated value is bound to a variable name.
Example: x = len("hello") (Here, len("hello") is the expression that runs first, producing 5, which is
then assigned to the variable x).
Operators and Operands
Operators are special tokens that represent mathematical or logical computations
Operands are the values or variables that the operator acts upon
Standard Arithmetic Operators
The tokens for basic operations are familiar from mathematics:
Operator Meaning Example Output
+ Addition 5+3 8
- Subtraction 9-4 5
* Multiplication 6*2 12
/ Division (float) 7/2 3.5
// Floor division 7 // 2 3
% Modulus 7%3 1
** Exponentiation 2 ** 3 8
Variable Substitution: When a variable name is used as an operand, Python first
replaces the name with its current value before performing the operation.
Example:
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Division Operators
Python provides two distinct division operators, and choosing the correct one is essential:
True Division (/)
Function: Performs standard, accurate division.
Result Type: Always yields a floating-point number (float), even if the result is a whole
number.
Example:
Floor Division (//)
Function: Divides the numbers and then truncates the result, discarding the fractional part
to produce a whole number.
Behavior: The result is always moved to the left on the number line (or "floored").
Result Type: Always yields an integer (int).
Example:
Type Converter Functions
The three primary type converter functions are int(), float(), and str().
1. int() Function (Converts to Integer)
The int() function attempts to convert its argument into an integer (int).
From Float: When converting a floating-point number, it performs truncation toward zero. This mean
it discards the decimal portion of the number; it does not round to the nearest whole number.
Example (Positive): int(3.9999) yields 3.
Example (Negative): int(-3.999) yields -3.
From String: It can convert a string containing only digits into an integer.
Example: int("2345") yields 2345.
Failure Condition: It fails with a ValueError if the string contains non-numeric characters that aren't
part of a valid number.
Example: int("23 bottles") ->ValueError.
2. float() Function (Converts to Floating-Point)
The float() function attempts to convert its argument into a floating-point number (float).
From Integer: It adds a decimal component, representing the number as a float.
Example: float(17) yields 17.0.
From String: It can convert a syntactically correct numeric string into a float.
Example: float("123.45") yields 123.45.
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
3. str() Function (Converts to String)
The str() function converts its argument into a string (str).
Function: It takes any data type (integer, float, etc.) and returns its textual representation, enclosed in
quotes.
Example (From Integer): str(17) yields '17'.
Example (From Float): str(123.45) yields '123.45'.
Order of Operations (Operator Precedence)
When a mathematical expression contains multiple operators, Python follows standard rules of
precedence and associativity to determine the exact sequence of calculations, ensuring a reliable result.
These rules are generally the same as in traditional mathematics, summarized by the mnemonic
PEDMAS.
Precedence Levels
The hierarchy below determines which operations are performed first. Higher precedence
operations are executed before lower precedence ones.
[Link] Precedence: Parentheses (())
Expressions enclosed in parentheses are always evaluated first.
Parentheses are used to force a specific order of evaluation, overriding the default rules.
They also improve code readability.
Example: In 2 * (3 - 1), the subtraction (3 - 1) is done before the multiplication.
[Link] Highest: Exponentiation (**)
This power operator is evaluated next.
Example: In 2 ** 1 + 1, the exponentiation 2 ** 1 (which is 2) occurs before the addition.
[Link] Level: Multiplication, Division, and Modulus
The operators * (multiplication), / (true division), // (floor division), and % (modulus) all share
the same level of precedence.
[Link] Level: Addition and Subtraction
The operators + and - share the lowest level of precedence.
Associativity
When multiple operators have the same level of precedence (like +, -, *, or /), associativity
determines the direction of evaluation.
Left-to-Right Associativity (Standard Rule)
Most Python operators, including addition, subtraction, multiplication, and both
division operators, are left-associative. They are evaluated sequentially from left to right.
Example: In the expression 6 - 3 + 2, the evaluation proceeds from left to right:
6 - 3 is calculated first, yielding 3.
Then, 3 + 2 is calculated, yielding 5.
Right-to-Left Associativity (Exception for Exponentiation)
The exponentiation operator (**) is the major exception; it is right-associative.
This means when two or more ** operators appear, evaluation proceeds from right to
left.
Example: 2 ** 3 ** 2 is interpreted as 2^{(3^2)}.
The rightmost operation, 3 ** 2, is done first (yielding 9).
Then, 2 ** 9 is calculated (yielding 512).
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Note:It is always a good practice to use parentheses, like (2 ** 3) ** 2, to remove ambiguity and
control the calculation order.
Operations on Strings
The general rule is that you cannot perform mathematical operations on strings, even if they
contain numeric characters. Python treats strings purely as sequences of text.
1. General Rule: Mathematical Operations are Illegal
Attempting to use standard arithmetic operations like subtraction or division on strings, or trying
to combine a string and a number with anything other than multiplication or special conversion, results
in an error.
Type Error Examples:
message - 1 (Subtraction is not defined for strings.)
"Hello" / 123 (Division is not defined for strings.)
"15" + 2 (You cannot directly add a string and an integer; the types must match for
addition.)
2. Concatenation (The Redefined + Operator)
For strings, the addition operator (+) is overloaded to perform concatenation.
Definition: Concatenation is the process of joining two or more strings end-to-end to create a single,
longer string.
Syntax: Both operands must be strings.
Example:
fruit = "banana"
baked_good = " nut bread"
print(fruit + baked_good) # Output: banana nut bread
Note: Python does not automatically insert spaces. If you want a space between the words, you must
include it in one of the strings (as shown above) or explicitly concatenate a space: fruit + " " +
baked_good.
3. Repetition (The Redefined * Operator)
The multiplication operator (*) is overloaded for strings to perform repetition.
Definition: Repetition creates a new string by repeating the operand string a specified number of times.
Syntax: One operand must be a string, and the other must be an integer (the repetition count).
Example:
print('Fun' * 3) # Output: FunFunFun
This operation is analogous to multiplication by repeated addition (e.g., 4 times 3 is 4+4+4).
4. Conceptual Difference: Lack of Commutativity
While string operations are analogous to math, a key difference lies in the
Commutative Property (a + b = b + a):
Math is Commutative: The order of operands doesn't matter (e.g., 4 + 5 is the same as 5 + 4).
String Concatenation is NOT Commutative: The order of concatenation is essential, as it
changes the resulting string.
Example:
"World" + "Hello" results in "WorldHello".
"Hello" + "World" results in "HelloWorld".
This difference highlights that while the operators are the same, their functions are
fundamentally text-based, not numeric.
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Input Function (input())
The input() function is the primary built-in tool in Python used to pause the program and get
data directly from the user via the keyboard during execution.
1. How the Function Works
Prompting the User: The input() function accepts a single optional argument, which is the
prompt displayed to the user.
Example:
name = input("Please enter your name: ")
Execution: When Python executes this statement, the program waits until the user types
some text and presses the Enter key.
Assignment: The text entered by the user is the return value of the input() function, which
is then assigned to the variable (e.g., name).
2. The Critical Type Rule
Rule: The input() function always returns a value of the type string (str), regardless of what
the user types.
Example: If the user enters 17 when asked for their age, the input() function returns the string value
"17".
3. The Programmer's Responsibility (Type Conversion)
Since input() always returns a string, it is the programmer's job to explicitly convert this string
into the correct numeric type if it's needed for calculations (like arithmetic).
You must use the type converter functions (int() or float()) immediately after receiving the input:
Get Integer
age = int(input("Enter age: "))
#Converts the string (e.g., "25") into the integer 25.
Get a Decimal Number
temp = float(input("Temp: "))
#Converts the string (e.g., "98.6") into the float 98.6.
Composition
Composition is a core programming concept where simple building blocks such as variables,
expressions, function calls, and statements are combined, often by nesting, to create larger, more
complex units of code.
[Link] and Purpose
Combining Blocks: Composition allows programmers to combine several small logical steps
into fewer, more compact lines of code.
Efficiency: It leverages the return value of one function or expression as the input or argument
for another function.
Analogy: It’s like assembling a complex machine from small, ready-made parts.
2. Example: Calculating Circle Area (Area= pi R^2)
This common task illustrates how input, conversion, and calculation can be composed:
Required Steps:
Get input (string) from the user using input().
Convert the string to a number using float().
Calculate the area using the expression 3.14159 * r**2.
Display the result using print().
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
A. Fragmented Approach (Max Clarity)
This approach separates every step, which is best for debugging and beginner code:
response = input("What is your radius? ")
r = float(response)
area = 3.14159 * r**2
print("The area is ", area)
B. Composed Approach (Nested Functions)
This approach nests the input() call inside the float() call, and the expression is moved directly
into the print() statement:
r = float( input("What is your radius? ") )
print("The area is ", 3.14159 * r**2)
C. Highly Composed Approach (Single Statement)
The entire logic is executed in a single, complex statement:
print("The area is ", 3.14159 * float(input("What is your radius?"))**2)
3. Best Practice: Prioritizing Readability
Clarity vs. Compactness: While composition can create highly compact code (like the
single-line example above), this compactness often sacrifices human readability.
The Modulus Operator (%)
The modulus operator (%) is a powerful arithmetic tool in Python used to find the remainder of
a division operation involving integers.
1. Function and Syntax
Function: The modulus operator works on integers (and integer expressions) and returns the
remainder when the first operand is divided by the second operand.
Token: The symbol used in Python is the percent sign (%).
Syntax: The syntax is the same as other operators (e.g., x % y).
Precedence: The modulus operator has the same precedence as the multiplication (*) and
division (/, //) operators.
Example:
>>> 7 // 3 # Integer division (quotient)
2
>>> 7 % 3 # Modulus (remainder)
1
This shows that 7 divided by 3 gives a quotient of 2 with a remainder of 1.
2. Practical Uses of the Modulus Operator
The modulus operator is surprisingly versatile and used widely in programming logic:
Checking Divisibility:
If the result of x % y is zero (0), it means that x is perfectly divisible by y.
Example:
10 % 5 is 0, meaning 10 is divisible by 5.
Extracting Digits:
You can extract the right-most digit(s) of an integer in base 10.
x % 10 yields the right-most digit of x. (e.g., 123%10=3).
x % 100 yields the last two digits of x. (e.g., 4567%100=67).
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT
1BPLC105B Python Programming
Unit Conversions (Time/Distance):
It is essential for breaking down a total quantity into larger units and the remaining
smaller units (e.g., converting total seconds into hours, minutes, and seconds).
3. Conversion Example (Seconds to H:M:S)
This example illustrates how modulus works alongside floor division (//) for sequential unit conversion:
Input: Get the total number of seconds.
total_secs = int(input("How many seconds, in total?"))
Calculate Hours: Use floor division to find the whole number of hours.
hours = total_secs // 3600 (Since 1 hour =3600 seconds).
Find Remaining Seconds: Use modulus to find the seconds left over after the hours are accounted for.
secs_still_remaining = total_secs % 3600
Calculate Minutes: Use floor division on the remaining seconds to find the whole number of minutes.
minutes = secs_still_remaining // 60
Final Remaining Seconds: Use modulus again to find the final seconds left over after the minutes are
accounted for.
secs_finally_remaining = secs_still_remaining % 60
Note:This step-by-step process efficiently converts a single integer (total seconds) into three
meaningful integer components (hours, minutes, seconds).
Code:
# 1. Get the total time from the user as a whole number.
total = int(input("Enter total seconds: "))
# --- 2. Calculate Hours and the Leftover Seconds ---
# Find the whole number of hours (using Floor Division //)
# 3600 seconds in 1 hour
h = total // 3600
# Find the seconds remaining after the hours are counted (using Modulus %)
left_s = total % 3600
# --- 3. Calculate Minutes and the Final Leftover Seconds ---
# Find the whole number of minutes from the remaining seconds
# 60 seconds in 1 minute
m = left_s // 60
# Find the final seconds left over after the minutes are counted
final_s = left_s % 60
# --- 4. Show the Result ---
print("Converted Time:")
print("Hours:", h)
print("Minutes:", m)
print("Seconds:", final_s)
Prepared by Mrs. Ashwini S, Dept of CSE, RLJIT