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

Python for Kids_ a Story Based Learning

The document 'Python for Kids' by Lokesh Gajula introduces young readers to Python programming through a narrative about a boy named Yash who moves to a new city and learns programming with the help of his friend Akhil. It covers fundamental concepts such as variables, data types, algorithms, and the importance of Python as a user-friendly programming language. The story is interspersed with technical explanations and exercises to engage children in learning Python in a fun and interactive way.

Uploaded by

saladin.ahmmed
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)
26 views

Python for Kids_ a Story Based Learning

The document 'Python for Kids' by Lokesh Gajula introduces young readers to Python programming through a narrative about a boy named Yash who moves to a new city and learns programming with the help of his friend Akhil. It covers fundamental concepts such as variables, data types, algorithms, and the importance of Python as a user-friendly programming language. The story is interspersed with technical explanations and exercises to engage children in learning Python in a fun and interactive way.

Uploaded by

saladin.ahmmed
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/ 211

PYTHON FOR KIDS

Lokesh Gajula

1
Contents
CHAPTER 1: INTRODUCTION........................................................................................................3
CHAPTER 2: WHAT IS PYTHON PROGRAMMING? ........................................................................6
CHAPTER 3: VARIABLES AND SIMPLE DATA TYPES. ....................................................................19
CHAPTER 4: STRINGS .................................................................................................................35
CHAPTER 5: LISTS ......................................................................................................................48
CHAPTER 6: WORKING WITH LISTS ............................................................................................60
CHAPTER 7: TUPLES AND DICTIONARY ......................................................................................73
CHAPTER 8: LOOPING IN PYTHON .............................................................................................86
CHAPTER 9: FUN WITH PYTHON .............................................................................................. 101
CHAPTER 10: DRAWING WITH PYTHON ................................................................................... 123
CHAPTER 11: IF STATEMENTS .................................................................................................. 142
CHAPTER 12: FUNCTIONS ........................................................................................................ 161
CHAPTER 13: CLASSES ............................................................................................................. 179
CHAPTER 14: CONCLUSION ..................................................................................................... 198

2
CHAPTER 1: INTRODUCTION.

In a small, beautiful village, there lived a jolly, light-hearted


12-year-old kid named YASH. Yash is a well-cultured boy,
who lives with his parents and knows to respect elders. He
is a good student who takes interest in learning new things.
One day Yash’s father got a job in the nearby city. So, it
was decided that they would move to that city and start a
new living. This made young Yash very sad as he was
habituated to his village and friends. As he had no choice,
with a heavy heart he left the village. The city had a
completely new environment, where the vehicles packed the
broad roads and the huge buildings cover the whole city.
Everyone and everything moved fast. There were no trees,
no lakes. Yash felt as if he entered a new planet.

YASH

Yash’s father rented a new house near the MAIN School which was close to his
working place. After few days, everyone got settled and got used to the new place.
Yash’s father decided to join Yash in the MAIN School, which is the best school in
the city. Everyone in the city knew about this school. Yash was excited to go to his
new school to learn new things, which he loves doing. One Monday morning, Yash
and his father went to the school and got a new admission.
Yash got his new uniform, books and stationery and decided to
go to school on Tuesday.

Tuesday morning, Yash woke up early excited for his


big day at school. He wore a pressed clean uniform with
polished shoes. Around 9AM, Yash’s father dropped him at the
school. Yash entered the class room and found the class full of
students. He was a bit nervous and shy, but he decided to act
normal and sat on the first bench. Beside him was a boy named
AKHIL.
Akhil is an easy-going, charming, helping, and apparently, the
brightest student in the class who loves to make new friends.

3 AKHIL
Akhil introduced himself to Yash and soon they became friends. They shared their
stories, where they came from, what their parents were, which cartoons they like,
everything with each other. They soon became close friends.
In the same class, there was a kid named DANY. He was smart but a
troublesome and annoying kid. He likes to tease and criticize others.

MAIN School had appointed a teacher for the newly introduced


computer science subject. The new teacher loved kids and tried to make
learning a fun activity for them. On that fine day, it was her first period
in Yash's class where she gave an introductory lecture about computer
science for an hour. The students loved her teaching style and were
thoroughly enjoying the subject. As the class concluded she announced
that she will be conducting a PYTHON assessment and the reward for
topping the exam would be a personal computer.
This got the students excited about the test. They were all talking
to ace the exam and get that personal computer the teacher said she
would give. Akhil had an edge in this regard as he knew well about
python programming because, it was his father who taught him the
subject. Meanwhile, Dany saw this as an opportunity to bully Yash and
started demeaning Yash for being a village kid and not knowing the
subject. He then went on to challenge Yash to beat him in the
DANY
assessment.

Yash felt very discouraged and disappointed. Seeing Yash sad, Akhil offered to
help him in this regard. Yash and Akhil decided to top the assessment and teach Dany
a lesson.
Dany was no less competitive, he sorted to homeschooling for python programming
from a private tutor.

4
Note:
• To see the learning progress of Yash, Akhil and Dany, let’s create a new ability
called Python Learning (0/100).

• With every new topic, concept learned, python learning score will increase.
• One who reaches 100 points first will top the assessment.

• All the three members python learning score will be shown on top of each
page.

5
CHAPTER 2: WHAT IS PYTHON PROGRAMMING?

One Sunday, Yash went to Akhil’s house to start learning python programming. Akhil
invited Yash inside and the conversation goes like this…

Akhil: Hey Yash! Let’s get started with python programming. Come and sit next to
me.
Yash: Sure. Let’s go.
Akhil: First, you need to know few programming terms to get started. Here is the list.
1. Code/Computer Program
2. Algorithm
3. Bug
4. Compilation
Let’s understand these one by one.
Yash: Sure, Let’s start with Code/Computer Program.
Akhil: Right! It is the building block of everything.
Code/Computer Program is a set of instructions that we give to a computer to tell it
what to do. These are the commands we give to a computer.
Yash: Great! What kind of commands can we give to a computer?
Akhil: Anything you wish for. Like...
• We can create web pages
• Play music
• Draw new stuff
• Create games
• Even do your homework

6
Yash: Amazing. So, if I just tell the computer what kind of game I want to create, it
will create it for me. Right?
Akhil: Yes, But not so fast.
Just like we humans use language to communicate, so do computers. We must give
these instructions to the computer in a language they understand. This language is
called a programming language.
Yash: Cool! So, PYTHON is a programming language. Are there any other
programming languages?
Akhil: There are lots of programming languages that you can use.
C, C++, Java, MATLAB and quite popular one these days is PYTHON.
Yash: So, that’s the reason why everyone is learning python. But, why is python so
popular?
Akhil: That’s a good question. There are number of things that make python
extremely useful for coding, mainly for beginners.
Quick & Efficient.
Doesn’t require the use of a lot of complicated syntax or symbols like ($,//,#....) while
writing the code.
User Friendly.
It’s easy to learn. It has an interactive shell, in which you can enter programs and run
them.
Turtle Module(drawing) for kids.
Many more services like graphics, Data Science, Deep Learning, Artificial
Intelligence (AI), Data Analysis, Web Mining, Cyber Security etc.
Yash: Oh My God! All these features in python?
Akhil: Yes! Absolutely.

7
Good that you understood the importance of python programming. Let’s see few more
technical terms.
Yash: Sure, what is an Algorithm?
Akhil: An algorithm is a set of instructions or rules designed to solve a definite
problem. We write code for algorithms. Algorithms are the backbone of every
program.
Algorithms help you understand simple problem like adding two numbers to complex
problem like converting speech to text.
Yash: Ohh! I guess algorithms are important. Can you give some examples of
algorithms?
Akhil: Sure! Some standard algorithms include
1. Sort Algorithms
• Merge Sort
• Quick Sort
• Selection Sort
• Bucket Sort
• Heap Sort
• Counting Sort
2. Search Algorithms
• Binary Search
• Depth/Breadth first search
3. Hashing
4. Dynamic Programming
5. String Algorithms
• KMP Algorithm
• Regular Expression
These are some of the standard algorithms. Don’t worry about all these new names,
you will know more about Data Structures and Algorithms as you learn programming.
Just remember that these are some standard algorithms.

8
Yash: Sure! What next?
Akhil: Let’s see what a Bug is.
Yash: BUG!!!!
Akhil: Don’t worry! It’s not a living thing.
A BUG is a general term used to denote an unexpected error or defect in hardware or
software, which causes it to malfunction.
It is a good practice, to invest time in the process of finding bugs before programs are
rolled out for their application. This process is known as testing.
Yash: It seems like BUG’s create a lot of trouble.
Akhil: Sure, they do, but with proper precaution we can prevent them.
Yash: OK! I will take care of my bugs.
Akhil: Let’s see what compilation mean.
Compilation is the process of creating an executable program through code written in
a computer program language. Through compiling, the computer can understand and
run the program without using the programming software used to create it. A compiler
is a program that translates computer programs written using letters, numbers and
characters into a machine language program.
An example of a compiler in C++.
Yash: Awesome. I feel like, computer science is not so hard, after all.
Akhil: Computer Science is an interesting field. With interest everyone can be an
expert.
Yash: Yes, please continue.
Akhil: With this knowledge we can dive into real programming.
To do python programming, we need python installed in out computer. Let’s see how
to install python.

9
Yash: Yeah…
Akhil: If you have WINDOWS on your computer, you must go to your web browser
and enter
https://www.python.org/

And press enter.


You will see a new web page like this. Click on downloads and select the latest
version of python 3 available. Once the windows installer has been downloaded,
double click the icon, and follow the installation instructions.
Make sure you note down which directory it installs python in.

10
After the installation, you should have a python3 entry in your start menu.

11
The python default installation automatically installs the IDLE shell for you.
IDLE Shell is an interactive environment. It allows you to experiment and edit text. It
is ideal for python coding. IDLE stands for Integrated Development Environment.
Yash: Why is that ideal for python?

Akhil: For starters, it provides you an editor window where you can type your code
and save it.
It also allows you to copy paste and do things that most word processors do. By that, I
mean it make sure you write your code in the correct python format. So, once you’ve
installed python on your system, you can just navigate to your python folder from the
start menu and click on IDLE.

12
Yash: Ok, but what if I’m using a MAC.
Akhil: To get the Mac OS version, you must go to
https://www.python.org/getit
on your browser and download the installer the same way. And if you have
UBUNTU/LINUX, chances are pythons already installed, but it may be an older
version. To get the latest version, you click on the button for Ubuntu software center
on the side bar. Enter python in the search box on the top right corner and select the
latest version of IDLE from the list of software.
Finally click install.
That’s it, DONE.
Now that you have python installed and you’ve opened the IDLE, you’ll see
something like this.

13
The one with three greater than (>) symbols is called prompt. It let’s you know that
you can start typing your commands from here.
Yash: Awesome, Let’s give some commands to the computer.
Akhil: Sure.
Let’s do the traditional Hello World program.
Just type – print(“Hello World!”) in the prompt.
Let’s understand what this line of code means. Here, we are trying to print Hello
World. We need to give message/text in double quotes (“ ”) to print function to print
the message/text. So, this line of code is responsible for printing whatever is placed
inside the double quotes of print function.
Yash: Let me try.
Entering…….
Now, I need to press return key.

14
Hurrah!! Hello World is displayed.
Akhil: This is what a command looks like Yash. You just commanded the computer
to print “Hello World!” and it did it.
It gave you a result. This result is called the output.

Notice that the prompt reappears after the output.


This is to let you know that the python shell is ready to accept more commands. Now
let’s save what you wrote, to use it later. Simply, click on file option and then save.

15
Yash: Super! I wrote my first python program. Thank you very much AKHIL.
Akhil: Not me, thank yourself. It’s your interest and desire that made you to start
learning python. Good Job. You should be proud of yourself.
I think this is good for today. Let’s learn more python tomorrow.
Yash: Sure! Excited as always.

16
Exercise:
1) What is Python?
a) A Game
b) A Human Language
c) A Computer Language
d) A Command
e) An Instruction
2) What is a BUG?
a) An Insect
b) A Fly
c) A Program
d) An Unexpected Error
e) A Language
3) What are the advantages of python?
a) Data Science
b) Web Development
c) Game Development
d) Artificial Intelligence
e) All the above
4) What is IDLE?
a) An Interactive Environment
b) A Text Editor
c) Integrated Development Environment
d) A Word Processor that can detect errors
e) All the above
5) How do you print “Hello World!”?
a) printf(“Hello World!”);
b) print(Hello World!);
c) print Hello World;
d) print(“Hello World!”);
e) show(“Hello World!”);
6) Write a python program to print your name.
7) Write a python program to print about your friend.

17
Fun Fact:

Python Was a Hobby Project:


What if I tell you, Python was not created as a commercial or a professional project,
and rather, it was a hobby project of the creator? Python’s creator Guido van Rossum
was looking for an interesting project to keep him occupied during Christmas.
He had already helped to create ABC programming language earlier in his
career and he had seen some issues with ABC but liked most of the features. Thus, he
took the syntax of ABC, some of its good features, and also fixed some issues
completely and had created a good scripting language which had removed all the
flaws. That project that he created and is said to have succeeded ABC, is Python!

18
CHAPTER 3: VARIABLES AND SIMPLE DATA TYPES.

Next Day…
Akhil: Hi Yash! How are you?
Yash: Fantastic. Eager to learn more python.
Akhil: Great, you are on the right track. So far, you’ve installed python in your
computer, you’ve written your very own hello world code in python. So, now let’s do
some math.
Yash: Sure, I love math.
Akhil: So, what is 3x4?
Yash: 3x4=12
Akhil: What is 19x22?
Yash: tough one, but it is 418.
Akhil: Good job. Then what is 7683x297?
Yash: Ohh…! That’s very hard to do in my mind. Can python help me with that?
Akhil: That’s what I want to tell you. Come on and start the IDLE shell as I had
shown you before.
Yash: Ok. I must go from start to python. Then to IDLE. It’s open.
Akhil: Then type 7683*297
Yash: Wait, what’s the asterisk (*) for.
Akhil: The asterisk is what computers use to represent multiplications instead of the x
that we humans use. Now, press the return key.
What do you see?

19
Yash: Output shows 2281851.
Akhil: That’s the answer we are looking for. The symbol ‘*’ is called an operator.
Operation Human Operators Python Symbol for the
operator
Addition + +
Subtraction - -
Multiplication x *
Division ÷ /
Remainder NA %

Yash: Cool. Looks the same almost.


Akhil: Yes, Next let’s take some realistic scenario. Let’s assume you own a bakery.
One day, you sold about 340 cupcakes each costing ₹50, how much money would you
earn? Find it out on python.
Yash: Ok, then that means I must multiply 340 by 50 to get the total earnings. Then
press return key.

