0% found this document useful (0 votes)
9 views45 pages

Basics of Python Programming

Uploaded by

aditipanchal647
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)
9 views45 pages

Basics of Python Programming

Uploaded by

aditipanchal647
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

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

Working in Interactive Mode


Interactive mode means you type the command – one command at a time and
the Python executes the given command there and then and gives you the
output
In Interactive mode, the commands are given in front of Python command
prompt >>> (Angular bracket).
Example
>>> 12+ 13
25
>>> print(‘Hello’)
Hello
Interactive mode is useful for testing code. You type commands one by one,
and Python executes each command immediately, giving the result or error
instantly.
Working in 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

2. From File Menu Choose – New File

3. Type the codes on File named ‘Untitled’


4. Click on Save from file menu
You will have a python file like this

5. Run/Execute the python file

6. Final Output

Interactive Mode Vs Script Mode


⚫ 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.
⚫ 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.
⚫ 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.
PYTHON CHARACTER SET
◾ Character set is a set of valid characters that a language can recognize
◾ It can be any letter, digit or any other special character. #, . ; &* () _/+=‘’ “” !
◾ It supports Unicode encoding standard
◾ ASCII – American Standard Code for Information Interchange
◾ Universal coding
◾ Letters from A-Z, a-z
◾ Digits 0-9
◾ Special Characters → space, +, - * / ** \ ( ) [ ] {} // = != == < > . ; : % ! & # <= >=
@ _(underscore)
◾ White spaces → blank space, tabs (↹) , carriage return(↵), new line, form feed
◾ Other Characters → Python can process all ASCII and Unicode characters as part of
data or literals.

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

Q How to find a word's keyword without compiling or interpreting it?


Ans: - The color specified by the editor for keywords
Q what is an editor?
Ans:- Editor allows you to move up,down, right,left, write a program, modify, execute and see the
output, save. Different languages a give different color to the token

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)

Valid Identifiers: Myfile, MYFILE, DATE_9, Z2TOZ9, _CHK, FILE13


Invalid Identifiers: DATA-REC, break, my.File, 19ct, First Name
3.) Literals - Literals are fixed or constant values used directly in code. They represent
data you assign to variables or use in expressions.

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 “”” “””

Single quotes or double quotes are single line


“ hello ‘you “

Quotes within quotes we use different types of quotes


Instruction Output
print(“he said,’hello how are you?’ ”) he said,’hello how are you?’
print(‘I said, “what an amazing day!” ‘) I said, “what an amazing day!”
print(“Father’s name is Mr Kapoor”) Father’s name is Mr Kapoor

Error Correct
print(‘he said, ‘hello’ ’) print(‘he said,”hello”’)
print(“India won “1 Gold Medal” ”) print(“India won ‘1 Gold Medal’”)

Triple quotes (“”” “””) or (‘’’ ‘’’) Output


• Multiline output This is a file
print(“”” this is a file This is a new file
This is a new file This is my file
This is my file This is a Python file
This is a Python file”””)

Character are of 2 types


1. Graphical - will be displayed on the screen
Eg A, %, *, special character
2. Non graphical - used for formatting
• Begin with \
• Instead of the character there will change in output
• Such characters are called escape sequence characters
• Only \ in python for typing one statement in multiple lines

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:

• Numeric Literals → Represent numbers of different types:


Integer- Similar as integers in Maths ex. t=+7, y =-98
Without decimal points
Can have + or – sign (by default +)
Commas cannot be used
Example : 12, -17, 100000, 1220000 n1=-1234, n2 = +34
12 and “12”
12 is a numeric literal, can do any arithmetic operation, “12” is string or character literal, can be (+)
concatenation,(*)repetition

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

print(56) 56 No conversion as it in decimal form


No prefix not even 0

print(0o56) 36 Conversion as it is octal form


5*6+6*1 Octal number begins with 0o
=36

print(0x56) 96 Conversion as it is hexa-decimal form


5*16+6*1 hexa-decimal number begins with 0x
=96

Float - Numbers with decimal points, real numbers


Can have + or – sign
Example : 0.3 , 56.8 , -34.8, +90.1
A float can be written in two main ways:
Type Example Value
Standard decimal num = 3.14 3.14
With exponent (scientific notation) num = 1.5e2 150.0 (1.5 × 10²)
Examples
# Basic float
a = 10.5
print(a) # Output: 10.5

# Float with no digits before decimal


