0% found this document useful (0 votes)
5 views

GRADE 9&10- Python

Uploaded by

Nilofer Naheeb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

GRADE 9&10- Python

Uploaded by

Nilofer Naheeb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Name derived from famous

BBC comedy show namely


Monty Python’s flying circus
Python was created by Guido Van Rossum
The language was released in February I991
Python got its name from a BBC comedy series from
seventies- “Monty Python‟s Flying Circus”
It is free to use
It has simple syntax and easy to learn and use.
Python is an interpreted language and is portable.
It is an Object oriented language.
It can be easily integrated with other languages
such as C, C++ and Java.
Easy to use Object oriented language
Expressive language
Interpreted Language
Its completeness
Cross-platform Language
Free and Open source
Variety of Usage / Applications
• Python is compact and very easy to use object
oriented language with very simple syntax rules.
It is very high level language and thus very-very
programmer -friendly

• More capable to express code‟s purpose than


many other language like – swapping of two
numbers:
In C++ In Python
int a=2, b=3, tmp; a,b=2,3
tmp=a; a,b=b,a
a=b;
S
b=tmp;
• It is interpreted not compiled, thus executes code
line by line and it makes python easy-to-debug and
suitable for beginners and advanced users

• When you install Python, you get everything i.e. you


don‟t need to install additional libraries. All
functionality is available with Python additional
library. Features like web-pages, database
connectivity, GUI features are available in Python
standard library.
• Python can run equally well on variety of platforms –
Windows, Linux/UNIX, Macintosh, supercomputers,
smart phones. Python is portable language.

• It is freely available i.e. without any cost can be


downloaded from www.python.org.
• It is also open source i.e. you can modify,
improve/extend an open-source software
Before we start working on Python we need to install
Python in our computer. There are multiple distributions
available today:
 Default Installation available from www.python.org is
called Cpython installation and comes with python
interpreter, Python IDLE(Python GUI) and
Pip(package installer).

 IDLE – Integrated Development and Learning


Environment
 It is Python’s built-in simple editor and interpreter
After Python installation we can start working with
python. In Python we can work in 2 ways:

Interactive Mode
(Immediate
Python Mode)
working
Ways
Script
Mode
The default installationof CPython comes with
Interpreter, Python IDLE and pip(package installer). To
Python
work in either interactive mode or script we need to
open Python IDLE

To work in interactive mode, follow the process given


below:
(i) Click start button  All Programs  Python 3.6.x
IDLE Or
Click start button  All Programs  Python 3.6.x Python
(command
line)
Interactive modes – one command at a time
Python executes the given command and gives the
output.
In interactive mode we type command at IiDLE

>>> 20(+>>> )
prompt (command give by user)
For
30 e.g if you type 20 + 30(output
in from of IDLE by
prompt
given
50 the above example
From python)
you can see than at >>>
we have to just give the command to execute and
python we execute it if it is error free otherwise
gives an error.
(
)
( ) )
( )
(

)
print
(“Hello”)
Script Mode – multiple commands can be saved in a
file as a
program and then we can execute the entire program
we type Python program in a file and then use the
interpreter to execute the content from the file.
Working in interactive mode is convenient for beginners
and for testing small pieces of code, as we can test
them immediately. But for coding more than few lines,
we should always save our code so that we may
modify and reuse the code
In Python IDLE :
Click File  New
In new window type the commands you want to save
in program
For example:
 print(“Hello World!”)

FileSave to save file. Give extension .py to


execute it as python script
Save the
program
and
press F5
( )
(
)
( ) )
( )
(

)
print
(“Hello”)
VARIABLES

A variable is a named storage location in the


memory whose value can change during
program execution. The data type of a variable
is determined by the type of data stored in the
variable.

CONSTANTS
A constant refers to a data value that remains
fixed. Its value does not change during the
execution of the program. They are of 2 types
Numeric and String constants.
Rules for Naming Variables in Python:
1. Start with a letter or underscore (_)
o Valid: name, _age
o Invalid: 1value
2. Can include letters, digits, and underscores
o Valid: student1, marks_total
3. Cannot start with a number
o ❌ Invalid: 2score
4. Cannot use Python keywords (like if, for, def, etc.)
o ❌ Invalid: class = "Math"
5. Are case-sensitive
o Name and name are different
6. Cannot contain special characters
o ❌ Invalid: total$, marks%
Good Naming Practices:
•Use meaningful names: marks_obtained, student_name
•Use underscores to separate words: total_marks
•Avoid single-letter names unless needed (like i in a loop)

