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

Python Lec1.1 DataTypes Variables

The document provides an overview of Python fundamentals, including programming concepts, the role of interpreters and compilers, and key features of Python. It covers variables, data types, operators, and best practices for naming and using identifiers. Additionally, it discusses input handling and type conversion in Python, emphasizing the importance of understanding data types for effective programming.

Uploaded by

abkidstoons
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)
2 views45 pages

Python Lec1.1 DataTypes Variables

The document provides an overview of Python fundamentals, including programming concepts, the role of interpreters and compilers, and key features of Python. It covers variables, data types, operators, and best practices for naming and using identifiers. Additionally, it discusses input handling and type conversion in Python, emphasizing the importance of understanding data types for effective programming.

Uploaded by

abkidstoons
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

Python Fundamentals

Dr. Indu Joshi

Assistant Professor at
IIT Mandi, India

19 May 2026
Programming

• Programming means giving instructions to a computer in a


language that can be processed and executed.
• Humans write instructions in a high-level language
• Machines finally execute only machine code
• A translator bridges the gap between both worlds
Translator Flow

Human-readable
program

Translator
(compiler/interpreter)

Machine code
Interpreter Vs Compiler

Interpreter Compiler
• Converts high-level language • A specific type of translator
into machine code
• Translates the complete
• Translates and executes line program at once
by line
• Faster execution after
• Slower because translation compilation
happens during execution
• Reports many errors together
• Stops at first error after compilation
encountered

Key Idea
Every compiler is a translator, but not every translator is a compiler.
Core Features of Python

• Python is simple and easy to learn


• It is free and open source
• It is a high-level language
• It is portable across operating systems
Why is Python Popular

• Readable syntax
• Large standard library
• Useful for both small scripts and large applications
• Common Uses: Web development, data analysis, AI/ML
Example 1 - Using print() with Different Values

Code Output
print("Python Basics") Python Basics
print(2026) 2026
print("Score =", 95) Score = 95
print("A", "B", "C") A B C

Observation
print() can display strings,
numbers, and multiple values
together.
Example 2 - Multiple print() Statements

Code Output
print("Learning Python") Learning Python
print("Variables store values") Variables store values
print("Operators process data") Operators process data

Observation
Every print() statement starts
output on a new line.
Variables

Definition Observation
A variable is a name given to a Each variable stores a value that
memory location in a program. can later be reused, printed, or
updated.

Examples Common Patterns


course = "Python" Single assignment:age = 20
batch = 2 Update value:age = age + 1
fee = 1499.50
Multiple assignment:
a, b = 5, 6
Example 3 - print() with Variables

Code Output
city = "Jaipur" Jaipur
score = 18 Score = 18
print(city) 23
print("Score =", score) 42
print(14 + 9)
print(7 * 6)
Observation
Python evaluates arithmetic
expressions first and then prints
the final result
Example 4 - Updated Variables

Code Output
count = 4 4
print(count) 7

count = count + 3
print(count) Key Point
Variables can be reassigned.
The latest assigned value
becomes the current value
Example 5 - Calculation within print()

Code Output
item = "Notebook" Notebook
quantity = 3 Quantity = 3
price = 40 Total = 120

print(item)
print("Quantity =", quantity) Observation
print("Total =", quantity * price) Variables make expressions
reusable. Once quantity and
price are stored, total cost is
easy to compute.
Python Character Set

• The set of valid characters that can be used in a Python


program

Character Categories Quick Examples


• Letters: A to Z, a to z Letters name, total
Digits 7, 2026
• Digits: 0 to 9
Symbols +, *, =
• Symbols: +, -, *, / and more. Space separates words
• Whitespaces: space, tab, carriage
return, newline Important Note
• Python can also process all Python is case-sensitive. Value
ASCII and Unicode characters and VALUE are different names.
ASCII Characters

• ASCII stands for American Standard Code for Information


Interchange.
• It is an early character encoding system used to represent text
in computers.
• Example- A: 65, B: 66, a: 97
Unicode Characters

• Unicode is a universal character encoding system designed to


represent characters from almost all languages and symbol
systems.
• A: U+0041
• (Hindi N) : U+0928
• :) : U+1F60A
Memory

Mental Model Simple Visualization


A variable name refers to a Variable Value
location in memory where its course ”Python”
current value is stored. batch 2
• course stores text fee 1499.50
• batch stores an integer
• fee stores a decimal Key Point
number Updating a variable changes
Reassignment Example the value stored in memory.
score = 10
score = 15

The older value is replaced by the


new value.
Rules for Identifiers

• A Python identifier is a name used to identify variables,


functions or other objects in a Python program.

Naming Rules Examples


1. Identifiers can be combinations of Valid: myVariable,
uppercase letters, lowercase letters, variable_1,
digits, and underscore (_) variable_for_print
2. An identifier cannot start with a Invalid: 1variable,
digit user-name, value@1

3. Special symbols such as Good Practice


exclamation mark, hash, at sign,
Use meaningful names such
percent sign, and dollar sign cannot
as total_marks,
be used
student_name, or
4. An identifier can be of any length net_price.
Choosing Better Variable Names

