0% found this document useful (0 votes)
24 views22 pages

Class 9 Part B - Lesson 5 - Intro. To Python

Uploaded by

mang.yash10
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)
24 views22 pages

Class 9 Part B - Lesson 5 - Intro. To Python

Uploaded by

mang.yash10
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
You are on page 1/ 22

(1) Algorithms

 An algorithm is a clear, logical, step-by-step method designed to solve a specific


problem.
 Example: Algorithm to prepare tea –
1. Boil water.
2. Add tea leaves.
3. Add sugar and milk.
4. Boil for 2–3 minutes.
5. Filter and serve.

(2) Flowcharts

 A flowchart is a diagram that shows the steps of an algorithm using symbols.


 Common symbols:

Common Flowchart Symbols


Symbol Meaning
⬛Oval/Ellipse Start / End
▭ Rectangle Process / Instruction
⬛Diamond Decision (Yes/No or True/False)
⬇⬛Arrow Flow of Control
⬛Parallelogram Input / Output

Flowchart for Finding Area of a Rectangle


Algorithm:

1. Start
2. Input length and breadth
3. Calculate Area = length × breadth
4. Print Area
5. End
(3) Introduction to Programming

 Programming = Giving instructions to a computer to perform a task.


 Programming Language = A programming language is a structured set of words and
symbols that enables people to communicate instructions to a computer.
 Program = It is essentially a series of instructions written in programming language.

(4) Introduction to Python

 Python is a high-level, interpreted, general-purpose language.


 Created by Guido van Rossum in 1991.
 Simple, easy to learn, widely used in AI, data science, web development.

(5) Features of Python

1. Simple & Easy – Syntax like English, beginner-friendly.


2. Interpreted – Runs line by line, no compilation needed.
3. High-Level – Focus on logic, not hardware.
4. Free & Open Source – Anyone can use and modify.
5. Cross-Platform – Works on Windows, Linux, macOS, Android.
6. Large Libraries – Built-in + third-party modules.
7. Object-Oriented – Supports classes & objects.
8. Dynamically Typed – No need to declare variable type.
9. Portable – Same code works on different systems.
10. Extensible – Can integrate with C, C++, Java.
11. GUI Support – Libraries for graphical apps.
12. Wide Applications – AI, ML, Web, Data Science, IoT, etc.

(6) Applications of Python

 Web development (Django, Flask)


 Data science and AI (TensorFlow, Scikit-learn)
 Game development (Pygame)
 Automation and scripting
 GUI development
 Business Application
 Audio or Video-based Application
 3D – CAD Application
 Image Processing Applications

(7) Limitations of Python

 Slower than C/C++ because it is interpreted.


 Uses more memory.
 Not ideal for mobile app development.
 Restricted Database Access

(8) Why the name Python?

 Guido van Rossum named it after the popular BBC comedy series “Monty Python’s
Flying Circus”. It was late on-air 1970.

(9) First Python Program


print("Hello, World!")

(10) Python provides us the ways to run/execute a program

(a) Using Interactive Mode

(b) Using Script Mode


Feature Interactive Mode Script Mode
Execution Line by line Whole program at once
Best for Small testing, calculations Writing large programs
Saving Code Not saved automatically Code is saved in .py file
Output Immediate After running the script

(11) Python IDLE

 IDLE = Integrated Development and Learning Environment.


 Comes with Python installation.
 Used to write, run, and debug programs.

(12) Python Character Set – A character set consists of a set of valid characters which
can be recognized by a language.

 Letters (A–Z, a–z)


 Digits (0–9)
 Special symbols (+, -, *, /, %, etc.)
 Whitespaces (tab, space, newline)
 Characters – ASCII & Unicode.

(13) Python Identifiers

 The identifiers are the words or names given to different objects such as variables,
functions, classes, etc.
 Rules:
o Cannot start with digit, ALWAYS START WITH A ALPHABETS.
o No special character other than underscore ( _ ) is allowed.
o Space is not permitted.
o Keywords cannot be used as identifiers.
o Identifiers can be of any length.
(14) Punctuators

 The Punctuators referred to as separators in some programming language are like


punctuation marks.
 Examples:
o : (colon)
o , (comma)
o () (parentheses), [] (square brackets), { } (Curly bracket)
o @ (at the rate)
o . (Dot)
o = (Assignment)
o / (Forward Slash)
o # (Hash Sign)
o Quotes  ‘ (single quote), “ (double quote)

(15) Keywords

 Predefined reserved words with special meaning. Total keywords in Python 3.12 is 36.

Keyword Meaning / Use