✅ Examples of Valid Variable Names


name = "Aarav"
student_1 = "Riya"
_total = 95
score2023 = 89

🚫 Examples of Invalid Variable Names


1name = "Ananya" # Starts with a number

total-marks = 88 # Hyphen is not allowed

for = "Python" # 'for' is a keyword ❌
Activity:
Instructions: Identify which of the following are valid
Python variable names:
1.1student
2.student_1
3.for
4._marks
5.total-score
6.age
7.True
8.classroom
🎮 Mini Quiz (MCQs)
1. Which of these is a valid variable name?
A. 2total
B. total-marks
C. student_1
D. for
2. What will happen if you use a keyword as a variable name?
A. It will be ignored
B. Python will run normally
C. It will raise an error
D. It will be converted to string
3. What is the correct way to name a variable that stores total marks?
A. total marks
B. total_marks
C. Total.Marks
D. total-marks
Mini Quiz (MCQs)
1. Which of these is a valid variable name?
A. 2total
B. total-marks
C. student_1
D. for
2. What will happen if you use a keyword as a variable name?
A. It will be ignored
B. Python will run normally
C. It will raise an error
D. It will be converted to string
3. What is the correct way to name a variable that stores total marks?
A. total marks
B. total_marks
C. Total.Marks
D. total-marks
What are Keywords?
Keywords are reserved words in Python. They have special meaning and are
used to define the syntax and structure of Python programs.
You cannot use keywords as variable names. Python will show an error.
Why Are Keywords Important?
Keywords tell Python what kind of operation or action to perform. They are like
the grammar rules of the Python language.
🔍 Examples of Keywords
Keyword Purpose
if To create a condition
else To give an alternative condition
elif "Else if" for multiple conditions
for Looping through a sequence
while Repeats a block while condition is true
def To define a function
return To return a value from a function
True Boolean true value
False Boolean false value
break Exits a loop
continue Skips the current loop iteration
None Represents no value or null
Mini Quiz (MCQs)
1. Which of these is a Python keyword?
A. value
B. loop
C. def
D. function
2. What happens if you use a keyword as a variable name?
A. It will print nothing
B. It will give an error
C. It will work normally
D. It changes the keyword
3. Which keyword is used to stop a loop?
A. exit
B. stop
C. break
D. return
4. What is the output of:
if True: print("Yes")else: print("No")
A. Yes
B. No
C. Error
D. Nothing
Mini Quiz (MCQs)
1. Which of these is a Python keyword?
A. value
B. loop
C. def
D. function
2. What happens if you use a keyword as a variable name?
A. It will print nothing
B. It will give an error
C. It will work normally
D. It changes the keyword
3. Which keyword is used to stop a loop?
A. exit
B. stop
C. break
D. return
4. What is the output of:
if True: print("Yes")else: print("No")
A. Yes
B. NoS
C. Error
D. Nothing
INPUT STATEMENT:
To make the program interactive, it is required
to take the input from the user, for which input
statement is used.

Ex:
X= input(“Enter your name:”)

Python functions int(), float(), eval() are used


with input ().
PRINT STATEMENT:
Print statement is used to display information
on the screen.
A data type is the classification of data — like numbers, text, or
true/false values — that tells Python how to store and use the
value.

INTEGER
DATA TYPES FLOAT
STRING
BOOLEAN
“I can hold words, numbers, or nothing at all.
Sometimes I change, sometimes I don’t.
I help your programs store and play –

What am I?
LEARNING OBJECTIVES
end of this lesson, students will be able to:
tify and explain Python data types: None, String, Tup
d escape characters.
e and execute simple Python programs using these ty
erentiate
· between mutable and immutable data types

CONTENT/TOPIC:

DATA TYPES
 String
 Tuple
 List
 Escape Sequence Characters
DATA TYPES -
Example
Data Type Description Code Output

Represents
None absence of x = None print(x) → None
value
Text, written in
String quotes s = "Hello" print(s) → Hello

