0% found this document useful (0 votes)
2 views72 pages

Module 1 PPT 2 Python Part 2 Chapter 2

Python Programming 1st and 2nd sem 2025 Scheme Module 1 Chapter 2 PPT Prathima G Associate Professor Dept of CSE(Data Science), M.S Engineering College Bangalore 1BPLC105B/1BPLC205B

Uploaded by

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

Module 1 PPT 2 Python Part 2 Chapter 2

Python Programming 1st and 2nd sem 2025 Scheme Module 1 Chapter 2 PPT Prathima G Associate Professor Dept of CSE(Data Science), M.S Engineering College Bangalore 1BPLC105B/1BPLC205B

Uploaded by

Prathima G
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Python Programming

Module 1_Chapter 2
By
Prathima G
Associate Professor, Dept of CSE(Data Science)
[Link] College,Bangalore
Variables, expressions and statements

Values and Data Types in Python


• Fundamental concept in programming
• Every program works with values
• Values are classified into different data types
What is a Value?
• A value is a basic unit of data used in a program.
• Programs manipulate these values to perform
operations.
• Examples:
• 4 → result of 2 + 2
• "Hello, World!" → text value
Data Types
• Values are grouped into classes called data types.
• Common Python data types:
• Integer (int) → whole numbers
• String (str) → sequence of characters
• Float (float) → decimal numbers
Integer Data Type

• Represents whole numbers without decimals


• Examples:
•5
• 10
• 17
• Example:
print(type(17))
• Output:
<class 'int'>
String Data Type

• Represents text or sequence of characters


• Always enclosed in quotation marks
• Examples:
str1=‘Hello’
str2="Python"
str3=‘’’Hello, World!’’’
Example:
print(type("Hello, World!"))
Output:
<class 'str'>
Float Data Type

• Represents numbers with decimal points