b = .25
print(b) # Output: 0.25

# Float with no digits after decimal


c = 5.
print(c) # Output: 5.0

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

Syntax Example Ordered Mutable Duplicates Allowed


Type
List Literal ["a", "b", "c"] Yes Yes Yes
Tuple Literal ("x", "y", "z") Yes No Yes
Dictionary Literal {"key": "value"} No Yes Keys: No, Values: Yes
Set Literal {1, 2, 3} No Yes No

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

How memory is assigned to a Python variable


• Named label whose value can be changed during the
process
• Type given to variable is called Data Type
• In Python a variable is an Object
• Python has no Datatype
• What is a Data type?
• Type in which variable is declared
• What type of data can be stored in a variable
• How much memory is allocated to the variable
• Range of data that can be stored in a variable
• Declare variable by a assigning a value to the variable
• Declare a variable
• Assign value
• But in Python we simply assign the value to a variable
and it is declared, memory is allocated

Syntax:
variable=value
Eg
x=12
name=”Ajay”
marks=90.2

Declare and define - occupy space in memory


Initialize - first value of the variable in the declaration
statement
Assign - giving a new value or expression( calculated) to the
variable, for assigning we use assignment operator(=)

x=10
x=12
Now, value of x 12 it is no more 10
x=12*2
Now, the value x will be 24

In Python we assign to declare and define


If you need a variable in Python just assign a value and it
will declared or define. First value assigned to variable,
memory will be allocated to variable, next value assign to
the variable data will change

Difference variable other programming languages and Python

Other Programming Python

Each variable has a data type, their No data type and variable does not need a
primitive data type datatype

size of variable if fixed Size is not fixed

Range of data is fixed No range - big data

First declare then assign Assign the value to declare


Concept of L-value and R-value
L-value (Left Value) - A L-value refers to a location that can appear on the left side of an
assignment.
It must be a variable or an object that can store a value.
Example:
x = 10
# Here, `x` is a L-value because it refers to a memory location where 10 is stored.
R-value (Right Value)- A R-value is any expression or value that can appear on the right
side of an assignment.
It represents data (a value), not a location.
Example:
x = 10
# Here, `10` is a R-value — it's the value being assigned to x.

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.

• It must be something that produces a value.

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=5 10000 {lvalue}


5

x
(rvalue)

Important Notes in Python


1. Only assignable entities can be lvalues (e.g., variables, list elements, object
attributes):
X=54

2. You cannot assign to expressions:


x+1=5 # SyntaxError
3. Python has no pointers, but you still use variable names (references) as lvalues.

Extra: lvalues in Multiple Assignment


Python supports multiple assignment:
a, b = 1, 2
• a and b are both lvalues
• 1 and 2 are rvalues
Lvalue- changes with rvalue
Variable = value/ expression/variable

a=10

a=10*5

a=b #b is predefined, a will become label of same memory as b

Value will be allotted to a

← goes from right to left LHS← RHS

Data flows from right to left

Error

A # must give some value

10=a #constant cannot be equal to a variable

In Python

Some data in Python is preloaded

20241 20242 20243 20244 20245 20246

9 10 11 12 13 14

a=10 a will be a label of memory 20242

a=12 Now, a will become label of memory 20244

b=12 Now, 20244 has 2 labels a and b

For every data type there is a class in Python therefore we call a variable is called Object of the
class
integer <class ‘int’>

float <class ‘float’>

Complex number <class ‘complex’>

boolean <class ‘bool’>

string <class ‘str’>

list <class ‘list’>

tuple <class ‘tuple’>

Dictionary <class ‘dict’>

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

prind(id(x)) Lvalue of x 1122345

print(type(x)) Class to which the object belongs <class ‘int’>

Advantage of the method:-


1. Dynamic typing
• Variable has no data type
• Value assigned to the variable, variable becomes label of that value
• type() it show the type according to value assigned to the variable
a=10
print(type(a))
<class ‘int’>
• When assign another value the label will shift to that value
• No change in that memory, a new memory will be given, id() displays memory
address of the variable
a=10
print(id(a))
20242
a=12
print(id(a))
20244
• New value, new data type can be given
a=10
print(type(a))
<class ‘int’>
a=”hello”
print(type(a))
<class ‘str’>

Method to declare a variable