20
I would earn a total of ₹17000.
Akhil: Great, now from the total cupcakes, let’s assume 6 of them get spoiled before
being sold, how much would you have earned then.
Yash: Well, 340-6*50

If I press return key, I get the answer, which is 40.


Wait a minute, that can’t be right. How can my money earned be less than the number
of cupcakes sold?
Akhil: See, that’s where the catch is. You were right in subtracting 6 from 340
cupcakes before multiplying with 50 rupees. But how python sees this is

21
First multiply 6 cupcakes with 50 rupees and then subtract from 340. Here’s why.

+ - * /
• In python every operator has a particular precedence or order.
• It performs multiplication and division operations before doing
addition and subtraction.
• If it sees a calculation with more than one type of operation, it
follows this order of precedence in executing it.
• Multiplication and division have the same precedence, while
addition and subtraction have the same precedence.
• In case where the python sees more than one operator with the same
precedence, it calculates from left and moves one by one to the
right.

Yash: Ok. This seems a bit tricky but I got the point.
Akhil: Cool. Let’s see few more examples. How will python try to perform a
calculation like this?
1267 – 56*14 + 18/2

Yash: As per the precedence, multiplication and division executes before addition and
subtraction.

So, this will make the expression as


= 1267 – 784 + 9
= 492
22
Akhil: Great. Now coming back to our original problem, do you understand why we
got 40 as the answer?
Yash: Yes, but then what is the solution?
Akhil: Parentheses or Round Brackets “()”.
When programming in python, we can use parentheses to control the order of
operations. Let’s see how.
In the cupcake problem, we want python to perform subtraction first. Next multiply
the result with 25.
For this, we can put parentheses around the part of the calculation we would like to
perform first.
So, now enter the following calculation in the IDLE.
>>> (340-6)*50
And press return key.

Yash: ₹ 16,700. That’s the answer we are looking for.

23
Akhil: Since, you got familiar with python, doing math with python. Let me introduce
VARIABLES.
Tell me, do you know how much money you’ll make if you produce
• Day 1: 520 cupcakes, 12 spoiled.
• Day 2: 100 cupcakes, 5 spoiled.
• Day 3: 130 cupcakes, 8 spoiled.
Would it be a good idea to do the whole calculation for each quantity, every time?
Yash: No, it would be nice if we could use some sort of formula for that.
Akhil: Exactly, you are very smart.
This is where VARIABLES come in.
You can think of variables as some sort of named place holders. Imagine having three
containers, each with different name.

Cupcakes_made Cupcakes_spoilt Cost_of_each_cupcake


340 6 50

In each of these containers, we can store a number of our choice. And whenever we
want, we can remove the number and put some other number in the container.

Cupcakes_made Cupcakes_spoilt Cost_of_each_cupcake


220 8 45

Each of these containers can be thought of to be variables. In python, we place


numbers into variables using the “=” sign. So, if we want to tell Python to store the
number 340 in the cupcakes_made variable, we type
>>> cupcakes_made=340

24
We can say that the value of cupcakes_made is 340.
To find out what value a variable hold, we can use the print command. "print()”. Type
this and tell me what you get.
>>>cupcakes_made=340
>>>print(cupcakes_made)
Yash: Entering the code….

Great, it gave the output 340, but here’s one thing I didn’t understand. Why did you
put an underscore for all the variable names? Why couldn’t you just call the first
variable as cupcakes made with a space in between?
Akhil: That’s a good observation. You see, when it comes to naming variables in
python, there are certain rules that you need to follow.

25
Rules:

• Variable names can contain only letters, numbers, and underscores.


They can start with a letter or an underscore, but not with a number.
For instance, you can call a variable name_1 but not 1_name.
• Spaces are not allowed in variable names, but underscore can be used
to separate words in variable names. For example, new_name works,
but new name will cause errors.
• Variable names should be short but descriptive. For example, name is
better than n, student_name is better than s_n, and name_length is
better than length_of_person_name.
• Be careful when using the lowercase letter l and the upper case letter
O because they could be confused with the numbers 1 and 0.
• Variable names are case sensitive.

So, let’s test your understanding. I will give you few names, you tell me which ones
are legal in python.
1. Book.open
2. Book 5
3. 3book
4. Book_5
Yash: Well, ‘Book.open’ has a dot, which is a special character. So that is illegal.
‘Book 5’ has a space, so not accepted.
‘3book’ starts with a number, so it is illegal.
I think ‘Book_5’ is the only legal variable.
Akhil: That’s right. Let’s move on.
So, you know how to create and print variables, let’s see how to use them. Let’s give
values to each of the following variables.

26
cupcakes_name.
cupcakes_spoilt.
cost_of_each_cupcake.
Now enter the following in the IDLE.
>>>cupcakes_made=340
>>>cupcakes_spoilt=6
>>>cost_of_each_cupcake=50
Now, instead of using numbers, we can perform our calculations using the variables
that hold them. So, type.
>>(cupcakes_made-cupcakes_spoilt) *cost_of_each_cupcake

Yash: entering the code….

Yash: Yes, the result is same. ₹ 16700.


Akhil: We can store the result of this calculation in another variable as follows.

27
>>> money_earned_on_day1 = ( cupcakes_made – cupcakes_spoilt) *
cost_of_each_cupcake.

So, now the variable money_earned_on_day1 will hold the value 16700.
Yash: Cool, what about day2.
Akhil: Simple, for day2 you change the values stored in the variables and repeat the
same calculation. Just copy paste the same code but change the variables values like
this.
>>>cupcakes_made=430
>>>cupcakes_spoilt=20
>>>cost_of_each_cupcake=50
>>>money_earned_on_day2 = ( cupcakes_made - cupcakes_spoilt ) *
cost_of_each_cupcake.

28
So, the day2 earnings are ₹ 20,500.
Similarly, you can do for day3 and so on….
Yash: Awesome. It will reduce most of my work.
Akhil: Yes, exactly. So, you see how helpful variables are.
Yash: Yes, they allow you to represent calculations as formulae that can be reused by
copying and pasting.
Akhil: That’s right. They are also helpful for many other purposes; we’ll see these
later. For now, it’s enough for you to know that VARIABLES are a way of holding
values to be used later.
Now, since you know quite much about python, let’s understand what the different
types of numbers python use.
Yash: Sure.

29
Akhil: In python, there are mainly two type of numbers
• Integers
• Floats
Integers:
A number which is not a fraction, a whole number.
Ex: -25, 89, 0, 11
Yash: I think, we used integers in out cupcake example.
Akhil: Exactly. You are familiar with integers. To recap, let’s try these in the IDLE.
>>>2+3
5
>>>3-2
1
>>>2*3
6
>>>3/2
1.5
>>>2 + 3*4
14
>>> (2+3) * 4
20

30
Floats:
Python calls any number with a decimal point a float. You can almost use decimals
same as Integers. Add them, subtract them, multiply them, divide them.
Try these out in the IDLE.
>>>0.1 + 0.1
0.2
>>> 0.2 + 0.2
0.4
>>>2 * 0.2
0.4
Yash: Gotcha. Integers for whole numbers and Floats for decimal numbers.
Akhil: Exactly. But you should note some key points.
1. If you divide two numbers, any numbers float or integer. The result is always a
float.
>>> 4/2
2.0
2. When you mix an integer and a float in any other operation, you’ll get a float as
well.
>>>1+2.0
3.0
>>>2*3.0
6.0

