0 ratings 0% found this document useful (0 votes) 24 views 15 pages Chapter-7 - Programming in Python
This document outlines the learning outcomes for a chapter on Python programming, focusing on statements, conditional programming, loops, and data structures. It introduces various types of statements, including assignment, expression, and compound statements, and explains how to use conditional statements and loops for decision-making and repetitive tasks. Additionally, it covers Python's built-in data structures such as lists, tuples, dictionaries, and sets, highlighting their properties and use cases.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Carousel Previous Carousel Next
Save Chapter-7- Programming in Python (1) For Later PROGRAMMING IN PYTHON
[EARNING OUTCOMES)
atthe end of this chapter, the students will be able to:
© understand different types of statements in Python.
«= Apply conditional statements in Python programs,
«= Implement iterative statements for repetitive tasks.
«= Explore and utilise various data structures in Python.
A Preview
(@®) Tippy: Hey Aliva! Ready to dive deeper into
‘
Pychon programming?
Aliva: Absolutely! I've been practicing the
basics we learned earlier. What's next?
;
Zippy: Today, we're going to explore more
advanced concepts in Python 3.12
We'll learn about different types of
statements, conditional programming,
loops, and some really cool data
structures!
Aliva: Sounds exciting! Lec’ get started!
DIFFERENT TYPES OF STATEMENTS
In Python, statements are instructions that perform specific actio
ns. They form the building
blocks of our programs. Let's explore some common types of statements:
1. Assignment Statements: These statements assign values to variables.
Example: x = 5
2. Expression Statements: These evaluate an expression and disc
ample: print("Hello, World!")
ard the result.
Programming in Pythonh
3. Compound Statements: These contain groups of other statements and contro} te
7
execution.
Examples: if statements, for loops, while loops, functions
“S
[7 trpes.ot statements py - D/Samunder Grewal/types.of statements py (3.124) — © ax
File E&t_Fermat_Run Options Window Help
[x = 200 “
lyn ss
atx
Princ (*x is greacer than y.")
ise:
print("x is net greater than y.")
U6 Cots]
A Desa =o x
[Preton 3.12.4 (eaaa/
vias:
Type “heip*, *copyet
x 45 qreacer whan y.
2 braces {} or keywords.
met
AX Computer studies -8
Fle Ede shex_Detug Options Window Help
© Python uses indentation to define
code blocks, unlike many other
© programming languages that use
jv3.12-4rBebatba, Jun € 2014, 19130116) [HSE ¥.1940 4 Dit (MDE) on «|
ight, “credits* or *License()* for more information.
RESTART: D:/Samundex Grewal/cypes_of_staceaents.py —
tee Cok6,
——-~--— [BEET
1. What is the purpose of an assignment statement?NALSTATEMENTS
Meacements are Tike decision-makers in
ail ed on different situations, just like hy
ot od? pe onditional statements allow our pro,
nt het aS follow an “if-then-else” logic, whic}
atl
peeing. The’
tions
Your code. They help your program choose
‘ow you decide what to wear depending on
grams to make decisions based on certain
h can be represented in a flowchart:
If statement flowchart
if (expression),
‘Statement(s)_
rest of code
spPrhon, we use 'f, ‘elif (else i, and ‘else’ statements for conditional execution. Here's a
ce eamprehensive example:
“python
#Get user's age
age = intlinput("Enter your age: "))
Determine ticket price based on age
ifege < 5:
price = 0
category
lif age < 13:
Price = 5
category = “child”
elf age < 18;
Price = 10
category = "teenager"
tif age < 69;
Price = 15
we ‘adult"
Price = g
“ategory
al “senior”
Programming in Python
124# Print the result a mo
print(f"You are a {category}. Your ticket price is $(pricel.")
# Additional check for special discount
if age == 50: oe
print("Congratulations! You get a special bi
rthday discount!")
{hr condiionai statements py - D/Semunder Grewal/conditional_statements py (3.124)
File Edit Format Run Options Window _Help
@ Get user's age
age = ine(inpur ("Enter your age: “))
# Determine ticker price based on age
Af age < 8:
price =
Category = “infant”
etic age < 13+
price = 5
Sategory = “cnia~
elit age < le:
price = 10
Category = “teenager”
ee 6Or
price = 15
Category = “edule”
elset
price = 0
Category = “senior”
# Print the resuie
print (eYou are a (category). Your ticket price 1s ¢(price).7)
# Addicional check for special discount
ie age == sor
DEAnt("Congratularions! You get a special bircnday discount?
Te IDLE She 2a
Fite 6 Shell_Debug Options Window Help
on vin32
Type “help, "copyright", "credits" or *license()" for more information.
>>>
= RESTART: D:/Samunder Grewal/conditional_statements.py
Enter your age: 17
You are a teenager. Your ticket price 1s £10.
>>>]
Python 3012.4 (eags/v3-12.4:0e0atba, Jun 6 2024, 19:30:16) [WSC v.1940 64 bic GuDEA) 4|
Se’
a Computer Studies - 8
te? Coedsted conditional statem
strates Ne ents and h y i
e ne decisions. ‘ow they can be used to categorise
yon
fast - ESE
e the output if the user enters 16 as their ager
fe b
wero
jon wold 0"
ab
jarive STATEMENTS
sce statements, also called loops, are like a repeating machine in your code. They let
| realise same thing over and over again without writing the same code multiple times, like
ad? «from 1 to 10 or checking each item in a lst. It allows us to repeat a block of code
sti Here are flowcharts for the two main types of loops in Python:
pute times.
FOR LOOP WHILE LOOP.
| 2ore we start learning about loops, we need to understand the Range( ) function. The
rage(l, 1) function in Python generates a sequence of numbers starting from 1 up to, but
tinduding, 11,
ead the explanation below regarding the working of Range( ) function:
\ The first argument, 1, specifies the starting value of the sequence, =
2 The second argument, 11, specifies the end value of the sequence, which is not included.
The sequence will increment by 1 by default.
"2ee(1, 11) will generate the numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10
ake
Programming in Python ai ts:
iteration statemen'
Nov, it's time to learn the
1. For Loop:
python
# Print a multiplicatio
number = int(input("Enter
print(f'Multiplication table
bl Co
os ae for multiplication table:
for (number):")
for i in range(1, 11):
result = number * i
print(f"{numberl x (i) = (result!")
[& multiplication. table.py - D/Samunder' GrewaV/multiplication table.py (3.124)
File Edit Format Run Options_Window Help
¥ Print a multiplication table
nunber = int (input ("Enter a nunber for multiplication table: ")) {
print ("Multiplication table for (number):")
for 4 in range(1, 12]
result = number * i
print (f"{number) x {i} = (result}")
.
ia Le Gat)
IDLE Shen 312A
Fie Edt Shell Debug Options Window Hep =) os)
Python 3.12.4 (tags/v3.12.4:008a!
Frees 3 2-428eGadba, Jun 6 2024, 19230316) [MSC v.1940 €4 bit GDH] |
Type "helps, “copyrighe®,
le crests or “lcente(* for wore snforncion
= RESTART: D:/Samunde: :
= RETO: pi/sumnte tern\mtistcaion snip
:
a
a
2
z
:
z
3
:
KKK
>>|
SEE
ey és
a Computer Studies - 8__tcrwelcome to the Number Guessing Game!")
mcm thinking of a number between 1 and 100,")
pn
ile True :
= egg = intinput("Take a guess:"))
attempts += 1
if guess < secret_number:
print("Too low! Try again.
if guess > secret_number:
print("Too high! Try again.")
else:
print({"Congratulations! You guessed the number in {attempts} attempts!")
break
[7p wie sutementpy - D/Semunder GrewaUwhile statement py (3.124)
Fie ESt Format_Run Options Window Help
F Guessing gene
sport random
‘teeret_number = random.randint (1, 100)
treapts = 0
His: ("Kelcone to the Number Guessing Gane!")
int ("I'm thinking of @ number between 1 and 100.")
Mite tee;
Guess = ine (inpuc (* 14
put ("Take a guess: *))
attempts += 1
‘f guess < secret_number:
euPE8 (Too low! Tey again.")
guess > secret_nunbe
exe 2!8€CToo hight Try
ine")
) acrenpts!")
Bilae(t*congratutationa! You gueased she musber $2 (ASSIS
Treat cot0)
Sele
Programming in Python a[A IDLE Shen 3.124 sy
File Eéit Shell Debug Options Window Help ®
Python 3.12.4 (taga/v3.12.4;8eGadba, Jun € 2024, 19230216) (HSC ¥.1840 ey Bye way |
on win32 ‘Ty
Type "help", "copyright", "credits" or “license()" for more information, f
>>o|
= RESTART: D:/Samunder Greval/unile_statenent-py
Welcone to the Nurber Guessing Gane’
I'm thinking of a number between 1 and 100.
Take a guess: 83
Too high! Try again.
Take @ guess: 23
Too high! Try again,
Take a guess: $5
Too high! Try again.
Take a guess: 8 |
Too low! Try again.
Take a guess: 70
Too high! Try again.
Take a guess: 15
Congratulations! You guessed the number in 6 atterpts!
>>>!
Lee 19” Coed)
-@
The ‘break’ statement in the while lo
7
Rea examples demonstrate how loops can be used example is used to exit the loop whe,
repeat actions (like creating a multiplication table) © the correct number is guessed. Python
or continue a process until a condition is met (like
n also has a ‘continue’ statement, which
guessing the correct number). skips the rest of the current iteration
|, and moves to the next one.
How would you modify the multiplication table code to print tables from 1 to 5?
1
1um of 10 guesses?
2. In the guessing game, how could you limit the player to a maxim
DATA STRUCTURES IN PYTHON
Data structures help us organise and store data efficiently. Python provides powerful ta
for efficiently organising and storing information. This section introduces four key built i
data structures: lists (ordered and mutable), tuples (ordered and immutable), dictions
(unordered key-value pairs), and sets (unordered collections of unique items), each with i!
own unique properties and use cases.
Set
AX Computer studies - 8
=getsiled description of the built-in data structures:
were, mutable collections of items, a
, "banana", "cherry"]
s¢iruits(0)) # Outputs: apple
sppondt date")
.) # Outputs: ["apple’, “banana”, ‘cherry’, “date*]
fered, immutable collections of items.
sits
ne
print
(10, 20)
penqcoorinatest1D # Outputs: 20
s: Unordered collections of key-value pairs.
3 pictionarie
gxomple:
tudent{"name"]) # Outputs: Alice
name": "Alice". "age": 14, "grade": 8}
4 ste Unordered collestions of unique items,
Example:
saigue_numbers = {1, 2, 3,3,4,4, 5)
intanigue numbers) # Outputs: 1, 2, 3, 4, 5)
Poeser324 = oF x
fe EX Shel Debug Options Window _Help
Fries 9012-4 (tags/v3-12.420e0a¢ba, Jun 7308
e a3 C200, 1901) TSC VIS GF bie DENT A
Se ‘help*, "copyright", "credits or "License()" for more informa:
ooitmuite = (Tepple", "banana", "chezry"]
>» grist traits(01)
rae
>» seus append ("date")
on) price (trutesy
jpllltslet, ‘banana’, ‘cherry, ‘dace*]
ies cat}L
dow Help
¥3.12.
Re
fon wins?
>>>] coordinates= (10,20)
>>>] print (coordinates (11)
20
Type "nelp*, “copyright®, "eredite* oF
tba, Jun @ 2024, 1919016) (HSC v.1940 64 bie egy
“
License ()" for more information,
— Ea
LE Shell 3.124
Fle Edt Shet_ Debug Option Window Help
Python 3.124 (eage/ya. 12.428
on wind
‘Type “hetp*, “copyright, “create,
doo] studente(nane" rraliee
>o>| print (stodent ["nane*})
Baace
>>|
jasba, Jun 6 2024, 19130116) (MSC v.1940 64 bic (umDea)) —,|
192114, "arade":0)
Soe
or "License()* for more information.
eco}
TA IDLE She 3.124
Fie Eét Shel Debug Options Window Help
on win32
‘Type “he1p*
>>>| unsque_numbers=(1,2,3,3,4,4,5)
>>> | print (unique_numbers)
(1, 2, 3 4, 5)
>>>]
Python 3.12.4 (tags/v3.12.4:8eGatba, Jun 6 2024, 19:30:16) (HSC v.1940 €4 bit (AMDEA)] Al
"copyright", “credits* or "License()" for more information.
- oO x!
a Computer Studies - 8
Le6_cot)y ee EE
main difference between a list and a tuple?
the i
1 nes
rede co experiment with diferent data structures by creat :
ee sends on approach will help solidity ther meee small programs that utilise
(prs Look BACK
“a py uses indentation to define code blocks.
cents (if, elif, else) allow programs to make decisions.
“4 Conditional statern
rte are used when the numberof iterations is known in advance
1 lops repeat as long, as a condition is true.
“tesa mutable ordered collections of items.
“sles ae immutable, ordered collections of items.
| + diionares store key-value pairs.
fem unordered collections of unique items.
tn
SE sor
ld
“ee ae
fany online platfo
1 help reinforce the once
to practice Python programming regularly M
beginners. This consistent practice will
Programming in PythonA. Multiple Choice Questions (MCQs)
1. Which of the following is not a type of statement in Python?
a. Assignment b. Expression c, Compound d. Paragraph
2. What does the ‘elif keyword stand for in Python?
a. Else if b. Else in loop c. Else input d. End loop ig
3. Which loop is used when you know the number of iterations in advance?
a. While loop b. For loop c. Do-while loop 4. Repeat loop
4, What data structure in Python stores key-value pairs?
a. List b. Tuple c. Dictionary d. Set
5. Which of these is a mutable data structure in Python?
a. Tuple b. String c. List d. Integer
B. Fill in the blanks with one word.
1. Python uses . to define code blocks.
. statement is used to exit a loop prematurely.
is an ordered, immutable collection of items in Python.
_ function in Python generates a sequence of numbers.
__ is an unordered collection of unique items in Python.
C. Match the following:
Column I Column II
1. if-elif-else a. Iterative statement
2. for loop b. Unordered collection
3. List c. Conditional statement
4 d. Ordered, mutable collection
e. Key-value pairs
. Dictionary
5, Set
D. Short Answer Type Questions
L Explain the difference between a ‘for’ loop and a ‘while’ loop in Python.
2. What is the purpose of conditional statements in programming?
sa
BX computer Studies -8oq a dictionary differ from a list in Python?
. in
cacor Type Questions
yon "9 the concept of nested conditional E
fae peseribe I statements with an example.
: pai how you would use a ‘for’ loop to create a simple number guessing game in
on.
3, Compare and contrast the four main data structures in Python: lists, tuples, dictionaries,
and sets.
E Application Based Questions
1 Write a Python program that uses a ‘whill
all even numbers from 1 to 20.
J! loop to calculate the sum of GAGE)2. Create a Python program that uses a dictionary to store and display
information about your favorite books (title, author, year).
3. Design a program that uses conditional statements to determine if a given &
year is a leap year or not.
G. Case Study Based Questions
Directions (Questions 1 to 2): Examine the following case study carefully and answer ty
questions that follow:
You are designing a simple quiz game using Python. The game should ask the playy
5 multiple-choice questions, keep track of their score, and display the final result.
1. How would you structure this program using the concepts learned in this chapter?
2. Describe the data structures and control flow you would use.
H. Assertion-Reason Type Questions
Directions (Questions 1 to 2): In each of the following questions, a statement: of Assertion
(A) is followed by a statement of Reason (R). Study both the statements and state which ofthe}
following options is correct.
1. Assertion (A): Python uses indentation to define code blocks.
Reason (R): Indentation in Python is optional and doesn’t affect the program's executie | |
a, Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct
explanation of Assertion (A).
b. Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct
explanation of Assertion (A).
c. Assertion (A) is true, but Reason (R) is false.
d. Assertion (A) is false, but Reason (R) is true.
LY Computer studies -8(ay: Tuples in Python are immutable.
tio® \ ghe items in a tuple cannot be changed :
2 erertion (A) and Reason (R) are true, and Rencent a a
ph focion of Assertion (A).
ex? ‘Assertion (A) and Reason (R) are true, but
p Both? “tion of Assertion (A).
esplani™n (A) is true, but Reason (R) is false.
'A) is false, but Reason (R) is true.
Reason (R) is not the correct
eo
gases
jects 7
H , ve ate pasic calculator program that can perform addition, subtraction,
cra ation, and division based on use input.
mi
celop a program that simulates a simple inventory management system)
2 ‘mall store, using appropriate data structures to store and manipulate ~~
product information.
yer with aiflerent loop structures to generate various patterns ofastershs (+) on
t
ge soeen- .
(tea program that reads alist of numbers from the user and uses data structures to find
2 ehighst. lowest, and average values.