• Single value
x=10
f=8.7
• Multiple variables and multiple value
a,b=1,2
Here, a will get 1 and b will get 2
a,b,c=1,”hello”,4.3
Here,
a=1, b=”hello”, c=4.3
Remember : number of variables on left must match the number values on right, if
not then its an error
• Multiple variable single value
a=b=c=1
Value at the end
Three variables with same value
All the variable will be 1, a,b,c are labels of memory assigned to 1
Eg a=10
b=c=d=a
In this a have the value to assign

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”)

Role of Semicolon in Python


In Python we type every statement in a different line
print(“hello”)
print(“how are you”)
But semicolon can be used to type on the same line
print(“hello”);print(“how are you”)
Output
hello
how are you
Remember: end has an advantage if and only if you write in a file or colab notebook
• print(a=15)
→ assign 15 value to a Python will answer as it will give an error
• print(“a,b,sep=’#’”)
a,b,sep=’#’
• print(a,b) print(“a,b”)
12 13 a,b
• Python read inside quotes except for escape sequence
• If you give an expression(equation ) solve then displays the answer
print(a+b)
Output
25
print(3.14*r*r)
Solves and give answer
r=2
print(“area=”,3.14*r*r)
area=12.54
print(“area=”,3.14*r*r,” sq m”)
area=12.54 sq m
print(“area=”,3.14*r**2,”sq m”)
area= 12.54 sq m
print(“area=”,3.14*r**2,”sq m”,sep=” “)

How to accept the data???


• Function - input()

• Can be give

input() → empty ()

input(“message”)

Eg

input(“enter data ”)

Enter data = → can input data here

print(“enter data”)

input()

Enter data

= → input here

print(“enter data”, end=” “)

input()

Enter data =

• Return data in string or text form

• Convert the data into the type you want

Eg

For integer data use int()

variable=int(input(“enter data:”))

Eg

a=int(input(“enter the value of a: “))

int() → for integer data

float() → for floating point values

str() → for string

• Without conversion then data will always be string

• Convert eval() → data converted as per the value


a=int(input(“Enter data:”)) a=eval(input(“enter data:”))

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.

2. Type comment as a triple- quoted multi-line string


Example
‘“multiline comments are useful for detailed
additional information related to program.
It helps clarify certain important things.”’
This type of multi-line comment is also called as doc string .
The docstrings are very useful in documentation.

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

PYTHON DATA TYPES


• Data Type specifies which type of value a variable can store.
• type ( ) function is used to determine a variable's type in Python.
Example
NUMBER DATA TYPE –
1. Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals).
Example : 12, -45
2. Float – This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point.
i) Fractional form or normal decimal notation:

Example : 3.14, 234.5678


ii) Exponential Notation
Example - 0.5E+5, 4.5E-10
3. Complex Numbers – A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j .
Complex Number is a number of the form A + Bj, where j is the imaginary number,
equal to the square root of -1 i.e. √−𝟏 .
Example - 5-6j real part=5, imaginary part -6

BOOLEAN DATA TYPE - Boolean values are the two constant objects False and True.

SEQUENCE DATA TYPES IN PYTHON


Sequence data types store multiple values in an ordered way.
Types:
• String (str) – Text, e.g., "hello"
• List (list) – Ordered, changeable, e.g., [1, 2, 3]
• Tuple (tuple) – Ordered, unchangeable, e.g., (1, 2, 3)
MAPPING DATA TYPES IN PYTHON
Mapping data types store key-value pairs.

• Dictionary (dict) – Unordered collection of key: value pairs


Example: {"name": "Ravi", "age": 12}

NONE DATA TYPE


None is a special data type in Python that represents “nothing” or no value.
x = None
print(x) # Output: None

MUTABLE AND IMMUTABLE DATA TYPES


In Python, data types are divided into two categories:
Mutable: Data can be changed after it is created.
Immutable: Data cannot be changed once it is created.
How does Python decide?
When a value is created, Python stores it at a memory location.
• If Python allows the same memory location to be updated, it is mutable.
• If Python creates a new object with a new memory address on change, it is
immutable.

Data Type Mutable / Immutable


int Immutable
float Immutable
str Immutable
tuple Immutable
bool Immutable
list Mutable
dict Mutable
set Mutable
Example to Understand:
IMMUTABLE MUTABLE
a = "hello" b = [1, 2, 3]
print(id(a)) # say memory address is 101 print(id(b)) # say memory address is 303

a = a + " world" b[0] = 100