31
Python defaults to a float in any operations that uses a float, even if the output is a
whole number.
Yash: Ok. Got your point.
Akhil: Let’s see a small topic called “comments”.
Yash: Comments!! What are comments?
Akhil: Comments are an extremely useful feature in most programming languages.
Everything you’ve written in your programs so far is python code. As your programs
become longer and more complicated, you should add notes within your programs
that describes your overall approach to the problem you’re solving. A comment
allows you to write notes in English within your program.
Yash: Great feature. But how do we comment in python?
Akhil: In python, the hash mark (#) indicates a comment. Anything following a hash
mark in your code is ignored by the python interpreter.
Ex:
#say hello to yash
print(“Hello Yash!!”)
python ignores the first line and executes the second line.
Great work. Let’s learn new concepts tomorrow.
Yash: Sure. Learning is fun with you.

32
Exercise:
1. What is a variable?
A. A python function
B. A programming language
C. A placeholder to store values
D. A constant
E. An operator
2. Select the legal variable name in python?
A. Mouse 22
B. 2mouse
C. Mouse.2
D. Mouse_2
E. Mouse/2
3. Which of the following symbols represents multiplication in python?
A. +
B. *
C. –
D. /
E. _
4. The result of 20/10 will be a float?
A. True
B. False
5. What is the output for the following calculation?
(22*11)-33+62/(4-1)
A. 123.6
B. 222.4
C. 229.6
D. 300.8
E. 44
6. Write python code to assign some number to a variable and print it.
7. Write a python program which uses variables No_of_choclolates,
cost_of_each_chocolate, total_cost. Fill these variables and find the total cost.
8. Find simple interest for principle of ₹ 10,000 , number of years=5, rate of
interest=5% using python. (Hint: Simple Interest= principle*no of years*rate of
interest/100)

33
Fun Fact:

Python Was Named After a TV Show:


The name Python, to a programming language, seems weird. So, was it named after a
snake called Python? Of course not! There is a whole different story behind it. The
inspiration for the name came from BBC’s TV Show- ‘Monty Python’s Flying
Circus’, as the creator of Python - Guido van Rossum was a big fan of the TV show
and also he wanted a short, unique and slightly mysterious name for his invention and
hence he named it Python!

34
CHAPTER 4: STRINGS

Next Day…...
Akhil: Well Yash! You’ve learned how to use variables to display numbers. You
know, the rules for creating variable names, how to use operators to do calculations
with variables and how to display the numbers that the variable holds using the print
command.
Yash: Yes, to print a variable value, I just type ‘print’ and then the variable name in
parenthesis. But, can variables be used only for printing numbers? Can’t we print any
text?
Akhil: That’s a very good question. Variables are not just used for storing numbers.
They can also be used to store text.
In programming languages, a text is called a ‘string’.

Letters, Address
words

STRING

Numbers Name

35
So, a variable used to store a string is called a String Variable.
Do you remember the first program you wrote?
Yash: Of course, I had printed the words Hello World.
Akhil: That’s right. The words ‘Hello World’, where actually a string of text. We
enclose our text in double or single quotes to tell python that it’s a string. This is done
so that it doesn’t confuse the word with other python words like print.
Yash: So, how do I assign the string hello world to a variable?
Do I just type.
>>> my_variable= Hello World
Akhil: Nope, you’ll get a syntax error if you do that.
Yash: A what error?

Akhil: You see, a syntax error message means that you made a mistake in
arrangement of words and symbols in the command.

36
• String values are always enclosed in double quotes or single quotes.
• In python, every instruction must be given according to the syntax or rules
or else python doesn’t understand.

Yash: Ok, then let me try using a string variable and printing its value.

Akhil: Remember Yash, if you start the string with a single quote, you should end it
with a single quote only. If you start with a double quote, you can only end with a
double quote. So, you can’t mix up the two types.
Yash: Got it.
Akhil: Good job Yash. Now, try to print the words, this is my computer, this time
with single quotes.
Yash: That’s easy.

37
Why is it showing a syntax error now?
Akhil: This kind of syntax error means that Python was probably expecting something
before the line ended. Check the code clearly, you forgot to put a single quote in the
end.
Yash: That’s right. Sorry, I forgot. I’ll make the correction. Actually, I want to change
my string instead of ‘this is my computer’. I want the variable to hold ‘This is Yash’s
computer’.
Akhil: Why not? Go ahead but just be warned, your sentence has a single quote in it.
Type it out, you’ll see why I pointed that out.
Yash: Ok. If I press return key.

38
Why is it showing a syntax error now?
Akhil: You see what I was talking about. When python sees the single quote after
Yash, it just thinks that this is the end of your string and then when it seems the rest of
the things that comes after, it gets confused. So, it gives you a syntax error.
The solution is to use a backslash (\) before each quotation mark that you want to
show python to be a part of your string.
Now let’s correct the code and execute it.
>>>my_variable=’This is Yash\’s computer’
>>>print(my_variable)
This is Yash’s computer

see, no error.
What if you want to type a whole story about yourself that would expand to multiple
lines? Right. This kind of text is called multiline string. If you type this kind of a
string,

39
“Python will
Treat the next
Line that you
Enter as your
Next instruction”
Python will treat that next line that you enter as your next instruction. Since your
sentence won’t make any sense to python, it will give you an error message.
To avoid problems like these, you should start and end a multiline string with three
single quotes (’’’).

Try it out…...
Yash: Sure.

Akhil: Great! Now, let’s move to the next topic.

40
EMBEDDING VALUES INTO STRING

Suppose, you want to display a message that contains the value of another variable.
So, if you have
• A variable called ‘age’
• Add its value to the value of another variable ‘display_text’ which holds a
sentence telling how old Yash is.
For these kinds of situations, we use a placeholder in the final display_text string.
Code:
>>>age=15
>>>display_text = “Yash is %s years old”
>>>print(display_text % age)
Yash is 15 years old

So, if you look closely, in second line I added a placeholder modulus s (%s) to tell
python that this is the place where I will insert the value of another variable.
In the third line, when I put the variable age after the modulus, I’m telling python to
replace modulus s (%s) in the display_text string with the value of the variable age.
Let’s run this and see what we get.

41
There you go. You see, python inserted the value of 15 in place of the placeholder %s.
You can use placeholders to represent both numbers and string values.
Yash let’s check your understanding.
Yash: sure.
Akhil: Calculate how old Yash will be after 5 years and after 10 years and display it.
Yash: Ok, let me type it out.

42
Akhil: You can also use more than one placeholder in a string.
Ex: If you want your earlier code to be reusable for more than one person, then this is
what you’ll do.

This will replace the first placeholder in display_text with the value of name and the
second placeholder with the value of age. Notice that I used the placeholder (%s) to
represent a string as well as a number.
Yash: So, if I want to print ‘how old john will be after 15 years’, I will add the last
line of code. Right?
Akhil: Exactly.
Yash: John is going to be really old.
Akhil: Very funny.
Let’s see some commands that we can give directly to string variables in python.
See this code, and run it.

43
>>>name = “Michael Jackson”
>>>print(name.title())
Michael Jackson

Yash: Ohh! What is this title()?


Akhil: This is called a method. In this code name refers to the lowercase string
‘michael jackson’. The method title() appears after the variable in the print() call.

A method is an action that python can perform on a piece of data.

The dot (.) after name in name.title() tells python to make the title() method act on the
variable name. Every method is followed by a set of parentheses, because methods
often need additional information to do their work. That information is provided

inside the parentheses. The title() function doesn’t need any additional information, so
its parentheses are empty.
Note that method and function words can be used interchangeably.
The title() method changes each word to title case, where each word begins with a
capital letter.
Some other useful methods are.

44
lower() method converts the string into lowercase.
upper() method converts the string into uppercase.

Yash: Cool! Lots of features. Loving it.


Akhil: Good! Python is huge. But very interesting.
I think this is good for today. Let’s meet tomorrow.
Yash: Sure. Have a great day.

45
Exercise:
1. Use a variable to represent a person’s name, and print a custom message to
greet that person.
2. Use a variable to represent a person’s name, and then print that person’s name
in lowercase, uppercase, and title case.
3. Find a quote from a famous person you admire. Print the quote and the name of
its author.
Ex:
Albert Einstein once said, ‘A person who never made a mistake never tried
anything new’.
4. Use three variables to store your name, surname, age and print a string with
these three variables.
5. Calculate how many hours of TV your friend John watches in a week, if he
watches 2 hours of TV every weekday and 3 hours every weekends. Use name
as one of your variables.
6. Print this string -
Shouldn’t
Couldn’t
Wouldn’t are
Things you
Shouldn’t say.

46
Fun Fact:

Python is Older Than Java:


Python programming language is high in demand has grown drastically in the past 10
years. So, it seems Python is a new language that got the attraction to its audience and
that gave it boost. But here’s a fun fact, Python is an old programming language and is
even older than Java. Python was initially released in 1991 whereas Java was released
in 1995. Thus, Python is now almost 30 years old and still stands strong for the future.

47
CHAPTER 5: LISTS

Next Day…...
Akhil: Well Yash, you have a good enough idea of strings and string variables.
Yash: Yes, I now know that a variable can hold both strings and numbers. I know
how to print a string and how to print a multiline string too. I also know how to use
placeholders in strings to allow printing values of other variables.
Akhil: Great!
Did you also notice, Yash; each time we wanted to print someone’s age, be it mine,
yours or someone else’s, we had to either type a lot of lines or introduce a lot of
variables.

>>>first_name = “John”
>>>last_name = “Wick”
>>>age = 32
>>>string_text = “%s %s is %s years old.”
>>>print(string_text % (first_name, last_name,age))
John Wick is 32 years old.

Let’s see this in IDLE.

48
Yash: That’s true.
Akhil: So, if you have ten friends whose ages you want to calculate, it’s going to be
really tiring to get. To get around this problem python gives us the facility of using
lists, using lists you can store on a number of strings in just one string variable in an
organized manner.

To make this clearer, let’s introduce a list called friends, which will contain the names
of all your friends.

>>> friend_names = [‘john’, ‘rob’, ‘smith’ , ‘jack’, ‘laura’]


>>>print(friend_names)

This is how you should assign strings to a list. I used square brackets to tell python
that this is going to be a list and I separated each string with a comma (,).

49
Output:

Next, we can use index of the item to refer the corresponding name.
Ex: if I want to use ‘smith’, which is in the third position in the list, I would say
friend_names[2]. Because, python always counts the list starting from 0.

Friend Index
john 0
rob 1
smith 2
jack 3
laura 4

>>> print(friend_names[2])
smith

50
Now, let’s check your understanding Yash.
Yash: Sure.
Akhil: Add to this, make a list of ages for these five friends in the same order.
Yash: Ok, so

>>>friend_names = [ ‘john’, ‘rob’, ‘smith’, ‘jack’, ‘laura’]


>>>friends_ages = [13 , 12 , 14, 13, 12]

Akhil: So, how old any 2 of your friends will be in 5 years. Pick rob and laura.
Yash: Ok. Let me try.

>>>print(“In 5 years, %s will be %s years old.” %


(friend_names[1], friends_ages[1]+5))

In 5 years, rob will be 17 years old.


>>>print(“In 5 years, %s will be %s years old.” %
(friend_names[4], friends_ages[4]+5))
In 5 years, laura will be 17 years old.

This is the result.

51
Akhil: Great. So, you can find the age of any of your friend after any number of years.
The beauty of this list is that you can easily change any part of the list by simply using
its index. This makes it much easier to use than strings.
So, for example, say you’re not friends with rob anymore and you’ve made a new
friend called pete instead. All you have to do is use rob’s index and change the
corresponding value of both friend_names and friends_ages lists.

>>> friend_names = [‘john’, ‘rob’, ‘smith’, ‘jack’, ‘laura’]


>>> friends_ages = [13, 12, 14, 13, 12]
>>> friend_names[1] =’pete’
>>> friends_ages[1] = 14
Print(friend_names)

See, here in the third statement, I asked python to replace the value of the second
friend’s name to pete instead of rob.

52
Output:

See, we changed the second age value to 14 instead of 12. We can even add two lists
into a single list.

>>>names_and_ages = [friend_names, friends_ages]


Print(names_and_ages)

53
The new list names_and_ages will have just two items, since it’s a list of variables,
not of the contents of the variables. So, if you want to refer to rob’s name, you cannot
type

>>>names_and_ages[1]

If you do that, it will give you the whole list of friends ages, since the variable
friends_ages are in index one of names_and_ages. Instead, you should refer to the first
list in the first square brackets and then the item in the item in the first list in second
set of rectangular brackets.
Like this.

>>> print(names_and_ages[0][1])

54
This means, index 0 of names_and_ages, i.e., the list friend_names and then to the
index 1 of friend_names i.e., rob.

Yash: Got it. Is there any way to add items to the list, like what if I make two new
friends, Ben and Ken?
Akhil: That’s a good point. To add values to list we use the append function/method.
You remember what’s a method is. Right?
Yash: Yes, A method is an action that python can perform on a piece of data.

Akhil: Exactly. So, to add Ben and Ken to the friend_names list, do this.

>>>friend_names = [‘john’, ‘rob’,’smith’,’jack’,’laura’]

>>>friend_names.append(‘ben’)

>>>friend_names.append(‘ken’)

>>>print(friend_names)

[‘john’,’rob’,’smith’,’jack’,’laura’,’ben’,’ken’]

55
You see the list now contains seven items instead of five.
Yash: What if I want to delete an item? What if I decided making friends with ben
and ken was not a good idea?
Akhil: In that case, you’ll use the ‘del’ command. Notice that I said command and not
function because a function name is always followed by parentheses, while a
command is not.

>>>del friend_names[6]
>>>del friend_names[5]
Print(friend_names)

[‘john’,’rob’,’smith’,’jack’,’laura’]

Yash: Great, now I understand append method and delete command.

56
Akhil: Good job. You are a quick learner Yash.
Yash: Thank You. But all the credit goes to you.
Akhil: It’s my pleasure. I think this is good for today.
Yash: Sure. Let’s meet tomorrow then. Bye!

57
Exercise:
1. Store the names of your family members in a list called family. Print each
person’s name by accessing each element in the list, one at a time.
2. This is continuation to question 1. Now print the custom greet message for each
name in the list.
3. Create 3 list items
• List of 5 friends
• List of their ages
• List of their favorite candies.
Print 5 statements of the form
“Raj is 15 years old, he loves to eat perk”
4. Create a list of guests you want to invite to your birthday party. Print separate
welcome message.
5. This is continuation to question 4.
• Add 2 new guests to the list
• Remove the 1st guest in the list.
• Change the 3rd guest to John.
6. Create a list of movies you want to watch. Add a new movie to the list. Print
the changed list.

58
Fun Fact:

Python is Not Slow.


If you know python and if you have been coding in Python, you might have heard in
the community that python is slow. But my question is, “what do you want to
develop?”. If python would have been slow then why would companies like NASA,
Instagram, IBM use python? So, what you want to develop, that is superior to
NASA’s operations and needs faster language.
Python is slower if compared to programming languages like C, C++, Java, and more
since they are compiled languages whereas Python is interpreted. Thus, this gives a
slightly slow speed.

59
CHAPTER 6: WORKING WITH LISTS

Next Day……
Akhil: Hi Yash! Well, you now know how List’s work.
Yash: Yes. I know how to create a list
>>> friend_names = [‘john’, ‘rob’, ‘smith’ , ‘jack’, ‘laura’]
I know how to add a new item to the list.
>>> friend_names.append(‘pete’)
I know how to change an existing item in the list.
>>> friend_names[2]=’michael’
and I know how to delete an item from the list.
>>> del friend_names[3]
Akhil: Great. But there are more to Lists. Let’s explore these new concepts.
Yash: Sure, After you.
Akhil: So, we saw how to delete an item in the list.
>>> del friend_names[3]
But we have two more ways to remove an item from a list.
Yash: Ok. What is the first one?
Akhil: Using pop() function.
Yash: What is pop()?
Akhil: The pop() function removes the last item in a list, but it let’s you work with
that item after removing it. Let’s take an example to make things clear.

60
Yash: Sure.
Akhil: Suppose, you made a list of places you want to visit in your lifetime. Let’s call
it places_to_visit.
>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,
‘bangkok’]
Now, you want to remove the last item from the list. In this situation, you can use
pop() function to remove an item.

>>> print(places_to_visit)
>>> popped_place = places_to_visit.pop()
>>> print(places_to_visit)
>>> print(popped_place)

61
See, what happened. In line three, we pop a value from the list and store that value in
the variable popped_place. Next, we print the places_to_visit list and popped_place
variable.
Yash: Cool! But what is the use of pop when we can use del command?
Akhil: Suppose, in a particular situation you want to delete the last item in a list. The
most recently appended item, but you forgot the count of items in the list. In this
situation pop() function comes in handy.
Yash: Ok.
Akhil: But there is another useful feature of pop(). You can even add an index value
to this pop() function and the item in that index will be popped.
Yash: What?
Akhil: Let me give you an example.

>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,


‘bangkok’]
>>>print(places_to_visit)
>>> first_place = places_to_visit.pop(0)
>>> print(“My first visit is to %s” % (first_place))
>>>print(places_to_visit)

62
See, in line 2, we used the pop function but this time we gave the index value of 0. So
‘paris’ will be popped out of places_to_visit list and it will be stored in first_place.
Next, we print it along with the updated places_to_visit.
Yash: Ok. How can we decide, when to use del command and when to use pop
function?
Akhil: If you’re unsure whether to use the del command or the pop() function, here’s
a simple way to decide; When you want to delete an item from a list and not use that
item in any way, use the del statement; if you want to use an item as you remove it,
use the pop() method.
Yash: Got it. del removes an item without returning the deleted item, pop() removes
an item with returning the popped item.
Akhil: Exactly. But remember that each time you use pop(), the item you work with is
no longer stored In the list.
Yash: Got it. I will keep it in mind.

63
Akhil: Let’s see other methods. You can remove an item by value. This method is
useful when you don’t know the position of the item you want to remove.
Let me give you an example.
>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,
‘bangkok’]
>>> print(places_to_visit)
>>> places_to_visit.remove(‘london’)
>>> print(places_to_visit)

See, in line 3 we tell python to find out where ‘london’ appears in the list and remove
that element.
Yash: Great. Lots of options to remove an item from a list.
Akhil: Yes, python gives you the flexibility to choose from a list of options.

64
Yash: Ok. I have a doubt. What if in my list places_to_visit, I have london twice, will
the remove function remove both the items?
Akhil: That’s an interesting question. The remove() function deletes only the first
occurrence of the value you specify.
Yash: Cool! Got it.
Akhil: Good. Now let’s see a new concept called sorting.
Yash: Sorting? What is sorting? What are its uses?
Akhil: Sorting is the most common technique to organize a list. Let me give you few
examples. See the two lists.

List_a = [12, 22, 8, 7, 44, 3, 6]


List_b = [‘b’ , ‘x’, ‘a’, ‘d’, ‘q’]

If you observe clearly, both the lists List_a, List_b are not properly organized. Now, if
I sort List_a, List_b then this is how they look.

Sorted_list_a = [3, 6, 7, 8, 12, 22, 44]


Sorte_list_b = [‘a’, ‘b’, ‘d’, ‘q’, ‘r’]

Yash: Ok. I got your point. So, sorting means, arranging the data in a particular order.
Akhil: Exactly.
Yash: Great. How can I sort a list using python?
Akhil: Using the sort() function. sort() method permanently sorts a list of items.
Let me give you an example.

65
>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,
‘bangkok’]
>>> places_to_visit.sort()
>>> print(places_to_visit)

See, in line2, we used the sort() method. It changed the order of the list permanently.
The places are now in alphabetical order,and we can never revert to the original order.

Yash: Is this the only order we can sort? What if I want to print a list in
unalphabetical order?
Akhil: Yes, we can also sort a list in reverse alphabetical/ unalphabetical order by
passing the argument “reverse = True” to the sort() function.
Let’s see an example.

>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,


‘bangkok’]

66
>>> places_to_visit.sort(reverse=True)
>>> print(places_to_visit)

See, the list is sorted in reverse alphabetical order. Again, the order of the list is
permanently changed.
Yash: Ok. What if I want to have a copy of my old unsorted list? Is there a way?
Akhil: Yes, we can use sorted() function to temporarily sort a list. The sorted()
function let’s you display your list in a particular order but doesn’t affect the actual
order of the list. Let me give you an example.
>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,
‘bangkok’]
>>> print(places_to_visit)
>>> print(sorted(places_to_visit))
>>> print(places_to_visit)

67
See, in second line, we used sorted function on places_to_visit list. The sorted
function didn’t change the order of places_to_visit list. It just printed a sorted order of
the places_to_visit list.
Yash: Understood. Sort() function changes the order of a list permanently, while
sorted function just prints the sorted list without effecting the original list.
Akhil: Correct. The sorted() function can also accept a reverse=True argument if you
want to display a list in reverse alphabetical order.
Yash: Ok.
Akhil: Now, let’s see how to reverse a list. Note that reversing a list is different from
sorting a list in reverse order. Reversing a list simply moves the last items to first and
first items to last.
Yash: Could you give me an example?
Akhil: Sure
See the code.

68
>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,
‘bangkok’]
>>> print(places_to_visit)
>>>places_to_visit.reverse()
>>>print(places_to_visit)

Notice that reverse() doesn’t sort backward alphabetically; it simply reversed the
order of the list.
Yash: Yes. Understood.
Akhil: The reverse() method changes the order of a list permanently, but you can
revert back to the original order anytime by applying reverse() to the same list a
second time.
Yash: Sure, we can. Reversing twice is same as the original list.
Akhil: Exactly. Now, let’s assume you didn’t keep the count of number of items in
the list, but you want to find the length of the list. How will you do that?
Yash: Let me think. Oops. No idea. Can you explain?
69
Akhil: Using the len() function.

>>> places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,


‘bangkok’]
>>> print(len(places_to_visit))