False Boolean value for false condition
True Boolean value for true condition
None Represents null value / no value
and Logical AND operator
or Logical OR operator
not Logical NOT operator
if Conditional statement
elif Else-if condition
else Alternative condition in if-else
while Looping (repeat while condition is true)
for Looping (iterate over sequence)
break Exit loop immediately
continue Skip current iteration and continue loop
pass Do nothing (placeholder statement)
def Define a function
return Return value from a function
lambda Create anonymous (inline) function
class Define a class
yield Used with generators to return values one by one
try Start of exception handling block
except Handle exceptions (errors)
finally Block that always executes in try-except
raise Raise an exception (error)
assert Debugging aid, checks condition
import Import a module
from Import specific part from a module
as Create alias (nickname) for module/object
global Declare global variable inside function
nonlocal Declare non-local variable inside nested function
del Delete object/variable
is Identity operator (checks if two objects are same)
in Membership operator (checks if value is in sequence)
with Context manager (resource management)
async Define asynchronous function
await Wait for asynchronous result
match Pattern matching (like switch-case)
case Used with match for pattern checking

(16) Indentation in Python

 Python uses indentation (spaces/tabs) instead of braces {}.


 Example:

if 5 > 2:
print("Five is greater")

(17) Statements in Python

 Simple statement: Executes once → print("Hello")


 Compound statement: Includes conditions/loops → if, while

(18) Comments in Python

 Used to explain code, ignored by interpreter.


 Single-line: # This is a comment
 Multi-line: """ This is a multi-line comment """

(19) Python Data Types

 A data type tells what kind of value a variable can hold.


 It defines the operations that can be performed on that value.
(20) Data Type Conversion

 Changing one data type into another is called type conversion.


 In Python, this can be done in two ways:
o Implicit Type Conversion / Type Promotion. (Type Casting by Python)
o Explicit Type Conversion / Type Casting. (Type Casting by Programmer)
 Example:

x = int("5") # string to int


y = float(10) # int to float

(21) Python Variables

 A variable is a name given to a memory location where data is stored.


 It acts like a container that holds values.
 In Python, you don’t need to declare the type of variable (Python is dynamically
typed).
 Example:

name = "OPTIMUS"
age = 18

(22) Python Operators  An operator is a special symbol that performs an operation


on values (operands). [for more details – page no.- 137 to 139]

 Arithmetic :  + - * / % ** //
 Relational (or) Comparision :  == != <> > < >= <=
 Logical :  and or not
 Assignment :  = += -= *= /= %= **= //=

(23) What is Operator Precedence? [for more details – page no.- 140 & 141]

Precedence decides the order in which operators are evaluated in an expression.

(24) Accepting User Input & Displaying Output

 Input ( )  Python accept input from a user and used it in the programs.

Example  name = input("Enter your name: ")

 Output ( )  The output is displayed in a python program using the print ( ) function.

Example  print("Hello,", name)


(25) Flow of Control and Conditions

WHAT IS CONDITIONAL STATEMENT? –

 Conditional statements are used to make decisions in a program.

 They execute a block of code only if a certain condition is true.

Types of Conditional Statements in Python :

1. if
2. if–else
3. nested if
4. if–elif–else

WHAT IS BLOCK IN PYTHON? –

 A block is a group of statements that belong together and are executed as a unit.

 In Python, a block is defined by indentation (spaces or tabs at the beginning of a line).

if statement

 An if statement is used to check a condition.


 If the condition is True, the block of code inside if executes.
 If the condition is False, the block is skipped.

if–else

 The if–else statement is used to check a condition.

 If the condition is True → the if block executes.

 If the condition is False → the else block executes.


nested if

 A nested if means an if statement inside another if statement.

 The inner if executes only when the outer if is True.

 Used when we need to check multiple conditions in a hierarchy.

if–elif–else

 The if–elif–else statement is used when we need to test multiple conditions.

 It checks conditions one by one from top to bottom.

 As soon as one condition is True, its block executes and the rest are skipped.

 If none of the conditions are True → the else block executes.

Statement Definition Paths/Conditions When to Use


if Executes a block only if 1 path (True case only) When you only care
condition is True about one condition
being True
if–else Executes one block if True, 2 paths (True / False) When you need to
another if False handle both True &
False cases
nested if An if inside another if. Multiple levels of When decisions depend
Inner runs only if outer is conditions on hierarchy / multiple
True steps
if–elif– Checks multiple conditions Many alternative paths When you have several
else in sequence. Executes first (1 True chosen) options to choose from
True block
Quick Summary

(26) Iterative Statements (or) Loops

They are used to repeat a block of code multiple times until a condition is met.

Loops are used to avoid repetition of code and make programs shorter, cleaner, and efficient.

1. for loop → Executes block for a fixed number of times / over a sequence.
2. while loop → executes block as long as condition is True.

3. do–while loop → executes block at least once, then checks condition (not directly in
Python, but can be simulated).
for loop using Function