print(id(a)) # new address, e.g., 202 print(id(b)) # still 303
OPERATORS
⚫ The symbols that trigger the operation / action on data are called Operators and the
data on which the operation is performed is called as Operands.
⚫ Operators are the constructs which can manipulate the value of operands.
⚫ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
⚫ The operand specifies the data that is to be manipulated by the operator.

TYPES OF OPERATORS
Python language supports the following types of operators:
⚫ Arithmetic Operators
⚫ Comparison (Relational) Operators
⚫ Assignment Operators
⚫ Logical Operators
⚫ Membership Operators
⚫ Identity Operators

Arithmetic Operators - Used to perform mathematical operations like addition,


subtraction, multiplication and division etc.
OPERATOR DESCRIPTION EXAMPLE
+ Addition Adds values on either side of the operator. a=10, b=20
a + b = 30
- Subtraction Subtracts right hand operand from left hand a – b = -10
operand.
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand b%a=0
and returns remainder
** Exponent Performs exponential (power) calculation on a**2 =100
operators
// Floor The division of operands where the result is the 9//2 = 4 ,
Division quotient in which the digits after the decimal point 9.0//2.0 = 4.0,
are removed. But if one of the operands is negative, -11//3 = -4,
the result is floored, i.e., rounded away from zero -11.0//3 = -4.0
(towards negative infinity) −

Comparison (Relational) Operators - Relational operators compares the values. It either


returns True or False according to the given condition.
Operator Description Example
== If the values of two operands are equal, then the (a == b) False
condition becomes true.
!= If values of two operands are not equal, then condition (a != b) True
becomes true. 7!=23 True
> If the value of left operand is greater than the value of (a > b) False
right operand, then condition becomes true.
< If the value of left operand is less than the value of (a < b) True
right operand, then condition becomes true.
>= If the value of left operand is greater than or equal to (a >= b) False
the value of right operand, then condition becomes 7>= 98 False
true.
<= If the value of left operand is less than or equal to the (a <= b) True
value of right operand, then condition becomes true. 8<=9

Assignment Operators - The assignment operator is used to assign values to variables in


Python.
Operator Description Example
= Assigns values from right side operands to c = a + b assigns
left side operand value of a + b into c
, j=78
+= Add AND It adds right operand to the left operand and c += a is equivalent
assign the result to left operand to c = c + a
-= Subtract AND It subtracts right operand from the left c -= a is equivalent to
operand and assign the result to left c=c-a
operand
*= Multiply AND It multiplies right operand with the left c *= a is equivalent to
operand and assign the result to left c=c*a
operand
/= Divide AND It divides left operand with the right c /= a is equivalent
operand and assign the result to left to c = c / ac /= a is
operand equivalent to c = c / a
%= Modulus It takes modulus using two operands and c %= a is equivalent
AND assign the result to left operand to c = c % a
**= Exponent Performs exponential (power) calculation c **= a is equivalent
AND on operators and assign value to the left to c = c ** a
operand
//= Floor It performs floor division on operators and c //= a is equivalent
Division assign value to the left operand to c = c // a

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 –

str= ‘HELLO 123#’


‘X’ in str
Operator Description Example
in Evaluates to true if it finds a variable in the x in y, here in results in a
specified sequence and false otherwise. 1 if x is a member of
sequence y.
not Evaluates to true if it does not finds a variable x not in y, here not in
in in the specified sequence and false otherwise. results in a 1 if x is not a
member of sequence y.
Identity Operators - Identity operators compare the memory locations of two objects.
is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal does not imply that they are
identical.
Operator Description Example
is Evaluates to true if the variables on either x is y, here is results in
side of the operator point to the same object 1 if id(x) equals id(y).
and false otherwise.
is not Evaluates to false if the variables on either x is not y, here is
side of the operator point to the same object not results in 1 if id(x)
and true otherwise. is not equal to id(y).

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)

2. Explicit Type Conversion (also called Type Casting)


You manually convert data using functions like:
• int() → Converts to integer
• float() → Converts to float
• str() → Converts to string
• list(), tuple(), etc.

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

SIMPLE INPUT AND OUTPUT


🠶 To get input from user use input()
🠶 By default input function
<variable> = input ("<Prompt to be displayed>")
This will pause the program and wait for the user to type something.
Note : Whatever the user types is taken as a string.
Example
name = input (‘Enter your name’) #taking text input
age = (input (‘Enter your age’)) # although user wants a number but input takes
#string by default.
Reading Numbers
age = int (input (‘Enter your age’)) #input string converted into integer
#suppose user entered 10
g = age+12 #10+12
print(g) #output - 22