len() function is very useful in any programming language. Remember that python
counts the items in a list starting with one unlike the index which start from 0.
Yash: Yes. Point noted.
Akhil: Great! Good job. We are learning a lot. We can continue our learning
tomorrow.
Yash: Ok. See you. Bye!

70
Exercise:
1. Create a list of movies you saw.
1.1. Add new movies to the list.
1.2. Remove a movie using del command.
1.3. Remove the last movie you watched using pop().
1.4. Remove a movie by its name.
2. Create a list of shopping items you want for the next week. Now sort the list using
sort() function.
3. This is continuation to question 2.
3.1. Create a copy of original list and print the sorted list.
4. Create a list of your friend names. Print the list in reverse order.
5. This is continuation to question 4.
5.1. Print the length of your friends list.

71
Fun Fact:

Python programming language has different variants for different use


cases and applications.
Some of the Python variants are,
CPython – It is written in C and is the most common implementation of Python.
Jython – It is written in Java that compiles to bytecode.
IronPython – This is implemented in C# and is an extensibility layer to framework
written in .NET
MicroPython – This variant runs on a microcontroller.

72
CHAPTER 7: TUPLES AND DICTIONARY

Next Day…...
Akhil: Welcome Yash. Let’s continue our learning.
Yash: Sure, let’s dive in.
Akhil: Yash! You are now familiar with lists, How to organize strings into lists, How
to use sort() and len() functions on lists.
Yash: Yes, Now I can initialize a list, I can add items to a list, I can remove items
from a list, I can sort a list, I can reverse a list and even find the length of my list.
Akhil: Great! Lists are great source to store our data. Python also provides two more
types to store our data, namely Tuples and Dictionaries.
Yash: Ok. What are Tuples?
Akhil: See, A tuple basically contains a fixed set of items whose items and their
values cannot be
• Changed
• Added to
• Deleted.
Yash: But, why should I want to do that? Wouldn’t I want some flexibility to be able
to change later?
Akhil: Sometimes Yash, there are certain fixed lists that I wouldn’t want to change.
For example, a list containing the days of the week.
I know that a week always contains the same days and in the exact same order. So it
would be useful to keep it as is, so that I don’t accidentally change any values later on.

73
Days of the week.

• Sunday
• Monday
• Tuesday
• Wednesday
• Thursday
• Friday
• Saturday

Similarly, Months of a year.

Months of a Year

January July
February August
March September
April October
May November
June December

74
There are similar fixed lists of numbers like the Fibonacci series, which is a set of
numbers in which each number is the sum of the previous numbers.

0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 ……

Let me show you how you can define a tuple for days of the week and how you can
refer to it and print individual items in the tuple. You should know that a tuple is
defined just like a list, but with parentheses instead of square brackets.

>>> Days_of_the_week = (‘Sunday’ , ’Monday’ , ’Tuesday’ ,


’Wednesday’ , ’Thursday’ , ’Friday’ , ’Saturday’)

Now, if you want to use the fourth item in the tuple, which is Wednesday, you should
use the same method of indexing as in lists. The fourth item has an index of 3. So, to
print Wednesday, I type.

>>>print(Days_of_the_week[3])
Wednesday

See, the output is Wednesday.

75
Yash: Great, looks same as lists, except the parenthesis.
Akhil: But, as the definition of tuple, we can’t add, change or delete an item from the
tuple.
Yash: Can you give me a demo.
Akhil: Sure, let’s try to change the third element from ‘Tuesday’ to ‘Friday’ using the
index.
Type the following code in the IDLE and see the output.

>>> Days_of_the_week = (‘Sunday’ , ’Monday’ , ’Tuesday’ ,


’Wednesday’ , ’Thursday’ , ’Friday’ , ’Saturday’)
>>>print(Days_of_the_week[2])
>>>Days_of_the_week[2]=’Friday’

Yash: Ok, let me type it out. Press the return key.

76
Why am I getting an error?
Akhil: See, in the code, we are trying to change the value of third day, but python
returns a type error. Basically, because we’re trying to alter a tuple, which can’t be
done to that type, python tells us we can’t assign a new value to an item in a tuple.
Yash: Ok, now I understood the difference between lists and tuples.
Akhil: Now let’s move on to Dictionaries.
Yash: Sure, I know what a dictionary is. But how python uses it?
Akhil: Let me explain. A Dictionary is a collection of lists or tuples. Each Dictionary
has a key and a corresponding value. Let’s take an example. Say, you want to solve
the same age problem, but in a more organized way with all the details about your
friends and their ages in one variable. In that case, a dictionary is the best way to go.

77
Yash: Why can’t we just use a list containing both lists like the names_and_ages
variable?
Akhil: We could have and it would have been just fine, but instead of five friends,
what if you had 100? Don’t you think it would have been tough for you to remember
and find the index number of each friend?
Yash: True. Then show me how to make a dictionary.
Akhil: Ok, now just look carefully at how I define the dictionary. The syntax is
important.

>>> names_and_ages_dict = {‘John’: 13,


‘Rob’ :12,
‘Smith’: 14,
‘Jack’: 13,
‘Laura’: 12
}
• We enclose items of a dictionary in curly brackets.
• We separate each item by comma (,).
• Within each item, we separate the key from the value by a colon.
Now, if I need to print only value from the list, say the age of Jack, I don’t even
need to know his index number, I simply type.

>>>print(names_and_ages_dict[‘Jack’])
13

78
By this line, I am telling python to print the value corresponding to the key Jack,
which is 13.
See, don’t you think this way is easier?
Yash: You are right. Give me another example.
Akhil: Ok, let’s see another example.
Say you decided to do one special activity each day of the week. You go ahead and
create a weekly plan.

Day Activity
Sunday Movie
Monday Chess
Tuesday Cricket
Wednesday Dance
Thursday Swimming
Friday Drawing
Saturday Cooking

79
Let’s create a dictionary for this routine.

>>>myroutine = {‘Sunday’:’Movie’,
‘Monday’:’Chess’,
‘Tuesday’:’Cricket’,
‘Wednesday’:’Dance’,
,’Thursday’:’Swimming’,
,’Friday’:’Drawing’,
,’Saturday’:’Cooking’
}
>>>print(myroutine)

Now let’s see the output in the IDLE.

80
See, we got our dictionary as the output.
Yash: Yes.
Akhil: Now let’s check if our dictionary is stored properly. Yash! What would you do
on Thursday?
Yash: Swimming.
Akhil: Cool. Let’s check it out.

>>>print(myroutine[‘Thursday’])
Swimming.

Yash: Yeah! I love swimming.

81
Akhil: Ok, so our dictionary is working fine. Now let’s see how to remove items from
the dictionary. To delete an item from a dictionary, you again use items key. In other
words, the key in a dictionary acts like the items index. So, to delete Sunday and its
activity from your dictionary, I use the del command as in lists.

>>> del myroutine[‘Sunday’]

Yash: Yes, Same as lists.


Akhil: Yes, now let’s see how to change the value in a dictionary. Could you try this
one?
Yash: Sure, as per my knowledge, we should use the key to access its value and
assign the new value. So.

82
>>> myroutine[‘Wednesday’] = ‘Football’
>>>print(myroutine)

Akhil: That’s great. You are a genius. See, the entry of Sunday got deleted as we used
the del command and the entry of Wednesday got changed to Football instead of
Dance.
Yash: Yes.
Akhil: Great! Good job Yash; This is good for today. See you tomorrow. Bye.
Yash: Good Bye.

83
Exercise:
1. Suppose, your school offers six subjects every year for the 5th class. Create a
tuple subjects and add items to it.
• Print each subject name.
2. Suppose, you and your friend want to know how many movies each of you saw
last week. Now create a dictionary of names_and_movies to store your friends’
names as keys and number of movies watched as values.
3. Create a tuple for months. Create a dictionary to store friends names and their
birth months. Use the previously created tuple to refer to months.
Print the birth month of any two friends.
4. This is continuation to question 3.
From the dictionary, delete the third friend.
Print out the dictionary to see if it got deleted.
5. Create a dictionary to store words and their meanings. Use these words.
1. Hale: Strong and healthy.
2. Milkman: A man who delivers milk to house.
3. Doorway: an entrance with a door.
4. Restless: Unable to rest or relax.
5. Ant: A small insect that lives with many others in an organized group.

84
Fun Fact:

There are around 700 separate programming languages.


Among this list, some of the most popular languages are JavaScript, Swift, Scala,
Python, PHP, Go, Rust and C#, with millions of users utilizing them in both their
careers and personal projects. However, new programming languages are constantly
being created.

85
CHAPTER 8: LOOPING IN PYTHON

Next Day….
Akhil: Hi Yash!
Yash: Hello, how are you Akhil?
Akhil: Doing great. Yash, you know a lot about python now. Proud of you.
Yash: Thankyou Akhil. All the credit goes to you.
Akhil: It’s my pleasure. Since you know about list, tuples and dictionaries. Maybe I
should introduce you to loops.
Yash: loops!! What are loops?
Akhil: Learn Carefully, this is one of the important topics in programming. You saw
how lists work. Lists usually contain some n number of items. To work with those
items, you use indexing. Suppose, in a list there are 100 items and you want to print
each item in the list. How would you do that?
Yash: So, to print the first item I will write print(list[0]) and to print second item I
will write print(list[1]) and similarly for other 98 items in the list. So, I should write
100 lines to print all the 100 items. But this is very tiresome. Is there an easy way to
do that?
Akhil: Yes, Using loops. Pythons ‘for’ loop is the most common one. Let’s take an
example. For the list places_to_visit, you want to print the name of each place in new
line. You can do this using a for loop. Observe the code carefully.

>>>places_to_visit = [‘paris’ , ’london’ , ’rome’ , ’dubai’ ,


’bangkok’ ]

86
>>>for place_name in places_to_visit:
print(place_name)
See, initially we defined our places_to_visit list. In line number 2 we define a for
loop. This line tells python to pull an item from the list places_to_visit, and associate
it with the variable place_name. In the next line, we tell python to print the place
that’s just been assigned to the place_name variable. Python then repeats lines 2 and
3, once for each item in the list.

Yash: Yeah! All the places got printed with very few lines of code. Great, but in line
three, I am confused. Can you explain more about it?
Akhil: see, the white spaces in line 3 is called indentation. To give indentation, you
press tab key in the keyboard. After entering the line three, you should press shift +
return key or return key twice to run the code.

87
Yash: Ok.
Akhil: You need to keep in mind these important points while using for loop.

• For is a keyword in python, so it should not be used for any other


purpose.
• For statement should end with a colon (:)
• Indentation should be properly maintained after the for loop.

Yash: Got it. Could you give me few more examples of looping?
Akhil: Sure, let’s take another example and look deep into the code to see what
actually is happening.
Yash: Sure.
Akhil: Let’s take the list of your friend’s names.
>>>friend_names = [‘john’,’rob’,’smith’,’jack’,’laura’]
Now, let’s print each friend’s name using for loop.

>>>for friend_name in friend_names:


print(friend_name)

88
See, we got the output of your friend’s names.
Yash: Yeah!
Akhil: What happens in this code is, Python initially reads the first line of the for
loop:
>>>for friend_name in friend_names:
This line tells python to retrieve the first value from the list friend_names and
associate it with the variable friend_name. This first value is ‘john’. Python then reads
the next line:
print(friend_name)
Python prints the current value of friend_name, which is still ‘john’. Because the list
contains more values, python returns to the first line of the loop:
>>>for friend_name in friend_names:

89
Python retrieves the next name in the list, ‘rob’ and associates that value with the
variable friend_name. Python then executes the line:
print(friend_name)
Python prints the current value of friend_name again, which is now ‘rob’. Python
repeats the entire loop again and again until the last item, which is ‘laura’. Because no
more values are in the list, python moves on to the next line in the program. In this
case nothing comes after the for loop, so the program simply ends.
Yash: Ok. So, all this happens in a loop. Now I understood the concept of loops.
Akhil: When you’re using loops for the first time, keep in mind that the set of steps is
repeated once for each item in the list, no matter how many items are in the list.
Yash: Gotcha.
Akhil: We can do a lot of wort within a for loop.
Yash: What do you mean by lot of work?
Akhil: See, suppose for the previous list friend_names you want to print “Hi john!
Will see you soon.” And similar message for other friends, you can do it using the for
loop. See the code.

>>> friend_names = [‘john’,’rob’,’smith’,’jack’,’laura’]


>>> for friend_name in friend_names:
print(“Hi %s! will see you soon.” % (friend_name))

Let’s, see the output.

90
See, separate message for each friend.
Yash: Yeah! What if I want to print two lines in the for loop?
Akhil: Easy. After the for loop, with same indentation write two print statements like
this.

>>> friend_names = [‘john’,’rob’,’smith’,’jack’,’laura’]


>>> for friend_name in friend_names:
print(“Hi %s!% (friend_name))
print(“How are you?”)

91
See, in the for loop, we have two lines of code. So python executes these two lines for
every item in the list friend_names.
Yash: Got it. What if after all the messages, I want to print good bye! How to do that?
Akhil: For that, you need to execute the for loop first. After that, you can print the end
message separately. See the code.

>>>friend_names = [‘john’,’rob’,’smith’,’jack’,’laura’]
>>>for friend_name in friend_names:
Print(“Hi %s!” % (friend_name))
---------------------------------------------

92
>>>print(“See you soon everyone.”)

let’s, see the output.

See, first the for loop got executed and we got the required output. Later we printed
the end message using a separate print statement. This print statement is not inside the
for loop. So, it got executed only once.
Yash: Got it. Python looks very interesting.
Akhil: Yes, it is.
Now, let’s look at creating lists using some numeric functions.
Yash: sure.
Akhil: Some times, we want to store a set of numbers in a list, like ages of our
friends, their birthday, number of movies your friends saw last week etc. All these

93
lists are created by user manually. But what if you want to create a list, like list of first
100 natural numbers. Would it be nice, to initialize it ourself?

Yash: No, writing 1 to 100 numbers is tiresome. Is there an easy way?


Akhil: Yes, using range() function. Python’s range() function makes it easy to
generate a series of numbers. Look at this code.

>>>for number in range(1,5):


print(number)

See, we got the list of numbers from 1 to 4.


Yash: But, why is 5 not printed.
Akhil: The range() function causes python to start counting at the first value you give
it, and it stops when it reaches the second value you provide. Because it stops at the

94
second value, the output never contains the end value, which would have been 5 in
this case. So, to print from 1 to 5, you would use range(1,6):

>>>for number in range(1,6):


print(number)

Yash: Cool, Got it.


Akhil: See, you can create a list of numbers using range function and assign it to a list
variable.
>>>numbers = list(range(1,6))
Print(numbers)

95
See, in line 1 we used list() function. This function returns a list. So it is useful to
convert non list type elements to list type.
Yash: Ok.
Akhil: You can also use range() function to tell python to skip numbers in a given
range. If you pass a third argument to range(), Python uses that value as a step size
when generating numbers.