Special chars print("Line1 Line1


Escape Seq. like newline (\ \nLine2") Line2
n) or tab (\t)
Immutable
Tuple sequence t = (1, 2, 3) print(t[1]) → 2

Mutable l[0]=10; print(l) →


List sequence l = [4, 5, 6] [10, 5, 6]
None – Absence of Value
None is used to represent "nothing" or "no value yet".
· None is a special constant.
· It is the only value of the NoneType data type.
· It is often used to represent the absence of a value or a null
value.
• It’s like a blank field in a form. We cannot create None type of
variables.
• None can only be assigned to variables.

Example:1
A form where a user hasn’t entered their phone number yet.
phone_number = None # User skipped the field
print("Phone number:", phone_number)
Output:
Phone number: None

Example:2
x = None
print(x) # Output: None
print(type(x)) # Output: <class 'NoneType'>
String – Text Data
A string type of data (str) is used to store a sequence of characters and
numbers in single quotes or double quotes.
For multiline strings, use triple single quotes or triple double quotes.
Example:1
To store a student's name and welcome message.
student_name = "Aarav"
message = "Welcome to Python class, " + student_name + "!"
print(message)

Output:
Welcome to Python class, Aarav!

Example:2
text = """This is a
multiline string
in Python."""
print(text)

Output: This is a
multiline string
in Python.
Escape Sequence Characters -
Escape sequence characters are non printable characters which are used
for formatting the text in output. It is represented with a backslash.
Escape sequences like \n (new line) and \t (tab space) improve the
readability of output.

Example:1
print("Student Report:\nName:\tAnanya\nGrade:\t9")

Output:
Student Report:
Name: Ananya
Grade: 9
Escape Sequence Characters -

Escape Sequence Description Example Output


\\ Backslash \\ → \
\' Single Quote It\'s fine. → It's fine.
"He said, \"Hi\"" → He
\" Double Quote said, "Hi"
Hello\nWorld →
\n New Line Hello
World
Name:\tJohn → Name:
\t Tab (horizontal) John
Carriage Return (start of
\r Hello\rWorld → World
line)
\b Backspace Helloo\b → Hello
Escape Sequence Characters -
Example Output
Escape Sequence Description (Varies by system )

\f stands for form feed.It’s a


page break character that
historically told printers to
Form Feed (next page — rarely move to the next page.In
\f used) modern terminals and text
editors, it usually has no
visible effect — it's treated like
a whitespace or special
symbol.

print("Line1\vLine2")
\v Vertical Tab Line1
Line2
Bell/Alert (makes a beep
\a sound) May beep on terminal
Activity: “Poem or Poster” Using Multiline Strings
Objective:
Students will create their own poster, poem, or message using multiline
strings in Python, helping them:
• Understand triple quotes (''' or """)
• Format output across multiple lines
• Write in your notebook
• Use triple quotes to create a string that includes:
• A title (centered or highlighted)
• A message, poem, or quote spread across 3–5 lines
Activity: 1 “Poem or Poster” Using Multiline Strings
Example 1: A Motivational Poem
message = """
***************************
BELIEVE IN YOURSELF
***************************
Every coder was once a beginner.
With practice, bugs turn into breakthroughs.
Keep typing, keep trying!
"""
print(message)
Example 2: A Healthy Eating Poster
poster = """
=========================
EAT SMART, STAY STRONG
=========================
Add greens to every plate
Drink 8 glasses of water
An apple a day keeps the doctor away
"""
print(poster)
List :
What is a List?
• Mutable (can be changed)
• Ordered collection
• Allows duplicates
• Defined using square brackets
• Lists let you add, remove, or change items — perfect for tasks,
groceries, or any dynamic data.

Example:1
todo_list = ["Math homework", "Science project", "Read Python notes"]
todo_list[0] = "Complete Math homework"
print("Updated To-Do List:", todo_list)

Output:
Updated To-Do List: ['Complete Math homework', 'Science project', 'Read
Python notes']
LIST:
Example : 2
# Creating a list
fruits = ["apple", "banana", "cherry"]

# Accessing elements
print(fruits[1]) # Output: banana

# Modifying an element
fruits[0] = "mango"
print(fruits) # Output: ['mango', 'banana', 'cherry']

# Adding an element
fruits.append("orange")
print(fruits) # Output: ['mango', 'banana', 'cherry', 'orange']

# Removing an element
fruits.remove("banana")
print(fruits) # Output: ['mango', 'cherry', 'orange']
Tuple
A tuple contains an ordered sequence of values. The values can be of
mixed data types and they are separated by commas and are enclosed
with parentheses.
• It is immutable (cannot be changed)
• Ordered collection
• Allows duplicates
• Defined using parentheses ()
• Safer for fixed data.
• Faster than lists due to immutability.
Example:1
# Creating a tuple
colors = ("red", "green", "blue")

# Accessing elements
print(colors[0]) # Output: red

# Trying to change a value will raise an error


# colors[1] = "yellow" # ❌ Error: 'tuple' object does not support item
assignment

# Length of tuple
print(len(colors)) # Output: 3
Tuple with one element:
Example:
single_tuple = ("apple",) # ← notice the comma!
print(type(single_tuple)) # Output: <class 'tuple'>

Without the comma:


not_a_tuple = ("apple") # This is just a string
print(type(not_a_tuple)) # Output: <class 'str'>

Feature List ([]) Tuple (())


Mutability ✅ Mutable ❌ Immutable
Syntax [] ()
More methods (append, Fewer methods (count,
Methods
remove, etc.) index)
Slightly faster (due to
Speed Slightly slower
immutability)
When data should remain
Use Case When data can change
constant
SET:
✅ What is a Set?
• An unordered collection of unique items.
• Defined using curly braces {} or the set() constructor.
• No duplicates allowed.
• Useful for membership tests, removing duplicates, and set operations.

Example: 1
# Creating a set
numbers = {1, 2, 3, 4, 5}
print(numbers)
OUTPUT:
# Adding elements
numbers.add(6) {1, 2, 3, 4, 5}
print(numbers) {1, 2, 3, 4, 5, 6}
{1, 2, 4, 5, 6}
# Removing an element {1, 2, 4, 5, 6}
numbers.remove(3)
print(numbers)

# Duplicate values are ignored


numbers.add(2)
print(numbers) # 2 won't be added again
Set Operations :
Example: 2
a = {1, 2, 3}
b = {3, 4, 5}

print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}

Dictionary Data Type in Python


✅ What is a Dictionary?
• Key-value pairs
• Keys are unique, values can be anything.
• Defined using curly braces {} with a colon : between key and
value
.
Dictionary
Example: 1
# Creating a dictionary
student = {
"name": "John",
"age": 14,
"grade": "8th" OUTPUT:
} John
# Accessing values {'name': 'John', 'age': 14, 'grade': '8th', 'marks': 92}
print(student["name"]) # {'name': 'John', 'age': 14, 'grade': '9th', 'marks': 92}
John
{'name': 'John', 'grade': '9th', 'marks': 92}
# Adding a new key-value pair
student["marks"] = 92
print(student)

# Updating a value
student["grade"] = "9th"
print(student)

# Removing a key
del student["age"]
print(student)
ACTIVITY 2:
x = None
→ What type is this?

l = [10, 20, 30]


→ Can you add to this?

t = (1, 2, 3)
→ Can you change the second value?

Question Answer
NoneType – represents
1 absence of value
2 Yes – it's a list, use append()
3 No – it's a tuple (immutable)
ACTIVITY 3: (GROUP)
Code Comparison Challenge Activity
Goal:
• Identify if the data type is mutable or immutable
• Predict the output

# Code 1
colors = ["red", "green", "blue"]
colors[1] = "yellow"
print(colors)

# Code 2
shapes = ("circle", "square", "triangle")
shapes[1] = "rectangle"
print(shapes)

# Code 3
nums = [1, 2, 3]
nums.append(4)
print(nums)

# Code 4
days = ("Mon", "Tue", "Wed")
print(days + ("Thu",))
ACTIVITY 3: - ANSWERS

Code 1: List → ✅ Mutable


Output: ['red', 'yellow', 'blue']

Code 2: Tuple → ❌ Immutable


Error: 'tuple' object does not support item assignment

Code 3: List → ✅ Mutable


Output: [1, 2, 3, 4]

Code 4: Tuple → ❌ Immutable (but supports concatenation)


Output: ('Mon', 'Tue', 'Wed', 'Thu')
SDG GOALS-

SDG 13 – Climate Action:


Use lists and tuples to store and analyze temperature or pollution
data.
SDG 15 –
Life on Land: Use strings to label species; tuples for fixed
environmental data points.

REAL LIFE APPLICATIONS:


Shopping Carts: Stores the list of products a user has selected.
Task Management: To-do lists, where each task can be added or
removed.
Data Collection: Storing user responses, records of purchases, or
student grades.
Database Records: Tuples are used to represent database entries,
where the data is fixed and immutable.
Data Security: Used in applications that require fixed,
unchangeable data, like encryption keys.
• Integers are used in financial apps, gaming scores, and physical
measurements.
• Floats handle anything involving precision, like taxes or scientific
measurements.
• Strings are used for anything textual, such as user input,
messages, and web development.
• Booleans control flow for decisions, such as "yes/no" answers or
checking conditions.
• Lists and Tuples store ordered data, but only Tuples are
immutable.
• Sets deal with unique data, ensuring no duplicates.
• Dictionaries manage key-value pairs for more complex data
management.
• NoneType represents nothingness, used in cases of uninitialized
or missing values.

You might also like