Output through print () – display the result

print( object, [sep =‘ ‘ or <separator string > end = ‘\n’ or <end-string>])

Example:
print("Hello", "World", "!!!!", sep="-")
output: Hello-World-!!!!

print("Hello", end=" ")


print("World")
output: Hello World
DEBUGGING
• Debugging refers to the process of locating the place of error, cause of error
and removing the errors by rectifying the code accordingly.An error in
program caused while executing it or producing incorrect output is called as
Program bug.
• An error called as bug is the code that prevents a program from compiling and
running correctly OR DESIRED OUTPUT.
• These are of three types:
• Compile Time Error
• Run Time Error
• Logical Error
1. COMPILE TIME ERROR - The errors that occurs during compile – time are called as
Compile time errors.
When a program is compiled, it checks whether it follows the programming languages rules
or not.
It is of two Types:
• Syntax Errors
• Semantics Error
Syntax Errors-

Syntax refers to formal rules governing the construction of valid statements in a
language.
• Python’s indentation errors (wrong indentation) are syntax errors.
Example –
X =9
X=<23 # x <=23
PRINT(x) # print(x)
if a<0:
print ‘negative’
Semantics Error-
• “Semantics refers to the set of rules which give the meaning of a statement.”
• This error occurs when the statement is not meaningful.
Example –

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.

3. RUN TIME ERROR –


A run-time error is an error that occurs while the program is running, causing it to stop
or crash. Such error happens after the program starts, when Python cannot
complete an instruction due to a problem during execution.
Examples:

• Dividing by zero → 10 / 0 (ZeroDivisionError)Using a value that doesn’t exist → print(x)


(when x is not defined)
• Accessing an invalid index → list[10] (if the list is smaller)

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

a=int(input("enter the 1st number:"))

b=int(input("enter the 2nd number:"))

sum=a+b

print("sum=",sum)
Q what is the difference between

print(“sum”) and print(sum)

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)

You can give anything in quotes, This has to be an identifiers


alphabets, digits or any special
character

No need to declare Declare or assign the value

In Python sum,Sum,SUM are 3 different identifiers


sum=a+b
print(Sum)
It is an Error

Q Write a program in Python to accept 3 numbers, find their sum and product.

a=int(input("Enter the 1st number:"))

b=int(input("Enter the 2nd number:"))

c=int(input("Enter the 3rd number:"))

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)

Other ways of writing this message

• print(a,”+”,b,”+”,c,”=”,sum)

• print(“SUM=”,sum)

• print(“Sum=”,a+b+c)

• print(“the Sum of “,a,b,c,” is “,sum)

• Message must : -sum of the 3 number, message that indicates that it is sum

Q Why I must give a message before input or printing output ?

Ans

• For programmer’s reference

• To make understandable for user

• Eg

• print(sum) --> 25

• print(“sum=”,sum) → sum=25

• Meaningful messages

• Message should be too long or too short,crisp message.


ypes of Expressions in Python (with Examples)

Here’s a breakdown of the most common types:

1. Arithmetic Expressions

• Perform basic mathematical operations.

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

2. Relational / Comparison Expressions

• Compare two values and return a Boolean (True or False).

x = 10

y=5

print(x > y) # True

print(x == y) # False

print(x != y) # True

3. Logical Expressions

• Combine Boolean values using logical operators.

x=5

print(x > 0 and x < 10) # True

print(x < 0 or x > 10) # False

print(not(x > 0)) # False

4. Bitwise Expressions

• Work at the bit level (less common for beginners).


a=5&3 # Bitwise AND

b=5|3 # Bitwise OR

c=5^3 # Bitwise XOR

d = ~5 # Bitwise NOT

e = 5 << 1 # Left shift

f = 5 >> 1 # Right shift

5. Assignment Expressions (Walrus Operator :=)

• Assign a value as part of an expression (Python 3.8+).

if (n := len("hello")) > 3:

print(n) # Output: 5

6. Identity Expressions

• Compare whether two references point to the same object in memory.

a = [1, 2]

b=a

print(a is b) # True

print(a is not b) # False

7. Membership Expressions

• Test whether a value exists in a collection.

fruits = ["apple", "banana"]

print("apple" in fruits) # True

print("grape" not in fruits) # True