>>>even_numbers = list(range(2,11,2))
>>>print(even_numbers)

See, in this code the range() function starts with the value 2 and then adds 2 to that
value. It adds 2 repeatedly until it reaches or passes the end values, 11 and produces
this result.

96
Yash: Got it.
Akhil: You can do a whole lot of stuff using the range() function. You can create a list
of even numbers, odd numbers, squares, cubes etc.
Yash: Great. What are the other functions we can use on numeric lists?
Akhil: Python provides some inbuild functions like

• min()
• max()
• sum()

Let’s, take an example.

>>>numbers = [1,2,3,4,5]
>>>print(min(numbers))
1

97
>>>print(max(numbers))
5
>>>print(sum(numbers))
15

Yash: Great. We can do lot of things with python. Good, I am learning python. This
will help me a lot in doing my homework.

Akhil: Exactly. Python is very useful. Good job Yash. We have come a long way.
Let’s have some fun tomorrow. See you soon.
Yash: See you! Bye.

98
Exercise:
1. Create a list of 5 animals you like.
(1) Use a for loop to print each animal’s name.
(2) Create a separate statement for each animal and print it in for loop.
(3) Add an end statement saying you love these animals.
2. Create a list of food items you love.
(1) Use a for loop to print each items name.
(2) Create a statement like “I love chocolates” for each food item.
(3) After the for loop, print an end message.
3. Create a list of first 100 natural numbers.
(1) Find the sum of numbers.
(2) Print the sum and the list.
4. Create a list of first 10 odd numbers.
(1) Find the sum.
(2) Print the sum and the list.
5. Create a list of multiples of 5.
(1) Print the list.

99
Fun Fact:

The World’s First Computer Programmer was a renowned Female


Mathematician.
Born in London on December 10,1815, Ada Lovelace, the daughter of the famous
poet Lord Byron, was an extremely talented mathematician. Later on, in life, she
would work closely with Charles Babbage, a popular mechanical engineer responsible
for creating one of the earliest mechanical computers.
From there, she would write a theory about coding a machine to calculate Bernoulli
numbers. The subsequent code would eventually become the first algorithm carried
out by a machine, and in essence, was the first computer program.

100
CHAPTER 9: FUN WITH PYTHON

Next Day….
Akhil: Hey Yash! Looking very happy today?
Yash: Yes, you said today we will have fun, right?
Akhil: Oh Yeah. Even I am excited to show the fun part of python. Come, let’s dive
in.
Yash: Sure, but what are we going to do with python that’s fun?
Akhil: I will show you four fun modules in python.
WIKIPEDIA To get information about anything
MATPLOTLIB To plot some graphs
PLOTLY To show you some places on a world map
TURTLE For drawing

Yash: Looks very interesting. Let’s dive in.


Akhil: First, let’s see what a module is.
Yash: Ok
Akhil: A module is a file consisting of python code. It can define functions, variables,
and also include runnable code. Any python file can be referenced as a module. A file
containing python code, for example: test.py, is called a module and its name would
be test.
Modules helps in reducing the redundancy of code and also makes tasks easier.
Yash: Ok, got it. But how can we use a module?
Akhil: To use a module in python, first you need to download the module. Next
import the module in to the code, where you want to use it.

101
Yash: Can you show some examples?
Akhil: Sure, let’s start with our Wikipedia module. To download Wikipedia module,
open your command prompt (type command prompt in start menu) and enter the
command.
pip install Wikipedia

Once it got installed, close the command prompt and open the IDLE.
Yash: Yes, let me do it.
Done. What next?
Akhil: Cool. Since you have Wikipedia module downloaded, we can now import and
use it.
Yash: But what is the use of Wikipedia module.

102
Akhil: Wikipedia is one of the largest and most popular sources for information on
the internet. Simply, we can call Wikipedia as an online encyclopedia.
Yash: Got it. But how will python use it?
Akhil: Wikipedia module is used to retrieve information from the online Wikipedia
website. We need to give some search item for the python, then pythons Wikipedia
module retrieves the relevant information and prints it for us.
Yash: Great. Can we test it?
Akhil: Sure, follow the code.

>>>import Wikipedia

In this line, we are telling python to import the Wikipedia module.

>>>info = Wikipedia.page(“Python Programming”)

In this line, we are telling python to retrieve information related to python


programming.

>>>print(info.summary)

In this line, python prints the summary of the information it retrieved.

103
See, we got some good, relevant information about python programming.
Yash: Cool. So, I can get information about anything right?
Akhil: Yes, anything.
Yash: Great. This is very helpful. I can now find relevant information about anything
easily.
Akhil: Yes, python has many other fun features. Do you love graphs?
Yash: Yes, I love math and graphs.
Akhil: Great, then our next topic will be interesting. It is called matplotlib.

104
Yash: What is matplotlib?
Akhil: matplotlib is a plotting library for the python programming language.
Yash: So, what are we plotting now?
Akhil: Look at this information.

Popular programming languages - 2020


Python 23.47%
JavaScript 20.73%
Java 19.41%
C# 7.31%
PHP 6.21%
C++ 5.74%
C 4.67%
R 3.71%
Others 8.75%

Let’s plot a pie chart for this data.

105
Yash: I love pie charts.
Akhil: Great, we will use matplotlib module to draw the pie chart. First, let’s
download the matplotlib module from the command prompt.

Yash: Sure, Doing it.


Done.
Akhil: Great. See, this is the code.

>>>import matplotlib.pyplot as plt

In this line, we are telling python to import matplotlib.pyplot as plt. So instead of


using matplotlib.pyplot , we can use plt as a short notation.

106
>>>y = [23.47, 20.73, 19.41, 7.31, 6.21, 5.74, 4.67, 3.71,
8.75]
In this line, we are creating a list y, which contains the percentage values that we want
to plot in the pie chart. Note that the sum of the values in y should be 100.

>>>plt.pie(y)
In this line, we are telling python to create a pie chart for y.

>>>plt.show()
In this line, we are telling python to show the plot that we made.

107
Yash: Great! Pie chart looks awesome. Is there a way to make it look more clear?
Akhil: Yes, matplotlib has lot of additional features. We can add labels to the data,
create a legend to make it clearer and even explode a special item to highlight it.
Yash: Ok. Could you give me a demo?
Akhil: Sure, let’s modify the previous example and explode the ‘python’ item in the
list. Observe the code.

>>>import matplotlib.pyplot as plt

108
>>>y = [23.47, 20.73, 19.41, 7.31, 6.21, 5.74, 4.67, 3.71,
8.75]
>>>mylabels = [“Python” , ”JavaScript” , ”Java” , ”C#” , ”PHP”
, ”C++” ,”C” , ”R” , ”Other”]
>>>myexplode = [0.2,0,0,0,0,0,0,0,0]
>>>plt.pie(y,labels=mylabels,explode=myexplode, shadow = True)
>>>plt.legend()
>>>plt.show()

109
See, now the pie chart looks clearer.
Yash: Yes, looks beautiful and clean.
Great, loving python. What will we do next?
Akhil: Let’s go on a world tour.
Yash: you are kidding right?

110
Akhil: Not really. Let’s go on a world tour virtually.
Yash: What do you mean?
Akhil: I mean, let’s create a world map and draw the places you want to visit.
Yash: Ok, now I got it.
Akhil: For this, we will use plotly module.
Plotly is used to create interactive visualizations as easy as writing one line of python
code.
Yash: Cool. Show me then.
Akhil: Sure, as always, you need to download plotly module from the command
prompt.
Yash: Ok. Doing it.
Done.
Akhil: In order to plot a place on a world map, we need the name of the place, latitude
of the place and longitude of the place. See, this is the data, we are using.

Place Name Paris London Rome Dubai Bangkok


Latitude 48.856613 51.507351 41.902782 25.204849 13.756331
Longitude 2.352222 -0.127758 12.496365 55.270782 100.501762

This is the code.

>>>from plotly.graph_objs import Scattergeo,Layout


>>>from plotly import offline
>>>names = [‘Paris’,’London’,’Rome’,’Dubai’,’Bangkok’]

111
>>>preference = [5,4.5,4,4,3.5]
>>>lat = [48.856613, 51.507351, 41.902782, 25.204849,
13.756331]
>>>lon = [2.352222, -0.127758, 12.496365, 55.270782,
100.501762]
>>>data = [{‘type’:’scattergeo’ , ’lon’:lon ,
’lat’:lat,’text’:names,’marker’:{‘size’:[5*mag for mag in
preference],’color’:preference,’colorscale’:’Viridis’,’reverses
cale’:True,’colorbar’:{‘title’:’Magnitude’},},}]
>>>my_layout = Layout(title=’World Tour’)
>>>fig = {‘data’:data,’layout’:my_layout}
>>>offline.plot(fig,filename=’world_tour2.html’)

Let’s, run this code.


Note: After running this code, a new html file will be opened and it will ask you to
select a browser to show the output. You need to select a browser of your choice.

112
Note:
Refer to this code image, if you made any typing mistake. The code should be same.
Else, you will get errors.

113
See, we got our world map with places we want to visit being plotted.
Yash: Yeah. Awesome.
Akhil: See, we can do lot of stuff with python. Python is fun.
Yash: Sure, it is. You said, we can draw in python. How?
Akhil: Yes, we can. Our next module ‘turtle’ helps us to draw in python.
Yash: Turtle!! Sounds strange, but show me please.
Akhil: Sure, I will show you some basic commands in turtle module today.
Yash: Ok.
Akhil: The turtle is a module that has all the commands you need for drawing. As
always, first you need to import the turtle module.
Yash: Should we need to download the turtle module?

114
Akhil: Don’t worry, turtle module is predownloaded in python. You just need to
import it. Follow the code.

>>>import turtle
We now imported the turtle module.
Yash: Yes.
Akhil: First thing we need to do while using turtle module is to create a canvas on
which to draw. We can do this, by using the pen function like this.

>>>t=turtle.Pen()
‘P’ should be capital. See, if you press the return key, you will get a blank screen with
an arrow in the center like this.

115
You can think of this as a piece of paper on which you want to draw. The arrow mark
in the center of the screen is our turtle.
Yash: Ok.
Akhil: Now, let’s try to move our turtle and draw something. Some basic movements
that our turtle can do are: move forward and backward and turn left and right by
varying degree. Let’s start by moving it forward. Type this code.

>>>t.forward(50)

Yash: Ok.

116
Akhil: What this command does is, it makes our turtle move forward by 50 pixels.
Yash: What’s a pixel?
Akhil: A pixel is the smallest point on the screen. In fact, the whole computer screen
is made up of tiny dots, each of which is called a pixel.

So, let’s see the output.

117
See, the turtle has drawn a line by moving 50 pixels forward. Now, let’s tell the turtle
to turn left. You can make turtle move either way, but let’s move it left for now.

>>>t.left(90)

What this does is, it tells the turtle t to turn left by 90 degrees. I’m sure you’ve learned
all about angles in school, right?
Yash: Yes, I have.
What if I wanted it to turn right? Should I just type right instead of left?
Akhil; Absolutely. Follow this diagram to see how your turtle face will turn at
different degrees.

Yash: Thanks, Akhil. That’s really helpful. What should we do after turning our turtle
by 90 degrees?
Akhil: Now, we draw another line of 50 pixels in this direction. Can you try this one?

118
Yash: Yes, I can.
>>>t.forward(50)

See, got it. I think I can make a square with it. Let me try.
Akhil: sure, go ahead.
Yash: So, the code will be.

>>>t.left(90)
>>>t.forward(50)

119
>>>t.left(90)
>>>t.forward(50)

Ok, let’s see the output.

Akhil: Good job Yash. Now you know how turtle works. I will introduce you to the
full turtle module tomorrow. This is good for today. Did you have fun?
Yash: Absolutely. Now I love python more than any other subject. Thank you Akhil.
Akhil: It’s my pleasure. Let’s have more fun with turtle tomorrow. See you soon.
Yash: See you, Bye!
120
Exercise:
1. Find some information about the inventor of python programming: “Guido van
Rossum” using Wikipedia module.
2. Draw a pie chart similar to this one.

3. Print some information about your favorite sports game using Wikipedia.
4. Draw a rectangle using turtle module.

121
Fun Fact:

The First Programming Language was called FORTRAN.


It was developed by a team lead by Mr. John Backup, an American computer
scientist. First appearing in 1964, FORTRAN is still in use today, predominantly
helping computer scientists to conduct complex tests in areas such as numerical
weather prediction, geophysics, crystallography, and computational chemistry.

122
CHAPTER 10: DRAWING WITH PYTHON

Next Day……...
Akhil: Hi Yash! Yesterday was fun right?
Yash: Sure, it is. Excited for today’s learning.
Akhil: Yes, I am excited as well. Let’s dive in.
Yash: Yes.
Akhil: So, you know how turtle works, you even draw a square yesterday.
Yash: Yes, I draw a square yesterday.
Akhil: Good, now let’s see few more basic commands in the turtle module.
Yash: Sure.
Akhil: type this command.

>>>t.reset()
and press return key.

See the output.

123
124
Yash: Hey! Where did my square go? you deleted my square.
Akhil: Yes, I used the reset() function to tell python to delete everything that turtle t
had created.
Yash: Interesting, can my turtle do moonwalk?
Akhil: You mean, can it move backward while drawing?
Of course, instead of typing t.forward(), you just use the t.backward() like this.

>>>import turtle
>>>t=turtle.Pen()
>>>t.backward(50)

125
See.
Yash: Cool. But while drawing, we might need to move our position without drawing
anything right. How can I do that?
Akhil: In that case, we use the turtles ‘up()’ function. Let’s see a demo.
But first, let’s turn our turtle left by 90 degrees. So, type this.

>>>t.left(90)
>>>t.up()
>>>t.forward(30)

126
If we look at the turtle now, you see. It’s moved forward 30 steps without drawing
anything.

127
Now, suppose if I want to draw another line parallel to the line I had drawn earlier.

So, I put my pen down again by using the turtles ‘down()’ function and continue.

>>>t.down()
>>>t.right(90)
>>>t.forward(50)

See, after I use the down function, I made the turtle turn right by 90 degrees and then
made it move forward by 50 steps, finally to make your turtle disappear , so that you
can only see what you’ve drawn type this.

>>>t.hideturtle()

128
129
There, we got out parallel lines and the turtle disappeared because of hideturtle()
function.
Yash: Understood. What else can we draw with turtle?
Akhil: You can draw circles too. Let’s see a demo. Type this code.

>>>t.reset()
>>>t.circle(50)

This, will create a circle of radius 50, you can change this value depending on how big
you want the circle to be.
Now, if I press the return key.