(27) Python Lists


A list is a collection of ordered, mutable, and heterogeneous elements.

 Ordered → elements maintain sequence.


 Mutable → can be changed (add, remove, update).
 Heterogeneous → can store different data types (int, float, string, etc.).
MCQs
⬛ MCQ Questions with Answers

1. Python was developed by:


a) Charles Babbage
b) Guido van Rossum
c) Dennis Ritchie
d) James Gosling

2. Which symbol is used for comments in Python?


a) //
b) #
c) /* */
d) --

3. Which of the following is NOT a Python keyword?


a) elif
b) lambda
c) main
d) while

4. Which of the following is an immutable data type in Python?


a) List
b) Tuple
c) Dictionary
d) Set

5. What will be the output of:

print(2 ** 3)

a) 6
b) 9
c) 8
d) 23

6. Which function is used to take user input in Python?


a) scanf()
b) cin
c) input()
d) read()

7. Which operator is used for floor division in Python?


a) /
b) //
c) %
d) **

8. What is the default data type of input() function in Python?


a) int
b) str
c) float
d) bool

9. Which of the following is NOT a Python IDE?


a) IDLE
b) PyCharm
c) Jupyter
d) NetBeans

10. Which of the following is a logical operator in Python?


a) and
b) or
c) not
d) All of the above

1. Who is the creator of Python?


Guido van Rossum.
2. Write the extension of a Python file.
.py
3. What is the use of # in Python?
It is used to write comments.
4. Give one example of a keyword in Python.
if, while, else (any one).
5. Which function is used to take input from the user in Python?
input()
6. Write the output of:

print(5 > 3)

True

7. Name any one Python operator.


+ (addition) or * (multiplication).
8. What is indentation in Python?
Indentation means spaces at the beginning of a line used to define blocks of code.
1. Differentiate between keywords and identifiers in Python.
Keywords: Reserved words with special meaning (e.g., if, for).
Identifiers: Names given to variables, functions, classes by the user.
2. Write two applications of Python.
Web development, Data Science, Artificial Intelligence, Game development (any
two).
3. What do you mean by flowchart? Why is it useful in programming?
Flowchart is a diagrammatic representation of steps in a program.
It helps in visualizing the logic before coding.
4. Write a Python program to check whether a number is even or odd.

num = int(input("Enter a number: "))


if num % 2 == 0:
print("Even")
else:
print("Odd")

5. Give two differences between comments and statements in Python.


Comments are ignored by Python interpreter, statements are executed.
Comments begin with #, statements are written normally.
6. Explain type conversion in Python with an example.
Changing one data type into another.
Example:

x = "10"
y = int(x) # converts string to integer

1. Explain any three features of Python.


o Easy to learn and use.
o Interpreted language (line by line execution).
o Portable and platform independent.
2. Write a Python program to find the largest of three numbers using if-elif-else.

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:


print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)

3. Differentiate between mutable and immutable data types in Python with


examples.
o Mutable: Can be changed (e.g., List [1,2,3]).
o Immutable: Cannot be changed (e.g., String "hello", Tuple (1,2,3)).
4. Write a short note on Python IDLE.
IDLE (Integrated Development & Learning Environment) is the default IDE for
Python.
It provides an editor, shell, and debugger to run programs easily.
5. What are punctuators in Python? Write any three examples.
Punctuators are symbols that structure code. Examples:
o : (colon)
o , (comma)
o () (parentheses)

1. Explain the different data types in Python with examples.


o int → whole numbers → x = 10
o float → decimal numbers → y = 3.14
o str → text → name = "AI"
o bool → True/False → z = True
o list → ordered collection → [1,2,3]
o tuple → immutable collection → (4,5,6)
o dict → key-value pairs → {"name":"John", "age":15}
2. Write a Python program to calculate the grade of a student based on marks.

marks = int(input("Enter marks: "))

if marks >= 90:


print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Grade D")

3. What are operators in Python? Explain Arithmetic, Relational, and Logical


Operators with examples.
o Arithmetic: +, -, *, / → 5 + 3 = 8
o Relational: <, >, == → 5 > 3 = True
o Logical: and, or, not → (5>3 and 3>2) = True
4. Write a program to calculate income tax according to given rules.

income = int(input("Enter income: "))

if income <= 250000:


print("No Tax")
elif income <= 500000:
print("Tax:", income * 0.05)
elif income <= 1000000:
print("Tax:", income * 0.20)
else:
print("Tax:", income * 0.30)

5. Explain the flow of control statements in Python with examples.


o if statement → executes block if condition is true.
o if x > 0: print("Positive")
o if-else → executes one block if condition true, another if false.
o if-elif-else → selects one block among many conditions.

You might also like