• Uses floating-point representation
• Examples:
var1=3.2
var2=5.75
var3=10.0
• Example:
print(type(3.2)
Output:
<class 'float'>
Using type() Function

• Python provides the type() function to identify the


data type.
• Example:
print(type("Hello"))
print(type(10))
print(type(5.6))
• Purpose:
Helps programmers check the class of a value
Numbers vs Strings

• Some values look like numbers but are actually


strings.
• Examples:
print(type("17"))
print(type("3.2"))
• Output:
<class 'str’>
<class 'str'>
• Reason:
They are enclosed in quotation marks
Strings in Python

•A string is a sequence of characters.


•Strings are enclosed in quotation marks.
•Python supports single, double, and triple quotes.
String Data Type Example

• Python identifies strings using the type() function.


Example 1:
>>> print(type('This is a string.’))
<class 'str’>
Example 2:
>>> print(type("And so is this."))
<class 'str'>
Different Ways to Write Strings

• Strings can be written using three quotation styles.


• Example: print(type('This is a string.’))
>>> type('This is a string.’) <class 'str’>
<class 'str'> print(type("And so is this."))
<class 'str’>
>>> type("And so is this.")
print(type("""and this."""))
<class 'str'> <class 'str’>

>>> type("""and this.""") print( type('''and even this...’‘’))


<class 'str'> <class 'str'>

>>> type('''and even this...'‘’)


<class 'str'>
• All these forms represent string data type.
Using Quotes Inside Strings

• Double quotes can contain single quotes.


• Example:
"Bruce's beard"
• Single quotes can contain double quotes.
Example:
• 'The knights who say "Ni!"'
• This helps avoid syntax errors in strings.
Triple Quoted Strings

• Strings enclosed with three quotation marks are


called triple quoted strings.
• They can contain both single and double quotes.
Example:
>>> print('''"Oh no", she exclaimed, "Ben's bike is
broken!"'‘’)

"Oh no", she exclaimed, "Ben's bike is broken!"


Multiline Strings

• Triple quoted strings can span multiple lines.


• Example:
• >>> message = """This message will
... span several
... lines."""
>>> print(message)
This message will
span several
lines.
Variables in Python

• Variables are an important feature of programming.


• They allow programs to store and manipulate data.
• A variable is a name that refers to a value.
What is a Variable?
• A variable stores a value in memory.
• The variable name is used to access or modify the
value.
• Variables make programs flexible and reusable.
Example structure:
• variable_name = value
Assignment Statement

• The assignment statement gives a value to a


variable.
• The assignment operator (=) is used.
Examples:
>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159

• These are three variable assignments.


Explanation of the Examples

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


• Variable message stores a string value.
>>> n = 17
• Variable n stores an integer value.
>>> pi = 3.14159
• Variable pi stores a floating-point value.
Assignment Operator (=)

• The symbol = is called the assignment operator.


• It assigns the value on the right side to the variable
on the left side.
• Example:
message = "Hello"
• Meaning:
Store "Hello" in the variable message.
Assignment vs Equality

• Do not confuse:
• Assignment operator (=) → assigns value
• Equality operator (==) → checks equality
• Example:

x = 10 # assignment
x == 10 # comparison
Invalid Assignment Example

• You cannot assign a value to a literal.


• Example:
>>> 17 = n
• Output:
File "<interactive input>", line 1
SyntaxError: can't assign to literal
• Reason:
The left side must always be a variable name.
Variables Can Change in
Python
• Variables help programs remember information.

• Example: storing the score of a football game.

• The value stored in a variable can change over time.


Why Variables Are Called
“Variable”

• The word variable means the value can change.

• A program can:
• Assign a value to a variable

• Later assign a different value to the same variable

• Example idea:
Like a scoreboard in a football game, the score
keeps changing.
• Example – Assigning a Value
>>> day = "Thursday"
>>> day
'Thursday'
Explanation:
• Variable day stores the string "Thursday".
• When we type day, Python returns the stored value.
Example – Changing the Value

• The value of the same variable can be changed.


>>> day = "Friday"
>>> day
'Friday'
• Explanation:
The previous value "Thursday" is replaced by "Friday"
Example – Changing Data Type

• A variable can even store a different type of value.


>>> day = 21
>>> day
21
Explanation:
• Now the variable day stores an integer instead of a string.
Variable Names and Keywords in Python

• Variables must follow specific naming rules.


• Incorrect names lead to syntax errors.
• Some words are reserved keywords and cannot be used as variable
names.
Rules for Variable Names
• Variable names can be arbitrarily long.
• They can contain:
• Letters
• Digits
• Underscores (_)
• The name must begin with a letter or underscore.
• Example structure:
variable_name = value
• Case Sensitivity
• Python variable names are case sensitive.
• Example:
Bruce
bruce
• Explanation:
These are two different variables.
Using Underscores

• The underscore (_) can appear in variable names.


• It is commonly used when a variable name contains
multiple words.
Examples:
my_name
price_of_tea_in_china
• Recommendation for beginners:
• Start variable names with a letter.
• Illegal Variable Names
• If a variable name violates the rules, Python produces a
SyntaxError.

Example 1:
>>> 76trombones = "big parade"

SyntaxError: invalid syntax


Reason:
• Variable name cannot start with a number.
• Illegal Character in Variable Name

• Example:

>>> more$ = 1000000


SyntaxError: invalid syntax

Reason:

• $ symbol is not allowed in variable names.


Python Keywords

• Example:
>>> class = "Computer Science 101"

SyntaxError: invalid syntax


Reason:
• class is a Python keyword.
What Are Keywords?

• Keywords are reserved words in Python.


• They define the syntax and structure of the language.
• Keywords cannot be used as variable names.
• Python has around 30+ keywords.
Examples:
class
if
else
while
for
return
•Variable names must start with a letter or underscore.

•They may contain letters, digits, and underscores.

•Python is case sensitive.

•Keywords cannot be used as variable names.

•Invalid names result in SyntaxError.


Statements in Python

• A statement is an instruction that the Python interpreter


executes.
Example
• Assignment statement
y = 3.14
• Other Types of Statements
• while statements
• for statements
• if statements
• import statements
•When a statement is typed in the Python command line,
Python executes it immediately.
•Statements do not produce a result
Evaluating Expressions

An expression is a combination of:


• Values
• Variables
• Operators
• Function calls
• Example in Python Prompt
>>> 1 + 1
2

Python evaluates the expression and displays the result.


Using Functions in Expressions

• Example:
>>> len("hello")
5
Explanation
• len() is a built-in Python function.
• It returns the number of characters in a string.
Other built-in functions we have seen:
• print()
• type()
• len()
Expressions Produce Values

• The evaluation of an expression produces a value.


• Because of this, expressions can appear on the right-
hand side of assignment statements.
• Example:
• >>> x = len("hello")
>>> x
5
Simple Expressions
• A value alone is also an expression.
Example:
>>> 17
17
• A variable can also be an expression.
Example:
>>> y = 3.14
>>> y

3.14
Operators and Operands

Operators
•Special symbols that represent computations.
•Used to perform mathematical operations.
Examples of Operations
•Addition Subtraction
•Multiplication Division Exponentiation
Operands
•The values or variables on which operators perform operations.
Example:
20 + 32
•+ → Operator
•20 and 32 → Operands
• Python Expression Examples

• Some valid Python expressions:

• 20 + 32
hour - 1
hour * 60 + minute
minute / 60
5 ** 2
(5 + 9) * (15 - 7)
Exponentiation Operator

• In Python:
* → Multiplication
** → Exponentiation (power)
Example:
• >>> 2 ** 3
8
Example:
• >>> 3 ** 2
9
Variables as Operands

• When a variable name appears as an operand,


Python replaces it with its stored value before
performing the operation.
• Example:
• hour * 60 + minute
• Here:
• hour and minute are variables used as operands.
Example – Converting Minutes to Hours

• Convert 645 minutes into hours

>>> minutes = 645


>>> hours = minutes / 60
>>> hours
10.75
Type Converter Functions

• Python provides functions to convert values from one


data type to another.

• Common Type Converter Functions

int() → converts value to integer

float() → converts value to floating point number

str() → converts value to string

These are called type converter functions.


Using int() Function

• The int() function converts a number or string into an


integer.
• For floating point numbers, Python removes the
decimal part (called truncation).
Examples:
>>> int(3.14)
3
>>> int(3.9999)
3
>>> int(3.0)
3
• Note: It does not round to the nearest integer.
• More int() Examples

• Examples with negative numbers and variables:

>>> int(-3.999)
-3
>>> int(minutes / 60)
10
Converting a string to integer:

• >>> int("2345")

2345

>>> int(17) #it works if its already int

17
Invalid Conversion Example

• If the string does not represent a valid number,

• Python produces an error.

Example:

>>> int("23 bottles")

Output:

• ValueError: invalid literal for int() with base 10: '23 bottles'
float() and str() Functions

float() Function

• Converts values into floating point numbers.

• >>> float(17)
17.0
>>> float("123.45")
123.45
str() Function

• Converts values into strings.

>>> str(17)
'17'
>>> str(123.45)
'123.45'
Order of Operations in Python

• When an expression contains multiple operators, Python


follows rules of precedence to decide the order of evaluation.
• Python follows the same rules used in mathematics.
• A useful acronym to remember the order is:
PEMDAS
• P – Parentheses
• E – Exponentiation
• M – Multiplication
• D – Division
• A – Addition
• S – Subtraction
Parentheses (Highest Precedence)

• Parentheses are evaluated first.


• They can force the order of evaluation.
• Example1:
>>> 2 * (3 - 1)
Result:
4
>>>(1 + 1) ** (5 - 2)
Result:
8
Exponentiation Precedence

• Exponentiation (**) has higher precedence than


multiplication or addition.
• Example1:
>>> 2 ** 1 + 1
Result:
3
>>>3 * 1 ** 3
Result:
3
Multiplication, Division, Addition, Subtraction

• Multiplication (*) and Division (/) have the same


precedence.
• Addition (+) and Subtraction (-) have the same
precedence but are lower.
Examples:
>>>2 * 3 - 1
Result:
•5
>>>5 - 2 * 2
Result:
•1
Left-to-Right Evaluation

• Operators with the same precedence are evaluated


from left to right.
• Example:
>>>6 - 3 + 2
• Steps:
6-3=3
3+2=5
• Final result:
•5
• Exception – Exponentiation
• Exponentiation (**) is evaluated right to left, not left
to right.
• Example:
>>>2 ** 3 ** 2
Result:
512
• Because Python evaluates it as:
• 2 ** (3 ** 2)
• To change the order, use parentheses:

• (2 ** 3) ** 2

Result:

• 64
Operations on Strings

• In Python, mathematical operations cannot normally be


performed on strings.

• Even if a string looks like a number, it cannot be used directly


in arithmetic operations.

• Examples of illegal operations:

>>> message - 1
>>> "Hello" / 123
>>> message * "Hello"
>>> "15" + 2
String Concatenation using +

• The + operator works with strings, but it performs


concatenation, not addition.
• Concatenation means joining two strings together.
Example:
• fruit = "banana"
baked_good = " nut bread"
print(fruit + baked_good)
Output:
• banana nut bread
• Note: The space before "nut" is part of the string.
String Repetition using *

• The * operator works on strings for repetition.


• One operand must be a string and the other must be
an integer.
Example:
>>>'Fun' * 3
Output:
• FunFunFun
Analogy with Arithmetic

• String repetition behaves similar to multiplication.


Example:
>>>4 * 3 = 4 + 4 + 4
• Similarly:
>>>"Fun" * 3
• is equivalent to:
"Fun" + "Fun" + "Fun"
Result:
• FunFunFun
Composition in Programming

• In programming, we often combine small building blocks to create larger


programs.

• Basic building blocks include:


• Variables

• Expressions

• Statements

• Function calls

• Composition means combining these elements to solve a problem.

• Example task:
Compute the area of a circle using the formula:
Step-by-Step Program

• First, write the program in four separate steps.

• response = input("What is your radius? ")


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

• Explanation:

1. Get input from the user

2. Convert the input to a float

3. Calculate the area

4. Print the result


Combining Statements

• We can compose some statements together to make the code


shorter.

• Example:

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


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

• Here:

• Input and conversion are combined into one line

• Calculation and printing are also combined.


Writing Everything in One Statement

• We can even write the entire program in one statement.

print("The area is ", 3.14159*float(input("What is your

radius?"))**2)

• This shows how programming allows us to compose

larger expressions from smaller parts.


• Modulus Operator in Python
• The modulus operator (%) gives the remainder
when one number is divided by another.
• It works on integers or integer expressions.
• The syntax is similar to other arithmetic
operators.
• It has the same precedence as multiplication (*).
Example:
>>> q = 7 // 3 # Integer division operator
>>> print(q)
2
>>> r = 7 % 3
>>> print(r)
1
Uses of the Modulus Operator

• The modulus operator is very useful in


programming.
1. Checking divisibility

• If x % y == 0, then x is divisible by y.

Example concept:

•x%y

• If result is 0 → perfectly divisible


Extracting Digits Using Modulus

• The modulus operator can extract digits from


numbers.
Examples:
• x % 10 → gives the last digit of a number
• x % 100 → gives the last two digits
• Example concept:
x % 10
x % 100
• This is useful in number manipulation problems.
• Example – Converting Seconds
• Program to convert seconds into hours, minutes,
and seconds.
• total_secs = int(input("How many seconds, in total?"))
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60

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


"secs=", secs_finally_remaining)

You might also like