130
See.
Yash: Wow. This is so cool. Can I change the color?
Akhil: Sure, you just add the following lines.

>>>t.reset()
>>>t.color(‘red’)
>>>t.circle(50)

First line will clear the screen, as you know. The second line will change the color of
the turtle to red.
These are some of the commonly used colors in python.

black blue brown


coral cyan Dark Blue
gold green grey
chocolate magenta maroon
orange pink red
khaki tan tomato
violet white yellow

The third line will then draw your circle in red. Now, let’s see the output.

131
You see, there is more, you can even fill the circle with a different color like this.

>>>import turtle
>>>t=turtle.Pen()
>>>t.fillcolor(‘yellow’)
>>>t.begin_fill()
>>>t.circle(50)

132
let’s see the output.

Yash: It just drew the circle, but didn’t fill it with color.
Akhil: wait for it, I didn’t yet add a very crucial line.

>>>t.end_fill()

Then I press return key.

133
Yash: Wow, that’s beautiful. Can I do the same when drawing anything?

134
Akhil: Yes, provided your drawing is closed in the end so that the fill color doesn’t
leak out. Make sure, you give your end_fill() command only after you’ve closed the
loop.
Yash: Yeah! This is so much fun. Thanks for all these Akhil.
Akhil: Don’t mention. Let’s see iterative drawing now.
Yash: What is that?
Akhil: You know for loop right. So, we will draw repeatedly using a for loop to create
interesting drawings.
Yash: could you give some examples please?
Akhil: sure, let’s draw a triangle. Follow the code.

>>>import turtle
>>>t=turtle.Pen()
>>>for i in range(3):
t.forward(100)
t.right(120)

See, in line three we started for loop to iterate for three times. Inside the loop, we said
python to draw a line of 100 pixels and then turn right by 120 degrees. So after the for
loop, we should get a perfect triangle.
Let’s see the output.

135
136
See, we got a triangle . This is similar to the square we had drawn last time, but using
a for loop. Let’s draw a square using for loop.
Yash: Ok.
Akhil:
>>>import turtle
>>>t=turtle.Pen()
>>>for i in range(4):
t.forward(100)
t.right(90)

see, in this code, we created a for loop to iterate for 4 times. Next we said python to
draw a line of 100 pixels and turn right by 90 degrees for each loop. So at the end we
get a perfect square.

137
Similarly, you can draw different shapes using for loop.
Yash: Great! Really interesting.
Akhil: So, you know how to draw and color them in python. Great.
This is good for today. Let’s meet again tomorrow.
Yash: Ok, have a nice day.

138
Exercise:
1. Draw a hexagon using for loop.
2. Draw this image in turtle module.

3. Draw a circle inside a square.


4. Draw a circle, square and rectangle.
Fill each with different colors.
5. Draw this

139
Fun Fact:
For this fun fact, let’s draw the cause of the world pandemic, corona virus (its
structure) using turtle.
>>>import turtle
>>>t=turtle.Pen()
>>>t.color(‘green’)
>>>for x in range(210):
if x in range(50):
t.hideturtle()
else:
t.forward(10+x)
t.left(x)

140
Output:

141
CHAPTER 11: IF STATEMENTS

Next Day…….
Akhil: I need to say this Yash. ‘You are on fire’. Now you can do a lot with python.
Yash: Yeah! Thank you. You are the one who taught me all this stuff.
Akhil: Actually, I am learning with you. Anyway, do you remember how we move
our turtle forward or backward and turn left or right. But what if you wanted the turtle
to decide whether it wants to turn left or right? Or How many steps it wants to move
forward?
Yash: Is that even possible?
Akhil: Of course, if you use ‘if’ statements, also known as condition statement. But
first, I think it’s about time we started making our codes more interactive. We want to
allow the user to have a say. So, we allow the user to give their input using the input()
function. Also, we want to type out our code all at once and then run it instead of
executing line by line.
For that, we simply click on file and then select new file from the drop-down menu.

142
The advantage of this is also that we can save our entire code to view it again later
on.
Yash: Ok. Could you give me a demo please?
Akhil: Sure, let’s run this code and save it firstprogram.py .

name = “Yash”
print(“HI %s! Welcome to python programming” % (name))

After this, you click “File” menu and select “Save As..” option from the drop-down
menu. Then, you will see a prompt like this.

143
Now, enter the File name in the text field and click on ‘Save’.
Now, you can run the program by clicking on ‘F5’. You should see the output like
this.

144
Yash: Got it. This is easy. I guess, writing all code at once and running it is simpler
than executing each line.
Akhil: Yeah! You can also reuse it by simply pressing ‘F5’. Now, let’s learn how to
use the input() function. I will type the code and I want you to run it as the user.
Yash: Sure.
Akhil:
name = input(“Enter your name: “)
print(“%s is a good person. “ % (name))

to run the program first, save it with a name of your choice and just press the ‘F5’ key.
Yash: Ok, let me try.

Yeah! Got the output.

145
Akhil: So now, we can utilize the user input to make our code more useful and
interesting. Let’s move to the if statements. The syntax for an if statement is like this.

If condition :
Action

The condition here can be any statement that needs to be true for the action to be
taken. Let’s see an example.

If condition: ask’s your age, if age>18


Action print that you are eligible for voting.

The code goes like this.

age = int(input(“Enter your age: “))


if age>18:
Print(“You are eligible for voting”)

You see here, after taking the input from the user, we are converting it to integer and
assigning It to the variable age. Python will treat every input as a string. So, we need
to convert it into an integer to do comparison with other integers. Then, the if
statement analyzes to see if the value in age is greater than 18. You see, I put a ‘>’

146
sign in the condition. When you do comparisons, you should use some symbols like
this.
> Compare if left is greater than right.
< Compare if left is less than right.
== See if left is equal to right
>= Compare if left is greater than or equal to
right
<= Compare if left is less than or equal to
right
!= Compare if left is not equal to right

So, after the condition is evaluated. If the result is true, python executes the lines next
to the if statement. Notice, I have indented the lines in the action part to tell python
that these are part of the if statements action. You need to make sure that all the lines
are indented by the same amount of space.
Now, let’s execute this code. Press F5 after saving the code.

147
Yash: Ok, got it. What if I had entered some other number?
Akhil: Maybe, if you gave a number greater than 18, the condition will be true and the
output will be different. See for yourself, run it again by pressing F5.

148
Yash: But, why didn’t python print anything for age less than 18?
Akhil: In that case, we use another variation of the if statement. It’s called the
“If – then – else” statement. Like this.

age = int(input(“Enter your age: “))


if age>18:
print(“you are eligible for voting”)
else:
print(“You are not eligible for voting”)

Now, if you run it. You will see output like this.

149
See, the logic is working fine.
Yash: Yeah, understood.
Akhil: Let’s take one more example. See this code.

name = input(“Enter your name: “)


if name == “Yash”:
print(“you are very nice”)
print(“you are smart”)
else:
print(“You are good”)

See, in this we are taking the name as an input. After that we compare it to “Yash”. If
both are equal, the block below the if statement (if block) will execute. If both are not
equal, else block will execute.
150
Let’s see the output.

See, we are getting different outputs for different inputs.


Yash: Great. But , what if I want to tell python to print one thing , if your name is
‘Yash’ another thing if your name is ‘Akhil’ and something else altogether for
everything else?

151
Akhil: In that case, we use yet another variation. Its called Elif condition statement.
Let’s see an example.

name = input(“Enter your name: “)


if name == “Yash”:
print(“you are very nice”)
elif name == “Akhil”:
print(“You are good”)
else:
print(“You are not in the team”)

Here, python will first check if the name entered is Yash, if the answer is false, it will
check if the name is Akhil. If true, it will execute the next line, if false it will execute
the last line.
You can have as many elif conditions as you require.

152
See, the logic is working fine.
Yash: Nice, what if I want more than one comparison to be done together? How do
we do that?
Akhil: That’s a good question. We have a way; you can even combine more than one
comparison in one condition. Let’s see an example.

name = input(“Enter your name: “)


if name == “Yash” or name ==”Akhil” :
print(“We are friends”)
else:
print(“Hey buddy.”)

153
Here, when a name is entered, python checks if either of the conditions in the if
statement is true. If so, it executes the first print statement and if it finds that nothing
of the two conditions is true, meaning if the name is neither “Yash” nor “Akhil”, it
executes the print statement after the else block.
Let’s see the output.

154
you can also use an ‘and’ operator instead of ‘or’. Let’s see an example.
Suppose, if your age is between 1 and 12, print as child and if your age is between 12
and 19, print teenager.

age = int(input(“How old are you?”))


if age<13:
print(“you are a child”)
elif age>=13 and age<=19:
print(“you are a teenager”)
else:
print(“you are an adult”)

Here, after the user input, python converts it to an integer and checks if its less than
13. If true, it prints ‘you are a child’. If false, it moves on to the elif statement and
checks if the age is more than or equal to 13 and also less than or equal to 19. If true,
it prints ‘you are a teenager’. If false, it just goes to the else statement that prints ‘you
are an adult’.
Let’s run this.

155
See, we got our output as expected.
Yash: Understood.
Akhil: One more thing before wrapping up. So far, we’ve entered strings and numbers
as values and used them to compare. But what if we want python to first see if a
variable has a value in it or not before comparison? In such cases, we use the “None”
value.

156
A variable with a “None” value is an empty variable. In fact, an empty variable is
different from a variable having a value 0.
Yash: But, why use it?
Akhil: Well, programmers often use it when they want to define all variables together
in the beginning, but don’t want to give a variable any value just yet. Let’s see an
example.

var = None
if var == None:
print(“The variable is empty”)

let’s see the output.

157
See, we got the output.
If statements are crucial for any programming language. You understood them right?
Yash: Yes! Clear.
Akhil: Ok then. See you tomorrow.
Yash: Ok! Bye.

158
Exercise:
1. How to define an empty variable?
A. Var = 0
B. Var = None
C. Var = “Empty”
D. Var = “ ”
2. How to check if both conditions are true in an if statement?
A. Using ‘or’
B. Using ‘and’
C. Using ‘==’
D. Using ‘>=’
3. Write a program to take user name and user’s password as inputs. Check if
password is equal to ‘pass@123’. If so , print welcome message. Else print
error message.
4. Write a program to calculate the bill at a shopping mall counter. Take user’s
name, total number of items, cost of each item. Find the total cost. If total cost
is more than 10000, give a discount of 1000. Print the bill.
5. Use turtle module to draw a square or circle based on user input.

159
Fun Fact:

Computer Programming was instrumental in helping end World War II


Alan Turing was another incredibly famous mathematician who was also born in
England, on June 23, 1912. In the computer science community, he is predominantly
recognized as the father of modern-day computer science.
However, alongside this lofty title, he was also responsible for helping the allies bring
World War II to a close. During the height of the large-scale conflict, he would use his
skills to crack the Enigma machine, a cipher utilized by the Nazis to protect their
military communications.

160
CHAPTER 12: FUNCTIONS

Next Day…...
Akhil: Hey Yash! How was your practice going on?
Yash: Pretty good actually. With all the stuff you taught me, it’s really easy to
practice programming now.
Akhil: Yeah.
Yash: I have a question. Loops are good enough when I want to repeat some lines
consecutively over and over. But what if I want to repeat some lines of code many
times but not consecutively?
Akhil: That’s a really good question. For problems such as these, Python has got a
very simple solution. “Functions”
Yash: You taught me about functions earlier. Are they both same?
Akhil: Yes, but now we need to understand how it actually works.
A function is a group of code that performs a certain task.
These tasks can then be performed over and over again, whenever needed by simply
using that function.
Yash: So, how do we use functions?
Akhil: As I said, you actually already used few functions before, without even
realizing it.
Ex: list()
range()
Pen()

161
Those were all functions, that’s why they were followed by parentheses, but these
were all built in functions.
However, you can even define your own functions to reuse.

My_function()
Your own function

Would you like to learn how?

Yash: Of-course.
Akhil: Ok. First of all, you need to know its syntax. A function basically composed of
three parts.
• A name
• A body
• Parameters
And, this is how the parts are put together.

def func_name(parameters):
line of code
line of code

Yash: Kind of reminds me of the for loop structure here.


Akhil: Here, func_name is the function name and it can be any name that you like.
But instead follow the rules for naming variables. I hope you remember the rules.
162
Yash: Of-course

• Variable names can contain only letters, numbers, and underscores.


They can start with a letter or an underscore, but not with a number.
For instance, you can call a variable name_1 but not 1_name.
• Spaces are not allowed in variable names, but underscore can be used
to separate words in variable names. For example, new_name works,
but new name will cause errors.
• Variable names should be short but descriptive. For example, name is
better than n, student_name is better than s_n, and name_length is
better than length_of_person_name.
• Be careful when using the lowercase letter l and the upper case letter
O because they could be confused with the numbers 1 and 0.
• Variable names are case sensitive.

Akhil: Good. Next part is the body.


This will contain the code that defines what the particular function does. The
parameters consist of variables that the function will be using. The parameter though,
is not compulsory. You can even use functions without any parameters.
Let’s see few examples.
When you need to use the function, you just call the function by using its name like
this.

>>>func_name(arguments)

Yash: Ok.

163
Akhil: Let’s write our first function.
Suppose, you want a function that says “Hello, welcome to python programming. I am
here to help you.”
So, in the IDLE define the function like this.

>>>def my_function():
print(“Hello, welcome to python programming.”)
print(“I am here to help you.”)

This is a simple function. I am not giving it any parameters, so the space between the
parentheses is blank. After writing the code, press shift + return key or return key
twice. So, we defined our first function called ‘my_function”. Now , whenever I need
my function, I will call the function by using it’s name. like this.

>>>my_function()

Note here, I didn’t put any arguments inside the parentheses. For the time being, just
know that it’s better if your number of arguments is equal to your number of function
parameters. So, If your function has no parameters, you don’t need any arguments
inside the parenthesis when calling the function.
Now, if I press the return key.

164
Yash: Great.
Akhil: You see, by using the function call, you used the function which was meant to
say “Hello, welcome to python programming...”. No matter how many times you
need it, you can just call this function and get this result. You can even call it from
inside any other python code, but we’ll come to that later. To show how functions are
useful see this diagram.

Easier to find Reduces the size of


errors code when writing
large codes

Benefits of using
functions

Simplifies the Allows code to be


coding process reused

165
Yash: Cool. Can you give few more examples?
Akhil: Now, let’s define a function that has one parameter. This function should greet
a person by his name. Let’s define it.

>>>def greet(name):
print(“hi %s” % name)
print(“Nice to meet you %s” % name)

now, press shift + return key or return key twice to let python know, you are done.
Now that your function is defined, you can call it any time. Now, I want to greet
Yash. So, I pass the name Yash as an argument to the function. The argument will be
passed on to the variable name. That means the variable name in the function
parameters will now hold the value Yash. This variable will then be used in the
function to say hi.