8. String Expressions

• Operations involving strings.

greeting = "Hello" + " " + "World" # Concatenation

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.

and Operator with Constants

x and y

• Returns x if x is falsy, otherwise returns y.

• Evaluation stops at the first falsy value (short-circuit).

Examples:

print(0 and 5) # 0 → 0 is falsy, returned immediately

print(3 and 5) # 5 → 3 is truthy, so returns 5

print("" and "hello") # "" → empty string is falsy

print("hi" and "") # "" → evaluates to empty string

or Operator with Constants

x or y

• Returns x if x is truthy, otherwise returns y.

• Evaluation stops at the first truthy value (short-circuit).

Examples:

print(0 or 5) # 5 → 0 is falsy, so returns 5

print(3 or 5) # 3 → 3 is truthy, returned immediately

print("" or "hello") # "hello" → empty string is falsy

print("hi" or "") # "hi" → first truthy value

Truthy and Falsy in Python

In a Boolean context, these are falsy:

• 0, 0.0, 0j

• None

• False

• "" (empty string)

• [] (empty list)
• {} (empty dict)

• set(), tuple(), etc.

Everything else is truthy.

Summary Table

Expression Result Reason

0 and 5 0 0 is falsy

5 and 0 0 5 is truthy → return next

5 and 10 10 Both are truthy → return last

0 or 5 5 0 is falsy → return next

5 or 0 5 5 is truthy → return immediately

"" and "hello" "" "" is falsy

"hi" or "" "hi" First operand is truthy

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:

1. Implicit Type Casting (done automatically)


2. Explicit Type Casting (done by the programmer)
Examples:
int(3.3) produces 3 str(3.3) produces “3.3”
12 Syntax Error - Occurs when the rules of the programming language are broken. Detected
before the program runs (during compilation).
Example –
X =9
X=<23 # x <=23
PRINT(x) # print(x) if a<0:
print ‘negative’
Run-time Error - Occurs while the program is running. Syntax is
correct, but something goes wrong during execution Example -
dividing by zero, accessing invalid index .
CASE STUDY BASED QUESTIONS
1. ABC school wants to develop a simple Python script to store a student’s name, roll number,
and marks in three subjects. They also want to calculate the average marks and check if the
student has passed (pass mark is 33 in each subject).
Questions:
1. Identify the appropriate data types for:
o Student name
o Roll number
o Marks
2. Write a Python code to store the above data and calculate average marks.
3. Use operators to check if the student passed in all subjects.
4. What error will occur if a string is added to an integer in the marks
calculation? Show how to correct it.
2. Rehan wants to create an employee salary calculator which takes basic salary and calculates
HRA (20%) and DA (50%), then calculates the gross salary.
Gross Salary = Basic Salary+HRA+DA
Questions:
1. Define variables to store basic salary, HRA, and DA.
2. Write the code to calculate gross salary.
3. Which operator will be used if we don’t want decimal values?
4. Identify and fix the error if someone mistakenly writes HRA =
basic_salary * 20/100%.
ANSWERS
1 1. Student name → str
Roll number → int or str (depending on format)
Marks → int or float
2. name = "Alice" roll number =
101 mark1 = 78
mark2 = 65
mark3 = 80
average = (mark1 + mark2 + mark3) / 3 print
("Average Marks:", average)

3. if mark1 >= 33 and mark2 >= 33 and mark3 >= 33:


print("Passed")
else:
print("Failed")
4. TypeError: can only concatenate str (not "int") to str

2 1. basic_salary = 20000 hra =


basic_salary * 0.20 da =
basic_salary * 0.50
2. gross_salary = basic_salary + hra + da print
("Gross Salary:", gross_salary)
3. // floor division
4. SyntaxError: invalid syntax due to % symbol in 20/100% hra =
basic_salary * 20 / 100 # or basic_salary * 0.20
COMPETANCY BASED QUESTIONS
1 Question:
You are building a banking system where users can deposit and withdraw money.
a.) Declare variables for account holder name, balance, and last transaction amount.
b.) Write code to update the balance after a deposit of ₹1500 and a withdrawal of
₹800.

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)

3 Competency Focus: Select and use appropriate data types. a)


- Name → `str`
- Age → `int`
- Weight → `float`
-Height→’float’
- Exercised → `bool` or `str`
b)
#input weight and height
bmi = Weight/(Height*Height)
print(bmi)

You might also like