Good Naming Habits Examples


• Use names that reveal what the Better: student_name,
value means total_marks, unit_price
• Prefer snake_case for multi-word Weaker: a1, value1, abc
names (all letters: lowercase,
words separated using Reason
underscores) Meaningful names make
• Keep names short but still debugging and later revision
much easier because the role
descriptive
of each variable is visible
• Avoid vague names such as x, immediately.
data, or temp unless the context
is very small
Data Types

Primary Built-in Types Examples


• Integer (int) age = 23 integer
topic = "Loop" string
• String (str) price = 49.75 float
passed = True boolean
• Float (float) value = None NoneType

• Boolean (bool)
• None (NoneType) Typical Uses
• int for counts and indexes
• float for averages
• bool for conditions
• str for names and messages
Choosing the Right Data Type

Quick Decision Guide Why This Matters


The chosen type affects which
Type Use when you need
operations are valid and what
int whole counts such as students result Python produces.
or marks
float decimal values such as height
or price Example
str text such as names or prompts A phone number may look
bool yes/no style condition results numeric, but it is usually stored
NoneType placeholder for no value yet as text because arithmetic is not
performed on it.
Example: Checking Data Types with type()

Code Output
count = 12 <class ’int’>
ratio = 4.5 <class ’float’>
passed = True <class ’bool’>
topic = "Functions" <class ’str’>
value = None <class ’NoneType’>
print(type(count))
print(type(ratio)) Observation
print(type(passed)) The type() function helps
print(type(topic)) us verify what kind of value a
print(type(value)) variable currently stores.
Keywords and Case Sensitivity

Key Rules Representative Keywords


• Keywords are reserved words in Python and else in return
• They cannot be used as identifiers as except is True
• Python is case-sensitive break for None while
• def if pass False
True, False, and None must use the
correct capitalization
Case Sensitivity
Invalid Names value, Value, and VALUE are
if = 10 treated as three different
class = "A" identifiers in Python.
True = 0
are invalid because they use reserved words.
Good Practice
Avoid variable names that closely
resemble Python keywords or differ
only in capitalization.
Working with Variables: Addition Example

Code Output
x = 8 sum = 19
y = 11
sum_value = x + y
print("sum =", sum_value) Key Point
Arithmetic results can be
stored in variables and reused
What Happens later.
• Values are stored in variables
• Python adds both values Extension
The same pattern works for
• Result is stored in sum_value subtraction, multiplication,
and division.
Comments in Python

Code Why Comments Matter


# Single line comment Comments explain logic,
print("Visible output") leave reminders, and improve
code readability.
"""
Multi-line
comment Execution Rule
"""
Python ignores comments
during execution, so they do
Types of Comments not affect output.
• # is used for single-line comments
Shortcut Tip
• Triple quotes are often used for
multi-line notes Use Ctrl + / to quickly
comment or uncomment
selected lines.
Types of Operators

Definition Quick Examples


An operator is a symbol that performs 8 + 2 gives 10
a certain operation between operands. 8 > 2 gives True
x += 1 updates x
• Arithmetic: +, -, *, /, %, ** a and b combines conditions
• Relational: ==, !=, >, <, >=, <=
Why They Matter
• Assignment: =, +=, -=, *=, /=
Operators are the core tools
• Logical: not, and, or used to calculate values,
compare data, and build
conditions.
Example: Arithmetic Operators