>>>greet(“Yash”)
Hi Yash
Nice to meet you Yash.

No matter what argument I pass to the greet() function, it will use that name to say hi.
Let’s try it with the name “Varun”.

>>>greet(“Varun”)
Hi Varun

166
Nice to meet you Varun.

See, we got our output as expected. You can even have more than one parameter in
the function.
Yash: How?
Akhil: Let’s see an example.
Suppose, you want to find the sum of two numbers. So, let’s define a function that
takes two parameters and prints the sum of those numbers.

>>>def sum_of_two_numbers(num1,num2):
print(num1+num2)

167
Simple function. This function takes two parameters, which are this time, numbers.
The function adds those numbers and prints their sum. Let’s try to use this function.
Can you try this one?
Yash: Sure, let me try.

>>>sum_of_two_numbers(3,8)
11

Akhil: Great. You understood the concept of functions well.


Yash: Yeah. Can we save a function in a new file, so we can use it in any other
program?
Akhil: Yes, of-course. Let’s try that now.
Open a new file and remember what name you saved the file with, because that’ll be
important. Remember your program on the cupcake problem?

168
Let’s define a function that will calculate the money you earn each day from your
shop. Let’s call the function per_day_income.
Parameters needed:
• cupcakes_made
• cupcakes_spoilt
• cost_of_each_cupcake
Let’s see, how to define it.

def per_day_income(cupcakes_made, cupcakes_spoilt, cost_of_each_cupcake):

money_earned=(cupcakes_made-cupcakes_spoilt)*cost_of_each_cupcake

print(“income = %s” money_earned)

See, in the function per_day_income, I used the formula that we used to calculate the
money earned each day and finally we print the income in new line. Let’s save this
function by the name ‘cupcakes.py’. You can give it any name you want, but
remember the name of both the function and the file it’s saved in.

169
Now, in another file, I want to calculate and print every day’s income separately. So I
will open a new file. Now I want to tell python to use the function per_day_income()
in this file. To do that, I use the import command like this.

from cupcakes import per_day_income


cost_per_cupcake = 50
made1 = int(input(“How many cupcakes were made on day1 ? “))
spoilt1 = int(input(“How many cupcakes were spoilt on day1 ?”))
print(“Day 1: “)
per_day_income(mode1,spoilt1,cost_per_cupcake)

Here, I got user input for cupcakes made on day1 and cupcakes spoiled. I already
know my cost_per_cupcake, so I didn’t need to get that input from the user. Now, I
call the function per_day_income() to calculate for me and to print how much money I
earned on day1.

170
I do this by using the value of the three variables
• made1
• spoilt1
• cost_per_cupcake
as arguments. If I save this and run it, this is what I will get as output.

Similarly, we can do this for day2, day3 and so on. You can even use loops to make
things easy.
Yash: Great.
Akhil: Let’s get back to our per_day_income() function. In this function, we used a
variable called money_earned. These kinds of variables (variables created inside a
function) are only visible within the function. This visibility is called scope of the
variable. So, the scope of money_earned is only limited to the function it was created
in. The moment the function finishes executing, the variable is destroyed.

171
Yash: So, what if I want to use a result from the function in the main program? Like ,
add up the income_per_day for any number of days?
Akhil: Yes, that becomes a problem since variables of a function don’t have much
scope outside the function. But there’s a solution.
To use the result of the function in some other code, you have to return the result to
the code from the function. Let’s see a demo. I will modify the cupcakes.py like this.

def per_day_income(cupcakes_made, cupcakes_spoilt, cost_of_each_cupcake):

money_earned=(cupcakes_made-cupcakes_spoilt)*cost_of_each_cupcake

print(“income = %s” money_earned)

return(money_earned)

When python comes across a return statement, it knows that its reached the end of the
function and it returns the value within parentheses to the program it was called from.
Remember
• you can only return 1 value.
• a return statement means that it is the end of the function.
So, anything in the function after the return statement will not be executed. Let me
show you , how to use the returned value.
Create a new file and enter the code.

from cupcakes import per_day_income

cost_per_cupcake = 50

total_income = 0

made1 = int(input(“How many cupcakes were made on day1 ?”))

172
spoilt1 = int(input(“How many cupcakes were spoilt on day1 ?”))

print(“Day 1:”)

total_income = total_income + per_day_income(made1,spoilt1,cost_per_cupcake)

made2 = int(input(“How many cupcakes were made on day2 ?”))

spoilt2 = int(input(“How many cupcakes were spoilt on day2 ?”))

print(“Day 2:”)

total_income = total_income + per_day_income(made2,spoilt2,cost_per_cupcake)

print(“Total income = %s” % total_income)

See, we added the per_day_income of two days as total_income and printed the total
income. If we run this.

173
See, we got the total income as 32600. Next let’s use loops to solve the same problem.
Yash: sure.
Akhil: First, let’s calculate the total income for three days.

from cupcakes import per_day_income

cost_per_cupcake = 50

total_income = 0

for i in range(1,4):

print(“Day %s: “ % i)

made = int(input(“How many cupcakes were made?”))

174
spoilt = int(input(“How many cupcakes were spoilt?”))

total_income=total_income+per_day_income(made,spoilt,cost_per_cupcake)

print(“Total income = %s” % total_income)

See, we used for loop to repeat the same code for 3 times. Next, we found the per-day
income for each day and added it to the total income. Finally, we print the total
income.

175
Yash: Great.
Akhil: Now you know, how functions work. This is enough for today. Let’s see one
final topic tomorrow.
Yash: Sure, see you.

176
Exercise:
1. Write a function to take user name as an input and print it 100 times.
2. Write a function that replicates a calculator (should do addition,
multiplication, subtraction and division)
3. Test your calculator function for these inputs.
• 12 +55
• 23 x 45
• 22 / 11
• 64 – 34
4. Define two functions square() and rectangle(). These functions should draw
a square and rectangle respectively when called. Use turtle module.

177
Fun Fact:

The First Computer Virus was created in 1986


Given the moniker Brain, the virus was created by two brothers, Basit and Amjad
Farooq Alvi, in Pakistan. According to the siblings, who ran a popular computer store,
they created Brain to stop their customers from making copies of their software
without permission.
However, unlike traditional viruses, Brain only contained a hidden copyright message
and did not corrupt or delete any of the user’s files or information.

178
CHAPTER 13: CLASSES

Next Day…...
Akhil: Well Yash. You have come a long way. This is our last topic to learn. Let’s
dive in.
Yash: Sure.
Akhil: Now, you know how functions help organize your code and avoid unnecessary
repetition. Well, there’s another useful tool in python that can help organize your code
further. They’re called ‘classes’.
In fact, you had unknowingly used one of these classes when you used the turtle
module.
Yash: Really? Which one?
Akhil: The Pen!
Classes are in essence used to classify things into groups. You can think of a class as a
sort of representation of real-life objects.
Ex: Animals, Birds, Cars, …...
A class in python represents the real life object by grouping together the
characteristics of the objects with things that the object does.
Ex:

‘toy’ characteristics: ‘toy’ functions:

Color: Move about:

Shape: Make sound:

Design:

179
‘animal’ characteristics:
‘animal’ functions:
Color:
Walking:
Height:
Eating:
Weight: Sleeping:
How many legs: Making noise:

Yash: Ok.
Akhil: You see, classes in python are described in the same way, only that the
characteristics of the class are called attributes of that class and the functions are
called the methods of that class.
Yash: But, why use classes?
Akhil: Let’s see some benefits of classes.

BENEFITS OF CLASSES AND OBJECTS

1. Encapsulation: Grouping together everything relating to an object into


a single entity.
2. Represent real life objects more accurately.
3. Keep your code organized.
4. Allows code to be reused.
5. Easier to modify and maintain.

180
Yash: Wow, that’s a lot of advantages. So, how do I use it in python.
Akhil: Well, this is the syntax.

class className:
attributes
methods

Yash: Ok, can you give some examples?


Akhil: Ok. Let’s say , you want to define two classes.

class class

‘animals’ ‘toys’

This is the code to do that.

181
class animals:
pass
class toys:
pass

see, the statement pass means that you don’t want to add anything to the class just yet,
you simply want to declare to python that you want to create two classes called
animals and toys.

Yash: Ok.
Akhil: Now, Yash I want you to open a new file and declare a class called cat.
Yash: Ok.

class cat:
pass

Akhil: Ok, now it’s time to add some characteristics and functions to the class. In
other words, let’s add some attributes and methods to the class. Tell me Yash, what
attributes would a cat have?
Yash: Let’s see
Well, it would have
• A pair of eyes
• Four paws
182
• A furry body

Akhil: Ok, let’s add these attributes to our class called cat.

class cat:
eyes = 2
paws = 4
body = “furry”

Now, what functions would it have?


Yash: Well, it would
• Walk
• Catch mice

Akhil: So, this is how I want to write my cat’s functions. I hope you remember how to
write a function. The method of a class is defined in the same way, but only in
indented form.

class cat:
eyes = 2
paws = 4
body = “furry”
def walk(self):

183
print(“I am walking”)
def catch_mouse(self):
print(“I caught a mouse!”)

You notice, I used the word self as a parameter for both the methods and the class. I’ll
explain in a while, why I did that. But just know that whenever you define a method
for a class, the first parameter for that function should always be given as ‘self’.
That’s usually the norm.
So, when I call the walk() method, it should print the sentence “I am walking”. When
I call the catch_mouse() method, it should print the sentence “I caught a mouse”.
Yash: Ok.
Akhil: Good. We are done with defining our class, now it’s time to bring this class of
art to some use. I had told you earlier that classes help to reduce code. So once your
class is created in python, you can reuse its attributes and methods as many times as
you like by creating objects of that class.

An object is an instance of a class.


184
Ex: for the class cat, you can have an object called Tom and another called Bella.
Both Tom and Bella are instances of the type cat. In other words, they’re both objects
of the class cat.
So, both tom and bella will have same attributes and functions that we defined in a cat
class. Now, we know that Tom and Bella are cats, but how do we tell python that?
Yash: How?
Akhil: We tell it by defining Toma and Bella as objects of the class cat. Here’s how.

Tom = cat()
Bella = cat()

This is the syntax of defining an object. We write the name of the object, followed by
the class name and then parentheses. Now, if I want to know how many eyes Tom
has, I simply do this.

print(Tom.eyes)

185
The same way, if I typed Tom.body, it would give me ‘furry’ as the result.
Let’s check for Bella too.

print(Bella.eyes)

186
So, you see both the objects Tom and Bella have the same attributes. Let’s now ask
Tom to walk. We can do this by calling the method walk.

Tom.walk()

187
Bella.catch_mouse()

188
Now, let’s try to make Tom and Bella talk. We want them to say how many eyes and
paws they have. So, let’s make some changes to the class.

def speak(self):

Print(“Hi, I am a cat. I have %s eyes and %s paws.” % (self.eyes, self.paws))

Yash: Why did you type self.eyes and self.paws in the print statement instead of just
eyes and paws.
Akhil: sharp observation. If we had only put eyes and paws, we would have gotten an
error. This is because the variables eyes and paws are not accessible within the
speak() method directly. We need to explicitly tell python which object’s eyes and
paws are we talking about.
The parameter ‘self’ is basically a temporary placeholder that holds the object itself.

189
The method of an object is called

The
object
itself

The object itself is passed as an argument to that method


and is placed in a variable called ‘self’.

That’s why, we always put self as the first parameter for every method of a class.
Yash: Ok. Now I understood.
Akhil: This allows the method and the object to use other methods or attributes within
the object. Now, let’s test it out. Let’s ask Tom to speak. Will you try this one?

Yash: Sure.

Tom = cat()
Tom.speak()

Let’s see the output.

190
Akhil: Great.
Yash: What if I want each cat to say its own name? I cannot add the name as an
attribute of the class cat. Because, for each object(cat), the name will be different.
Akhil: Yes, you’re right. It’s very natural for objects of a class to have certain
attributes of their own.
Ex: Name, Height, Weight, Breed ….

191
For this, we use an __init__() function which is called as soon as an object of a class
is created. The init function is a special type of function and is always called
whenever we want to initialize some properties of a class.
Note: __init__() has two underscores before , two underscores after the word init.
So, let’s modify our code.

class cat:

eyes = 2

paws = 4

body = ‘furry’

def __init__(self,name_of_cat):

self.name = name_of_cat

def walk(self):

print(“I am walking”)

def catch_mouse(self):

print(“I caught a mouse!”)

def speak(self):

print(“Hi, My name is %s” % self.name)

print(“I have %s eyes and %s paws.”%(self.eyes, self.paws))

As for any other class method, the init method should also have the self parameter. In
addition to that, we use a parameter called name_of_cat. What the init method in this
example will do is , create an attribute for the cat class called ‘name’ and it will give it
the value that will be passed as an argument when the object is created. Let’s also

192
change the speak method. This statement will print the name of the cat when the speak
method is called.
Now, let’s test it.

Tom = cat(“Tom”)
Bella = cat(“Bella”)
Tom.speak()

193
See, I passed the name Tom as an argument, since an init method has been defined for
this class. It will be called as soon as the object is created and python will pass the
value Tom, as the parameter name_of_cat. Similarly for Bella. Now, when I called the
speak() method , we got our output.

Yash: Let me try asking Bella to speak.

194
Great, Both Tom and Bella can now say their own names. This is fun.
Akhil: In this way, you can create as many cat objects as you like. You could also
have added other cats like Happy, Jos, Lexa, Alex and so on.
I had mentioned in the beginning that the turtle module has a class called Pen. It
contains all the variables and functions that our turtle will need. See, now you got to
understand how classes and objects works. This is enough. I suppose you are ready for
tomorrow’s assignment.
Yash: Yes. I am eagerly waiting for the assignment.
Akhil: Yeah. Let’s rock tomorrow’s assignment.
Yash: Sure, we will.

195
Exercise:
1. Make a class called Restaurant.
Attributes: restaurant_name, cuisine_type
Methods: describe_restaurant()
2. Test your restaurant class by creating three different restaurant objects.
3. Make a class called User.
Attributes: first_name, last_name, age, address.
Methods: describe_user(), greet_user()
4. Test your user class by creating two user instances.
5. Make a class called Bank.
Attributes: name, balance
Methods: deposite_money(), withdraw_money(), print_balance()
6. Test your Bank class by creating a new Bank instance.

196
Fun Fact:

The First Computer ‘BUG’ was an actual real-life bug.


