Basics of Python Programming
Basics of Python Programming
Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991.
Python is widely used in:
• Web development Automation
• Data science • Software development
• Machine learning
Python Pluses / Features of Python
• Object Oriented Language • Extensive Standard Library
• Simple and Easy to Learn • Its Completeness in library –
• Expressive Language “Batteries included”
• Interpreted Language • Cross Platform Language
• Dynamically Typed • Free and Open Source
•
How easy and expressive python is, can be understood by this
example- If we want to display a simple Hello World message on screen
using python, we have to execute the following command
print(“HELLO WORLD!!”)
isn’t this easy and expressive.
Execution Modes in Python
There are two modes to work on python:
◦ Interactive (also called Immediate Mode)
◦ Script Mode
Script Mode is used when we want to save all the commands in the form of program file
and want to see all output lines together rather than sandwiched between successive
commands.
Steps for writing in Script mode –
1. Open Python IDLE
6. Final Output
PYTHON TOKENS
◾ Token is the smallest individual unit of program
◾ Also called as Lexical units or Lexical elements
◾ Types of tokens:
▪ Keyword
▪ Identifier
▪ Literal
▪ Operator
▪ Punctuator
1.) Keywords – These are reserve words which has special meaning to the compiler or
interpreter.
Python keywords:
FALSE None True and as break class continue def pass
for from global if import in is not or raise
del elif else except finally with return try while
2.) Identifiers – These are names given to the different parts of the program like variables,
objects, classes, functions, lists, dictionaries etc.
Identifier forming rules :
▪ Valid combination of letters and digits.
▪ First character can be a letter(A-Z ,a-z) or underscore( ) but not a digit(0-9).
▪ Upper case and lowercase alphabets are treated differently.
▪ Unlimited in length.
▪ Must not be a keyword eg break, print
▪ Cannot contain any special character except _ (underscore)
Types of literals
• String Literals → Text enclosed in single ('),double (") or triple(''') quotes.
Example -
name = "Alice"
greeting = 'Hello'
message = ''' new things
new ways'''
• Anything in quotation marks is a string
• Arithmetic operator used +, *
• As it display
• Python uses 3 types of quotation marks
• Single quotes ‘ ‘ eg ‘a’ ‘apple’, ‘computer science’
• Double quotes eg “a”, “apple”, “Computer science”
• Triple quotes ‘’’ ‘’’ or “”” “””
Error Correct
print(‘he said, ‘hello’ ’) print(‘he said,”hello”’)
print(“India won “1 Gold Medal” ”) print(“India won ‘1 Gold Medal’”)
Use of \ in Python
To continue a line or command
print(“hello \
friends”)
This is single line
hello friends
print(‘’’hello \
friends’’’)
Even triple quotes are used but use \ it will be printed in one line only
Error
print(“hello
friends”)
But in Triple quotes \ for same line display or multiple lines if you want to display in multiple lines
Triple quotes in place of single quotes and double quotes but vice versa is not possible
Escape Sequence - An escape sequence in Python is a combination of characters that starts with a
backslash (\) and is used to represent special characters in a string that cannot be typed directly or
would otherwise be interpreted differently by the compiler.
Why Use Escape Sequences?
• They're used to:
• Insert characters like newlines, tabs, quotes, etc.
• Include characters that are difficult or impossible to type directly.
• Format output in specific ways.
Python Escape Sequences Table
Escape
Description Example Output
Sequence
\\ Backslash print("a\\b") a\b
\' Single quote print('It\'s OK') It's OK
\" Double quote print("He said \"Hi\"") He said "Hi"
Hello
\n Newline print("Hello\nWorld")
World
\t Horizontal tab print("Name\tAge") Name Age
\r Carriage return print("123\rABC") ABC
\b Backspace print("Hello\b") Hell
Line1 (form feed)
\f Form feed print("Line1\fLine2")
Line2
Line1 (vertical space)
\v Vertical tab print("Line1\vLine2")
Line2
\a Bell (system alert) print("\a") Bell sound (if enabled)
abcdef (null char
\0 Null character print("abc\0def")
hidden)
Octal value (e.g., \141 =
\ooo print("\141") a
a)
Hexadecimal (e.g., \x61
\xhh print("\x61") a
= a)
Unicode character by print("\N{GREEK CAPITAL LETTER
\N{name} Δ
name DELTA}")
\uXXXX Unicode (16-bit hex) print("\u03A9") Ω
Escape
Description Example Output
Sequence
\UXXXXXXXX Unicode (32-bit hex) print("\U0001F600")
Notes
• Escape sequences are used to represent characters that can't be typed directly or have special
meaning (like newline).
• In raw strings, escape sequences are not interpreted:
Remember
- Sign(+ or -) are allowed
- Commas are not allowed
- Leading 0s are not allowed
- can use underscores (_) for readability:
big_number = 1_000_000
print(big_number) # Output: 1000000
Python supports integers in several number systems:
Type Format Example Value (Decimal)
Decimal Base 10 (0–9) num = 100 100
Binary Base 2 (0 or 1), prefixed with 0b or 0B num = 0b1101 13
Octal Base 8 (0–7), prefixed with 0o or 0O num = 0o12 10
Hexadecimal Base 16 (0–9, A–F), prefixed with 0x or 0X num = 0xA 10
Example
Statement output reason
# Scientific notation (e or E)
d = 1.2e3
print(d) # Output: 1200.0
e = 2.5E-2
print(e) # Output: 0.025
Notes
• Floats are of type float in Python.
• Scientific notation is useful for very large or very small numbers.
• All float literals are stored in double precision (64-bit) internally.
Quick Check
print(type(3.0)) # <class 'float'>
print(type(2e2)) # <class 'float'>
• Complex – a+bj
Example : 3+5j, -2j
• Boolean Literals → True(1), False(0)
• Special Literal → None - Represents the absence of a value or null.
Example : data = None
• Literal Collections → Literal collections are ways to store multiple items in a single
variable using built-in Python data structures. They include lists, tuples, dictionaries,
and sets.
4.) Operators
Operators in Python are special symbols that let Python do something with values (called
operand).
Each operator type serves a different purpose.
Some commonly used types of Python Operators:
• Arithmetic Operators – Perform basic math
+ - * / % // **
(Example: a + b, a * b)
• Relational (Comparison) Operators – Compare values
== != > < >= <=
(Example: a > b, a == b)
• Logical Operators – Combine conditions
and or not
(Example: a > 5 and b < 10)
• Assignment Operators – Assign values
= += -= *= /= etc.
(Example: x += 1 is same as x = x + 1)
(Topic Operator explained later)
Punctuators - Punctuators are the symbols that are used in programming languages to
organize programming sentence structures, and indicate the rhythm and emphasis of
expressions, statements and program structure.
Most common punctuators of Python programming Language are:
‘ “ \ () [] {} @ , : . =
Variables - A variable in a program is uniquely identified by a name (identifier). Variable
in Python refers to an object — an item or element that is stored in the memory. Value of
a variable can be used and processed during program run.
Example - num=89, marks = 35
Name = ‘Joseph’, c=2+3i
Dynamic typing - A variable pointing to a value of certain type, can be made to a point to a
value/object of different type. This is called DYNAMIC TYPING.
Example
x=25
print(x)
x= ‘Hello’ # same variable x is now string
print(x)
Variable in Python
Named labels in RAM whose value can be modified during the
execution of the program and it can be processed within the
program. They are not available outside of the program file, can
be used in shell once program is executed
Declare a variable
variablename(identifier)=value
Eg
a=10
s=”Computer”
f=9.8
• To declare a numeric variable assign numeric literal
• To declare a string variable assign string literal
Syntax:
variable=value
Eg
x=12
name=”Ajay”
marks=90.2
x=10
x=12
Now, value of x 12 it is no more 10
x=12*2
Now, the value x will be 24
Each variable has a data type, their No data type and variable does not need a
primitive data type datatype
What is an lvalue?
• lvalue (Left Value) refers to a location that can appear on the left side of an assignment.
• In Python, lvalues must be variables or data structures that can store a value.
Valid lvalue:
x = 10
Here, x is an lvalue – a variable name that refers to a memory location where the value 10 is stored.
Invalid lvalue:
10 = x # SyntaxError
You cannot assign a value to a literal or expression.
What is an rvalue?
• rvalue (Right Value) is the data or value that you assign to an lvalue.
Valid rvalue:
x=2+3
Here, 2 + 3 is an rvalue – it evaluates to 5, which gets assigned to x.
Summary Table
Expression lvalue? rvalue? Notes
x=5 Yes Yes Memory address of x is lvalue, 5 is rvalue
5=x No No Invalid
x=y+1 Yes Yes Memory address of x is lvalue, y + 1 is rvalue
x + 2 = 10 No No Invalid, x + 2 is not assignable
Visual Diagram
Assignment Statement
lvalue = rvalue
------------- ----------------
Variable Name Expression / Value
(x) (5, x + 1, func())
x
(rvalue)
a=10
a=10*5
Error
In Python
9 10 11 12 13 14
For every data type there is a class in Python therefore we call a variable is called Object of the
class
integer <class ‘int’>
Eg
x=10
Python does not fixes data type with a variable name therefore data of different type will
change the data type of the variable also
type() function return the class to which the obejct belongs
print(x) Rvalue of x 10
Multiple variable when multiple value is assigned to Python solves right side then
assigns to left
Easy swapping
Exchanging values of variable
a,b=b,a
a← b, b ← a
• Substitution and solve then assign
a=2
b=3
a,b=b*2,a=3
Substitute values of a and b
=> a,b=3*2,2*3
Now solve right side
=> a,b=6,6
Now assign value to a and b
Therefore a=6 , b=6
a,b,c=2,3,4
Here a=2,b=3,c=4
b,c,a=a*3,b*5,c*2
= 6,15,8
Now assign
b=6, c=15, a=8
a,b=2,3
a,b,b,a=a*2,b*3,b*4,a*3
=4,9,12,6
a=4
b=9
b=12 #changes the previous value
a=6
Finally a=6,b=12
x=2
y=x/2
x=”hello”
y=x/2
Error str cannot be divided
a,b=2,3
a,b=a*2,b*3
# a will become 4 b will ne 9
b,a=b*4,a*3
#b=36,a=12
After one statement Python uses the latest value of the variable
How to display data in Python????
• Use print() to print the data
print()
• Use literal be numeric or non numeric
print(“this is a string”)
print(literal/variable)
• Between 2 literals or 2 variable use comma
print(a,b)
Python will give 3-4 spaces in between them
• If Operator is used then solve and displays the answer
• One print statement prints on one line
print()
Prints a blank line
• To print a blank give
print() → prints a blank line
• Use escape sequence characters in Python
Eg
print(“hello\nfriends”)
Output
hello
friends
• sep :- new separator between 2 variables, literals, by default sep is spaces (3-
4), but if mentioned then spaces will be replaced by the value is “”
a=12
b=13
print(a,b,sep=”#”)
Output
12#13
print(a,b)
Output
12 13
print(“apple”,”banana”,”mango”,sep=”,”)
apple,banana,mango
print(“apple”,”banana”,”mango”,sep=”KKK”)
appleKKKbananaKKKmango
But this will change the line
• end this will not change the line but it will print that between 2 lines, by
default in between 2 print() statement there is \n, if given using end Python
will not change the line but on same line between 2 lines print the string
print(a,end=”#”) → this will not change the line
print(b)
Output
12#13
print(a)
print(b)
Output
12
13
• Remember sep by default \t (4 spaces) and end by default is \n (new line
character)
• Both can be used together
a,b,c,d=12,13,14,15
print(a,b,sep=”#”,end=”!”)
print(c,d,sep=”&”,end=”%”)
print(“over”)
• Can be give
input() → empty ()
input(“message”)
Eg
input(“enter data ”)
print(“enter data”)
input()
Enter data
= → input here
input()
Enter data =
Eg
variable=int(input(“enter data:”))
Eg
This will accept only integer data This will take any type of data
Separate function for different data types One function for all the data type
int(), float(), str(),
Restrict user to input the correct form of data User to input any type of data
COMMENTS - Comments are the lines or statements that are ignored by the compiler/
interpreter.
These are additional readable information to clarify the source code.
It enhances the readability of the program
It is of two types –
Single Line comment
This type of comment begins with a symbol # (Pound or hash) character and end with
end of physical line.
Multiline Comment or Block Comment can be given in two ways:
1. Add a # symbol in the beginning of every physical line part of multi-line comments.
Example
# Multiline comments are useful for detailed
# additional information related to program
#It helps clarify certain important things.
BAREBONES OF PYTHON
• EXPRESSION - An expression is any legal combination of symbols and values that
represents a value.
Example
◾ (18/2) +15 – Arithmetic Expression
◾ (12>34) - Relational Expression
◾ a and b not b – Logical Expression
◾ ‘and’ + ‘else’ – String Expression
◾ STATEMENT – A Statement is a programming instruction that does something ie
some action take place.
Example
print(‘hello’
) print(a+5)
BLOCKS AND INDENTATION - A group of statements which are part of another statement or a
function are called block or code-block or suite in Python
Example
◾ Comment
◾ Functions
BOOLEAN DATA TYPE - Boolean values are the two constant objects False and True.
TYPES OF OPERATORS
Python language supports the following types of operators:
⚫ Arithmetic Operators
⚫ Comparison (Relational) Operators
⚫ Assignment Operators
⚫ Logical Operators
⚫ Membership Operators
⚫ Identity Operators
Logical Operators - Logical operators perform Logical AND, Logical OR and Logical NOT
operations. It also returns either True or False.
OPERATOR DESCRIPTION Example
and Logical AND: True if both the operands are true x and y
otherwise False
or Logical OR: True if either of the operands is true x or y
otherwise False
not Logical NOT: True if operand is False and vice versa not x
Membership Operators - Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples. This also results in True or False. There are two membership
operators as explained below –
PRECEDENCE OF OPERATORS
Evaluation of the expression is based on precedence of operators. When an expression
contains different kinds of operators, precedence determines which operator should be
applied first. Higher precedence operator is evaluated before the lower precedence
operator
Sr.No. Operator Description
1 ** 2**3 Exponentiation (raise to the power)
2 ~+- Complement, unary plus and minus (method names
for the last two are +@ and -@)
3 * / % // Multiply, divide, modulo and floor division
4 +- Addition and subtraction
5 >> << Right and left bitwise shift
6 & Bitwise 'AND'
7 ^ | Bitwise exclusive `OR' and regular `OR'
8 <= < > >= Comparison operators
9 <> == != Equality operators
10 = %= /= //= -= += *= **= Assignment operators
11 is, is not Identity operators
12 in,not in Membership operators
13 not, or, and Logical operators
Example : 2*3**2 this will result in 18 as exponent has higher precedence than multiply.
TYPE CONVERSION
Type conversion means we can change the data type of a variable in Python from one
type to another. It is categorised into two types:
1. Implicit Type Conversion (Automatic)
Python automatically converts data type during operations when safe.
a = 5 # int
b = 2.0 # float
c = a + b # Result: 7.0 (float)
x = "123"
y = int(x) # Now y is an integer 123
More Examples:
int(3.3) produces 3 str(3.3) produces “3.3”
float(3) produces 3.0 float(“3.5”) produces 3.5
Example:
print("Hello", "World", "!!!!", sep="-")
output: Hello-World-!!!!
x*y =z
Z=X*Y
An expression cannot be on left side of assignment statement.
a>=q if :
If a>=q:
2. LOGICAL ERROR –
• Its executes the program successfully but you will not get desired output
• For example – An incorrectly implemented algorithm or use of variable before
initialization, wrong end of loop etc.
• It is often hardest to prevent and locate.
Example - To Multiply 3 nos.
Q Write a program in Python to accept 2 variables from the user and find their sum.
Solution:
1 input - 2 variable
2 find sum by adding them
3. Find sum by adding them
Algorithms
Step 1: start
Step 2: input a
Step 3: input b
Step 4: sum=a+b
Step 5: print(sum)
Step 6:stop
Program
sum=a+b
print("sum=",sum)
Q what is the difference between
Ans
print(“sum”) print(sum)
“Sum” is a string literal so will be Python will consider sum as a variable and display
printed as it is the data in sum variable( displays rvalue of the
variable)
Q Write a program in Python to accept 3 numbers, find their sum and product.
sum=a+b+c
product=a*b*c
print("Sum of ",a,",",b,",",c,"=",sum)
print("product=",product)
print("Sum of ",a,",",b,",",c,"=",sum)
• print(a,”+”,b,”+”,c,”=”,sum)
• print(“SUM=”,sum)
• print(“Sum=”,a+b+c)
• Message must : -sum of the 3 number, message that indicates that it is sum
Ans
• Eg
• print(sum) --> 25
• print(“sum=”,sum) → sum=25
• Meaningful messages
1. Arithmetic Expressions
a = 10 + 5 # Addition
b = 10 - 2 # Subtraction
c=4*3 # Multiplication
d=8/2 # Division
e=7%3 # Modulus
f = 2 ** 3 # Exponentiation
g = 9 // 2 # Floor Division
x = 10
y=5
print(x == y) # False
print(x != y) # True
3. Logical Expressions
x=5
4. Bitwise Expressions
b=5|3 # Bitwise OR
d = ~5 # Bitwise NOT
if (n := len("hello")) > 3:
print(n) # Output: 5
6. Identity Expressions
a = [1, 2]
b=a
print(a is b) # True
7. Membership Expressions
8. String Expressions
repeat = "Ha" * 3
What Happens When You Use and / or with Constants?
In Python, and and or return the actual operand values, not necessarily True or False.
x and y
Examples:
x or y
Examples:
• 0, 0.0, 0j
• None
• False
• [] (empty list)
• {} (empty dict)
Summary Table
0 and 5 0 0 is falsy
Tip to Remember
• and: Returns the first falsy value, or the last if all are truthy.
• or: Returns the first truthy value, or the last if all are false.
QUESTION BANK
MULTIPLE CHOICE QUESTIONS
1. What is the first phase in the Python project cycle?
a) Design
b) Development
c) Requirement Analysis
d) Testing
2. What activity is commonly done in both the testing and maintenance phases?
a) Writing user stories
b) Fixing bugs
c) Creating diagrams
d) Writing documentation
3. Which of the following best defines an algorithm?
a) A diagram showing steps
b) A step-by-step procedure for solving a problem
c) A computer program
d) A software model
4. What is a flowchart used for?
a) Drawing architectural models
b) Writing code
c) Visually representing algorithms
d) Designing databases
5. In a flowchart, which symbol is used to represent a decision?
a) Rectangle b) Parallelogram c) Oval d) Diamond
6. Who developed Python?
a) Dennis Ritchie b) Guido van Rossum c) Bjarne Stroustrup d) James Gosling
7. Which of the following is used to output data in Python?
a) echo() b) write() c) print() d) show()
8. What is the correct way to create a variable in Python?
a) var x = 10 b) int x = 10 c) x := 10 d) x = 10
9. What data type is the result of: type("123")?
a) int b) str c) float d) bool
10. Which of the following is NOT a Python data type?
a) list b) tuple c) array d) dictionary
11. Python is: a) Compiled b) Interpreted c) Both d) None
12. Which of these is not a core data type?
a) List b) Dictionary c)Tuple d) Class
13. What is the output of this code? x =
None
print(type(x))
a) <class 'null'> b) <class 'empty'> c) <class 'NoneType'> d) <class 'str'>
14. Which of the following is a mutable data type?
a) list b) tuple c) str d) int
15. What will be the result of 3 + 2 * 2?
a) 10 b) 7 c) 9 d) 8
16 What is the result of bool (0) in Python?
a) True b) False c) 0 d) Error
17. What type of error is raised by the following code?
x = 10
print(x / 0)
a) NameError b) TypeError c) ValueError d) ZeroDivisionError
18. Which of the following is a valid Python variable name?
a) 1variable b) @name c) _value d) class
19. What will this code output? a =
[1, 2, 3]
print(a[3])
a) 3 b) IndexError c) None d) 4
20. Which of the following is NOT a keyword in Python?
a) None b) pass c) eval d) finally
ANSWERS
1 2 3 4 5 6 7 8 9 10
c b b c d b c d b c
11 12 13 14 15 16 17 18 19 20
b d c a b b d c b c
ASSERTION AND REASONING QUESTIONS
In the following questions, a statement of Assertion(A) is followed by a statement of Reason (R).
Make the correct choice as:
A. Both A and R are true, and R is the correct explanation of A.
B. Both A and R are true, but R is not the correct explanation of A.
C. A is true, but R is false.
D. A is false, but R is true.
1. Assertion (A): int and float are both immutable data types.
Reason (R): Reassigning a number to a variable changes the data inside the same memory
location.
2. Assertion (A): The None keyword in Python represents the absence of a value.
Reason (R): None can be used in conditional statements and evaluates to False.
3. Assertion (A): Lists in Python are mutable.
Reason (R): Lists do not support indexing and slicing.
4. Assertion (A): Division by zero in Python raises an error.
Reason (R): The interpreter cannot represent infinity.
5. Assertion (A): The expression 4 + 5 * 2 evaluates to 18.
Reason (R): In Python, operators are evaluated from left to right without any precedence.
6. Assertion (A): is operator checks if two variables refer the same object in memory.
Reason (R): The == operator compares values, not identities.
7. Assertion (A): x += 3 is a shorthand for x = x + 3.
Reason (R): += is a compound assignment operator that modifies the variable in- place for
immutable types.
8. Assertion (A): The expression 10 // 3 results in 3.
Reason (R): // operator performs floor division in Python.
ANSWERS
1. Answer: C
Yes, they are immutable, but reassigning creates a new object, not changes the value
in-place.
2. Answer: A
3. Answer: C
Lists are mutable, but they do support indexing and slicing.
4. Answer: B
Python raises a ZeroDivisionError for mathematical correctness, not because it can't
represent infinity (it can, e.g., via float('inf')).
5. Answer: C
Correct result is 14. Operator precedence means * is evaluated before +.
6. Answer: A
7. Answer: C
x += 3 does not modify in-place if x is immutable (like an int) — it creates a new
object.
8. Answer: A
SHORT ANSWER QUESTIONS
1. Explain Problem Solving and give its steps?
2. Write an algorithm to find the largest of three numbers.
3. Draw a flowchart to calculate area of circle
4. Differentiate between Interactive mode and Script mode?
5. Differentiate between Keyword and Identifiers?
6. What are Literals in Python? Identify the following type of literals-
a) x=’Rehan’
b) y=3+6j
c) t= ‘True’
d) p=3.15
7. What is the purpose of comments in Python? In how many types we can give
comments in Python explain it.
8. Differentiate between mutable and immutable data types?
9. Differentiate between List and Dictionary with example?
10. When Tuple is preferred over List?
11. What is type casting? Explain with example.
12. Differentiate between Syntax Error and Run time error?
ANSWERS
1 Problem Solving is the process of identifying a problem, analyzing it, and finding an
effective solution, often by writing a program.
It is a key skill in programming and computational thinking.
Steps of Problem Solving
1. Analysing the problem,
2. Developing an algorithm,
3. Coding,
4. Testing, and debugging
2 Step 1: Start
Step 2: Input three numbers: A, B, and C Step
3: Check If A > B and A > C, then print A is the
largest
Step 4: Else if B > C, then Print B is
the largest
Step 5: Else
Print C is the largest
Step 6: Display the largest number
Step 7: Stop
3
4 1. Interactive Mode does not save the command entered by you in the form of a
program but in Script mode program can be saved for later use.
2. In Interactive Mode the output is sandwiched between in the command lines while
in Script Mode the output of a program is displayed all together.
3. In Interactive Mode, the output can be displayed as well as can be done using print
function.
But in Script mode, print() command is preferably used to print results.
5 Keywords are reserve words which has special meaning to the compiler or interpreter.
Python keywords:
False, None, True, and , as, break etc
Identifiers are names given to the different parts of the program like variables, objects,
classes, functions, lists, dictionaries etc.
Example - age, student_name, totalSum, calculate_area
6 Literals are fixed or constant values values used directly in code. They represent data
you assign to variables or use in expressions
a) x=’Rehan’ - String Literal
b) y=3+6j – Complex Literal
c) t= ‘True’ – String Literal
d) p=3.15 - Float literal
7 Comments are the lines or statements that are ignored by the compiler/ interpreter.
These are additional readable information to clarify the source code. It
enhances the readability of the program
It is of two types –
Single Line comment - This type of comment begin with a symbol # (Pound or hash
)character and end with end of physical line.
Multiline Comment or Block Comment can be given in two ways:
1. Add a # symbol in the beginning of every physical line part of multi-line
comments.
2. Type comment as a triple- quoted multi-line string
8 Immutable data type - Cannot change once created (any change creates a new object).
These data types cannot be changed after they are created.
Type Example
int x = 10
float pi = 3.14
bool flag = True
str Name="Alice"
tuple colors = ("red",”green”,”blue”)
Mutable Data types Can change after creation (modify content without changing
identity).
Type Example
list nums = [1, 2, 3]
dict info = {"name": "Bob",’Gender’:’Male’,’Age’:23}
9 Feature List Dictionary
Structure Ordered sequence Unordered key-value pairs
Access By index (e.g., list[0]) By key (e.g., dict["key"])
Syntax Square brackets [] Curly braces {}
Key-Value No (only values) Yes
Example ["a", "b", "c"] {"a": 1, "b": 2}
10 Tuples are immutable, meaning their values cannot be changed after creation.
This makes them more secure and reliable when storing constant data.
11 Type casting is the process of converting one data type into another manually. Python
supports two types of casting:
2 Question:
An e-commerce platform calculates discounts based on the purchase amount. If the amount is
more than ₹5000, a 10% discount applies.
Write a Python program to take an amount as input and display the final price after applying
the discount if applicable.
3 Question:
You are developing a health tracking app. Each user logs their name, age, weight (in kg),
height(in m) and whether they exercised today (Yes/No).
a.) Identify appropriate data types for each of these attributes.
b.) Write a program to calculate BMI(weight/height2) according to values entered.
ANSWERS
1 Competency Focus: Declare and use variables for storing and updating data. a.)
account_holder = 'Neha' balance =
10000
last_transaction = 0
b.)
# Deposit
last_transaction = 1500 balance +=
last_transaction # Withdrawal
last_transaction = -800 balance +=
last_transaction
print ('Updated Balance:', balance)
2 Competency Focus: Use arithmetic, comparison, and logical operators appropriately.
amount = float (input ("Enter purchase amount: ")) if amount >
5000:
discount = amount * 0.10 else:
discount = 0
final_price = amount - discount print ("Final
Price:", final_price)