Code Output
a = 6 9
b = 3 3
18
print(a + b) 2.0
print(a - b) 2
print(a * b) 0
print(a / b)
216
print(a // b)
print(a % b)
print(a ** b) Quick Reading
The same inputs produce
different outputs when we ask
for exact division, floor
division, remainder, or power.
Example: Division, Floor Division, and Remainder

Code Output
a = 17 3.4
b = 5 3
3
print(a / b) 2
print(a // b)
print(int(a / b)) Key Difference
print(a % b)
a / b returns a
floating-point result, while
Operators Used a // b keeps only the
whole-number quotient.
• / → exact division
• // → floor division Observation
int(a / b) removes the
• % → remainder operator
decimal part after division.
Quick Note: a // b vs int(a / b)

Code Output
a = -17 -4
b = 5 -3

print(a // b) Observation
print(int(a / b))
This difference becomes
important mainly for negative
Why They Differ numbers.
// performs floor division, while
int() removes only the decimal
part from the result.
Example: Operations on Strings

Code Output
s = "Go" GoGo
GoGo
print(2 * s) Goal
print(s * 2)
print(s + "al") Key Point
# print(s ** 2) # invalid Strings support
concatenation with + and
repetition with *. The power
operator ** is meant for
numeric values, not strings.
Example: Relational Operators

Code Output
marks = 72 False
passing = 40 True
True
print(marks == passing) False
print(marks != passing)
print(marks >= passing)
Observation
print(marks <= passing)
Relational operators always
produce boolean results, so
they are commonly used
inside conditions.
Example: Assignment Operators

Code Output
balance = 120 150
300
balance += 30
print(balance)
Meaning
balance *= 2 Assignment operators update
print(balance) the same variable in a shorter
and cleaner way.
Equivalent Operations
balance += 30 means: balance = Common Operators
balance + 30 += -= *= /=
Example: Logical Operators

Code Output
is_raining = False True
has_umbrella = True True
temperature = 28 True

print(not is_raining) Logical Operators


"and" requires both
print((temperature > 25) and
has_umbrella)
conditions to be True,
"or" requires at least 1
print((temperature < 20) or condition to be True,
has_umbrella)
"not" reverses a boolean
value.
Observation
Logical operators combine or reverse
boolean expressions to create larger
decision rules.
Type Conversion

Automatic Conversion Example Output / Result


distance, time = 7, 2.5 9.5
value = distance + time <class ’float’>
TypeError: unsupported
print(value)
operand type(s)
print(type(value))

Key Point
Incompatible Types Python automatically converts
price, discount = 500, "50" compatible numeric values to a
wider type when needed.
final_value = price - discount
Observation
Operations between incompatible
types such as numbers and
strings produce errors.
Example- Type Casting

Code Output
price = 500 450
discount = "50" <class ’int’>

discount_value = int(discount) Meaning


final_value = price -
Type casting is manual
discount_value
conversion performed using
print(final_value) functions such as int() and
print(type(discount_value)) float().

Observation
Converting values to compatible
types allows arithmetic
operations to work correctly.
More Casting Examples

Code Output
ratio_text = "2.75" 2.75
ratio_value = float(ratio_text) 18 students

count = 18
label = str(count)
Use Case
Casting is useful when values
print(ratio_value) are received as strings but later
print(label + " students") need numeric processing or
formatted output.

Observation
float() converts text to
decimal values, while str()
converts values into text.
Common Casting Functions

Useful Conversion Functions Examples


Function Purpose int("25")
int(y) convert to integer float("3.14")
float(y) convert to decimal value
str(y) convert to string str(42)
list(y) convert to list
tuple(y) convert to tuple Key Point
set(y) convert to set
dict(y) create dictionary from pairs Casting changes the data
type without changing
the logical value.
Input in Python

Core Rules Common Mistake


• input() accepts values from the If you write input() +
keyboard input(), Python joins two
strings unless both are
• The result of input() is always
converted first.
stored as a string
• Use int(input()) for integers Example
"12" + "8" → "128"
• Use float(input()) for decimal
int("12") + int("8") → 20
values

Key Point
Typical Flow
Input conversion is important
Read input → convert if needed → whenever arithmetic
process → display output operations are required.
Example: Input as String, Integer, and Float

Code Sample Run


city = input("Enter city: ") Enter city: Delhi
Enter year: 2026
year = int(input("Enter year: ")) Enter height: 172.4
height = float(input(
City: Delhi
"Enter height: "))
Year: 2026
print("City:", city) Height: 172.4
print("Year:", year)
print("Height:", height) Observation
Different conversions are
Key Point applied depending on the
input() alone stores text, while int() expected type of input data.
and float() convert values for numeric
processing.
Example: Input and String Concatenation

Code Sample Run


first = input("First name: ") First name: Riya
last = input("Last name: ") Last name: Sharma
Riya Sharma
full_name = first + " " + last

print(full_name) Observation
String concatenation is
Key Idea commonly used for names,
messages, labels, and
The + operator joins strings together to formatted output.
create larger text.
Practice Problem 1: Sum of Two Numbers

Problem Example Solution


Write a program to input two a = int(input(
numbers and print their sum. "Enter first number: "))

Sample Run b = int(input(


"Enter second number: "))
Enter first number: 14
Enter second number: 9 sum_value = a + b
sum = 23
print("sum =", sum_value)
Concept Used
input() + type conversion
+ arithmetic addition
Practice Problem 2: Area of a Square

Problem Example Solution


Write a program to input the side side = float(input(
of a square and print its area. "Enter side: "))

Sample Run area = side * side


Enter side: 7 print("area =", area)
area = 49.0

Concept Used
Input + multiplication + variable
storage
Practice Problem 3: Average of Two Floating Numbers

Problem Example Solution


Write a program to input two a = float(input(
floating-point numbers and "Enter first value: "))
print their average.
b = float(input(
"Enter second value: "))
Sample Run
Enter first value: 6.5 avg = (a + b) / 2
Enter second value: 9.5
average = 8.0 print("average =", avg)

Concept Used
Input + arithmetic addition +
division
Practice Problem 4: Compare Two Integers

Problem Example Solution


Input two integers a and b. a = int(input("Enter a: "))
Print True if a >= b;
otherwise print False. b = int(input("Enter b: "))

print(a >= b)
Sample Run
Enter a: 12
Enter b: 12
True

Concept Used
Input + relational operator +
boolean result
Practice Problem 5: Convert Minutes to Hours

Problem Example Solution


Input total minutes and print minutes = int(input(
the equivalent number of "Enter total minutes: "))
hours and remaining minutes.
hours = minutes // 60
Sample Run
remaining = minutes % 60
Enter total minutes: 145
hours = 2 print("hours =", hours)
minutes = 25 print("minutes =", remaining)

Concept Used
Input + floor division +
remainder operator
Thank You

Contact: indujoshi@[Link]

You might also like