In the programming world, a bug is an error that causes a program to crash or behave
in strange ways. First coined by Thomas Edison in 1878, the term ‘bug’ would
eventually find mainstream use in modern computing.
However, it was in 1947 that the first case of a computer bug was recorded. Grace
Hopper, an admiral in the US Navy, was working on a Mark 11 computer when she
discovered a moth had become stuck in the relay, thus causing it to malfunction.
Once the moth was removed, she wrote in her journal “first actual case of bug being
found” – and the rest is history.

197
CHAPTER 14: CONCLUSION

The assessment day had finally arrived. Both Yash and Akhil were confident about
their python programming skills, on the other hand Dany was also confident. The
teacher handed out the assessment papers to every student and the assessment had
begun. The assessment was for 1hour 30 minutes.
Every student was confident about the paper and gave their best to top the assessment.
Later that day, the assessment results were declared. Both Yash and Akhil topped the
assessment with great margins. The teacher was delighted with their performance and
gifted both of them with two personal laptops. Yash and Akhil were overjoyed with
the happenings around them. Dany was sad. He realized that criticizing others was a
mistake and decided to change his ways. He appreciated Yash and Akhil for their
performance. They all became friends thereafter and stayed happy.

------- The End -------

*python programming assessment is in the next page.


198
MAIN SCHOOL
PYTHON PROGRAMMING ASSESSMENT
TIME: 1HR 30MIN MAX.MARKS: 100

General Instructions

1. The question paper is divided into two sections A and B.


2. Section A is theory part and is of 40 marks.
3. Section B is programming part and is of 60 marks.
4. Students should attempt all the questions without fail.

Section - A

Q.N. Answer the following questions in three to five sentences each. (5 x 8 =40)
1. What is __init__()?
2. What is the difference between a parameter and an argument?
3. What is scope?
4. What does range(1,10,2) return ?
5. What is a variable?

Section-B

Q.N. Write the code for the following questions. (3 x 20 =60)


1. Write a program to print the multiples of 3 or 5 between the range 0 and
limit(parameter). The user should enter the limit value. For example, if limit
is 20, it should print
3, 5, 6, 9, 10, 12, 15, 18, 20.
2. Write a function called check_number that takes a number.
1. If the number is divisible by 3, it should return “Happy”
2. If it is divisible by 5, it should return “Programming”
3. If it is divisible by both 3 and 5, it should return “Happy
Programming”.
4. Otherwise, it should return the same number.
3. Create a class called Vehicle.
Attributes: max_speed
Mileage
Methods: describe()
199
show_mileage()

define the init method to give the instance variables. Test this class by
creating 2 instances of vehicle class.

200
SOLUTIONS

CHAPTER 2:

1. C
2. D
3. E
4. C
5. D
6. print(“Lokesh Gajula”)
7. print(“My friends name is Ravi, he is a very good
boy.”)
CHAPTER 3:
1. C
2. D
3. B
4. A
5. C
6. my_number = 21
print(“My number is %s” % my_number)
7. no_of_chocolates = 32
cost_of_each_chocolate = 2
total_cost = no_of_chocolates * cost_of_each_chocolate
print(“Total cost=%s” % total_cost)
8. principle = 10000
no_of_years = 5
rate_of_interest = 5
simple_interest =
principle*no_of_years*rate_of_interest/100
print(“Simple Interest = %s” % simple_interest)
CHAPTER 4:
1. name = “lokesh gajula”
print(“Hi everyone, my name is %s” % name)
2. name = “lokesh Gajula”
print(name.lower())
print(name.upper())

201
print(name.title())
3. quote=”Nepoleon Hill once said, ‘No man is ever
whipped, until he QUITS in his own mind’.
print(quote)
4. name = “Lokesh”
surname = “Gajula”
age = 22
print(“Hi! My name is %s %s, I am %s years old” %
(name, surname, age))
5. name = “John”
tv_on_weekdays = 2
tv_on_weekends = 3
total_tv = 5*tv_on_weekdays + 2*tv_on_weekends
print(“%s watches %s hrs of tv every week” % (name,
total_tv))
6. print(‘’’ Shouldn’t
Couldn’t
Wouldn’t are
Things you
Shouldn’t say.’’’)
CHAPTER 5:
1. family = [“Mohan”,”Lakshmi”,”Mahesh”,”Latha”]
print(family[0])
print(family[1])
print(family[2])
print(family[3])
2. print(“My father name is %s. Hi dad” % family[0])
print(“My mother name is %s. Hi mon” % family[1])
print(“My sister name is %s. Hi %s” % family[3])
3. friends = [“ravi”,”Krishna”,”murali”,”pavan”,”valli”]
friends_ages = [21,20,20,21,22]
favourite_candies =
[‘pulse’,’melody’,’parle’,’eclairs’,’coffybite’]
print(“%s is %s years old, he loves to eat %s” %
(friends[0],friends_ages[0],favourite_candies[0]))
print(“%s is %s years old, he loves to eat %s” %
(friends[1],friends_ages[1],favourite_candies[1]))
print(“%s is %s years old, he loves to eat %s” %
(friends[2],friends_ages[2],favourite_candies[2]))

202
print(“%s is %s years old, he loves to eat %s” %
(friends[3],friends_ages[3],favourite_candies[3]))
print(“%s is %s years old, she loves to eat %s” %
(friends[4],friends_ages[4],favourite_candies[4]))
4. guests_list = [“Mr Sharma”, “Kiran Sir”, “Devi mam”, “
Ravi”, “Mohan”]
print(“Welcome to the party %s” % guests_list[0])
print(“Welcome to the party %s” % guests_list[1])
print(“Welcome to the party %s” % guests_list[2])
print(“Welcome to the party %s” % guests_list[3])
print(“Welcome to the party %s” % guests_list[4])
5. guests_list.append(“Mr Kumar”)
guests_list.append(“Sri Devi”)
del guests_list[0]
guests_list[2]=”John”
6. movies_to_watch = [“Dilwale Dulhania Le Jayenge”,
“Titanic”,”A Star Is Born”,”Annihilation”]
movies_to_watch.append(“Jurassic Park”)
print(movies_to_watch)
CHAPTER 6:
1. watched_movies = [“Bahubali”, “Dabangg”,”Dangal”,”The
Dark Knight”,”The Godfather”]
watched_movies.append(“Back to the future”)
del watched_movies[1]
popped_movie = watched_movies.pop()
watched_movies.remove(‘Dangal’)
2. shopping_list = [“bread”,
“rice”,”Soaps”,”shampoo”,”biscuits”]
shopping_list.sort()
print(shopping_list)
3. shopping_list = [“bread”,
“rice”,”Soaps”,”shampoo”,”biscuits”]
print(sorted(shopping_list))
4. friends = [“ravi”,”Krishna”,”murali”,”pavan”,”valli”]
friends.reverse()
print(friends)
5. print(len(friends))
CHAPTER 7:

203
1. subjects = (“English” , “Hindi” ,”Mathematics”,
“Science” ,”Social”, ”Computer Science”)
print(subjects[0])
print(subjects[1])
print(subjects[2])
print(subjects[3])
print(subjects[4])
print(subjects[5])
2. names_and_movies = {“Ravi”:2,
“Krishna”:3
“Murali”:5
“Pavan”:3
“Valli”:1}
3. months =
(“January”,”February”,”March”,”April”,”May”,”June”,”Jul
y”,”August”,”September”,”October”,”November”,”December”
)
friends_birthmonths={“Ravi”: months[2],
“Krishna”: months[6],
“Murali”: months[3],
“Pavan” : months[11],
“Valli” : months[8]}
print(friends_birthmonths[“Valli”})
print(friends_birthmonths[“Murali”])
4. del friends_birthmonths[‘Pavan’]
print(friends_birthmonths)
5. words_and_meanings = {“Hale” : “Strong and Healthy.”,
“Milkman” : “A man who delivers
milk to house.”,
“Doorway” : “An entrance with a
door.”,
“Restless” : “Unable to rest or
relax.”,
“Ant” : “A small insect that
lives with many others in an
organized group.”
}

204
CHAPTER 8:
1. animals = [“Cow”, “Dog”, “Horse”, “Cat”, “Tiger”]
for animal in animals:
print(animal)
for animal in animals:
print(“Animal name is %s” % animal)
print(“I love these animals”)
2. food_items = [“Butter Chicken”, “Biryani”, “Kebab”]
for food_item in food_items:
print(food_item)
for food_item in food_items:
print(“I love %s” % food_item)
print(“These are my favorite food items”)
3. numbers = list(range(1,101))
sum_of_numbers = sum(numbers)
print(“Sum of first 100 natural numbers = %s” %
sum_of_numbers)
print(numbers)
4. odd_numbers = list(range(1, 20, 2))
sum_of_odd_numbers = sum(odd_numbers)
print(sum_of_odd_numbers)
print(odd_numbers)
5. multiples_of_5 = list(range(5,100,5))
print(multiples_of_5)
CHAPTER 9:
1. import wikipedia
info = wikipedia.page(“"Guido Van Rossum")
print(info.summary)
2. import matplotlib.pyplot as plt
y=[4.4,6.9,5.5,16.6,66.6]
mylabels=[“Australia”,”Others”,”Canada”,”UK”,”USA”]
plt.pie(y,labels=mylabels)
plt.show()
3. import Wikipedia
ipl_info = Wikipedia.page(“Indian Premium League”)
print(ipl_info.summary)
4. import turtle

205
t=turtle.Pen()
t.forward(90)
t.left(90)
t.forward(40)
t.left(90)
t.forward(90)
t.left(90)
t.forward(40)
CHAPTER 10:
1. import turtle
t=turtle.Pen()
for x in range(6):
t.forward(60)
t.right(60)
2. import turtle
t=turtle.Pen()
t.color(‘red’)
t.circle(90)
t.color(‘green’)
t.circle(60)
t.color(‘violet’)
t.circle(30)
3. import turtle
t=turtle.Pen()
for x in range(4):
t.forward(60)
t.right(90)
t.up()
t.right(90)
t.forward(60)
t.left(90)
t.forward(30)
t.down()
t.circle(30)
4. import turtle
t=turtle.Pen()
t.fillcolor(‘pink’)
t.begin_fill()
t.circle(30)

206
t.end_fill()
t.up()
t.forward(40)
t.fillcolor(‘green’)
t.begin_fill()
t.down()
t.forward(60)
t.left(90)
t.forward(60)
t.left(90)
t.forward(60)
t.left(90)
t.forward(60)
t.end_fill()
t.up()
t.left(90)
t.forward(70)
t.down()
t.fillcolor(‘red’)
t.begin_fill()
t.forward(90)
t.left(90)
t.forward(60)
t.left(90)
t.forward(90)
t.left(90)
t.forward(60)
t.end_fill()
5. import turtle
t=turtle.Pen()
t.fillcolor(‘blue’)
t.begin_fill()
t.circle(90)
t.end_fill()
t.up()
t.left(90)
t.forward(30)
t.right(90)
t.down()
t.fillcolor(‘green’)

207
t.begin_fill()
t.cirle(60)
t.end_fill()
t.up()
t.left(90)
t.forward(30)
t.right(90)
t.down()
t.fillcolor(‘red’)
t.begin_fill()
t.circle(30)
t.end_fill()
CHAPTER 11:
1. B
2. B
3. user_name = input(“Enter the user name: “)
password = input(“Enter the password: “)
if password == “pass@123”:
print(“Hi %s, welcome” % user_name)
else:
print(“Invalid Username or Password”)
4. name = input(“Enter your name: “)
no_of_items = int(input(“Enter the number of items
bought: “))
cost_of_item = int(input(“Enter the cost of each
item: “))
initial_bill = no_of_items * cost_of_item
final_bill = initial_bill
if initial_bill>10000:
final_bill = final_bill-1000
print(“Total bill = %s” % final_bill)
5. shape = input(“Enter either square or rectangle: “)
import turtle
t=turtle.Pen()
if shape.lower() == ‘square’:
t.forward(60)
t.left(90)
t.forward(60)
t.left(90)

208
t.forward(60)
t.left(90)
t.forward(60)
elif shape.lower()==’rectangle”:
t.forward(90)
t.left(90)
t.forward(60)
t.left(90)
t.forward(90)
t.left(90)
t.forward(60)
else:
print(“Selected an invalid shape”)
CHAPTER 12:
1. def print_100_times(name):
for i in range(100):
print(name)
entered_name=input(“Enter your name: “)
print_100_times(entered_name)
2. def calculate(num1,num2,operator):
if operator==’+’:
return num1+num2
elif operator==’-‘:
return num1-num2
elif operator==’*’:
return num1*num2
elif opearator==’/’:
if num2==0:
print(“Invalid number2”)
else:
return num1/num2
else:
print(“Enter a correct operator”)
return 0
3. print(calculate(12,55,’+’))
print(calculate(23,45,’*’))
print(calculate(22,11,’/’))
print(calculate(64,34,’-‘))
4. def draw_square():

209
import turtle
t=turtle.Pen()
t.forward(60)
t.left(90)
t.forward(60)
t.left(90)
t.forward(60)
t.left(90)
t.forward(60)
def draw_rectangle():
import turtle
t=turtle.Pen()
t=forward(90)
t.left(90)
t.forward(60)
t.left(90)
t.forward(90)
t.left(90)
t.forward(60)
draw_square()
CHAPTER 13:
1. class Restaurant:
def __init__(self,name,r_type):
self.restaurant_name = name
self.cuisine_type = r_type
def describe_restaurant(self):
print(“This is %s restaurant, we serve %s”
% (self.restaurant_name,self.cuisine_type))
2. r1 = Restaurant(“Hungry Birds”,”Chinese”)
r1.describe_restaurant()
r2 = Restaurant(“Swagat”,”Indian”)
r2.describe_restaurant()
r3 = Restaurant(“Tastry House”,”Italian”)
r3.describe_restaurant()
3. class User():
def __init__(self,f_name,l_name,age,address):
self.first_name = f_name
self.last_name = l_name
self.age = age

210
self.address = address
def describe_user(self):
print(“This is %s %s” % (self.first_name,
self.last_name))
print(“lives in %s” % self.address)
def greet_user(self):
print(“Welcome %s %s” % (self.first_name,
self.last_name))
4. user1 = User(‘john’,’wick’,32,’Hyderabad’)
user1.greet_user()
user2 = User(‘Jack’,’watson’,28,’London’)
user2.describe_user()
5. class Bank():
def __init__(self,name,balance):
self.name = name
self.balance = balance
def print_balance(self):
print(“Balance = %s” % self.balance)
def deposit_money(self,amount):
self.balance = self.balance + amount
print(“Successfully deposited”)
def withdraw_money(self,amount):
if self.balance < amount:
print(“Insufficient balance”)
else:
self.balance = self.balance – amount
print(“Successfully withdrawn”)
6. b1 = Bank(“Indian Bank”, 12000)
b1.withdraw_money(5000)
b1.print_balance()

211

You might also like