Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

word

-
I
Let's learn

Book8
coding!
Make sure you have bought a
genuine Paramount book and
not a pirated edition ..
• Always check the ANTI-PIRACY SECURITY LABEL applied to the title
cover before purchasing/paying for a Paramount book.
• The pirated books can be identified by the inferior quality paper,
reduced printing quality, sub-standard binding, blurred images and
unclear or hazy text. These all give a textbook second-rate quality
and poor texture and appearance but you still pay the price of a
genuine book.
• Do not accept a book if the label is missing, is being torn or
tampered, or you are unable to find the security features and
authentication marks as shown below:

Coin reactive
U.Vvisible

SICPASTAR®
High Security
multilevel ink
Colour shift from
=-t-i-----..;___
Pink to Green
Up-Conversion
responds to
hand-held devices

ANTI-PIRACY SECURITY LABEL

If someone is selling pirated books of Paramount or if you sense that you


have bought a pirated book, please contact:

Paramount Books (Pvt.) Ltd.


152/0, Block-2, P.E.C.H.S. Karachi.
Tel: (92-21) 34310030, legal®paramountbooks.com.pk
www.paramountbooks.com.pk
IJ
I
I

llello World Kids


Book8 · ·
Copyrights © by
Hello World Kids Inc.

All rights reserved.


No part of this book may be photocopied, reproduced, stored
in a retrieval system, or transmitted in any form or by any
means, electronic or mechanical or recorded without written
permission from the publisher.

By:
Hello World Kids team

Designed By:
@Waleedlutfe

Hello World Kids Inc.


P.0.Box: 230196, Amman 11123, Jordan
http://www.helloworldkids.org

This Special Edition of


"Hello World Kids"
is for Sale in Pakistan Only

Paramount Books (Pvt.) Ltd.


152/0, Block-2, P.E.C.H.S., Karachi-75400.
Tel: +92-21-34310030, info®paramountbooks.com.pk
www.paramountbooks.com.pk

I I

2
~ \
Index

Unit 1 Hello Python 7

Lesson 1 Introduction to Python 8

Lesson 2 Python Specials 14

Lesson 3 Variables in Python 15

Lesson 4 Input and Output in Python (1/0) 21

Lesson 5 Python in Real Life 25

Unit Exercises 27

Unit2

Lesson 1
Lists and Functions

Hello Lists
-
30

Lesson 2 Operators in Python 33

Lesson 3 Hello Python Functions 37

Lesson 4 Functions with Parameters in Python 38

Lesson 5 Void and Return Functions 40

Unit Exercises 41

Unit3

Lesson 1

Lesson 2
Conditions and Loops

Introduction to If Statement

If Statement in Python
-
44

45

lesson 3 Hello While loop 48

Lesson 4 Hello For loop so


Lesson 5 loopy Practice 53

Unit Exercises 54
Unit4 Classes and Objects

Lesson 1 Object-Oriented Programming


56
Lesson 2 What are Classes?
57
Lesson 3 What are Objects?
58
Lesson 4 Handling Classes and Objects
59
Lesson 5 Examples on Classes and Objects
60
Unit Exercises
61
Unit 5

Lesson 1
Modules in Python

Time in Python
II
64

Lesson 2 Random 65

Lesson 3 Built-ins 67

Lesson 4 Code Blocks and Indentation in Python 71

Lesson 5 Clean and High-Quality Code 72

Unit Exercises 74

II
-

Unit-6 Challenges · · ·

Challenge 1 Higher/Lower Guess Game 76


Challenge 2 Hangman 77
Challenge 3 Password Generator 78
Challenge 4 Snakes and Ladders 79
Introduction

Dear student!

Have you ever thought of all the technological innovations around


you? And how they have made our lives easier?

All these innovations wouldn't have been without great efforts,


hard work and creative ideas. However, as new challenges rise,
the world needs creative thinkers, problem solvers and innovators.

Hello World Kids believes that with your creativity and


determination, you can unleash the entrepreneur inside you to
lead in our growing world; that's why you will be learning with us
new thinking and problem solving skills through the concepts of
programming.

5
. .t~
II
II
II
C!

< _,. ·.'...·-~·

.: .
~- I

This book is dedicated to the


Scientists and Programmers of
the future.
Even if it was a single
fingerprint in those who would
change the world!
Unit 1
Hello Python

7
C on ·t Introduction to P thon

outcomes: After this lesson, you should be familiar with the term ID
and you should be able to mention some of its feature/

Introduction:
Why do we need to learn computer programming?
Programming helps you ~nk differently, easily_ and
~ a s i_t ~nds on log~c and e_roblem solving. With
programming, you create things from almost nothing!

u-1
12

8
illlll&....;:a ...
Why Python?
Python is an easy-to-learn programming language that has some
useful features for a beginner programmer. The code is quite easy
to read when compared to other programming languages, as you
can easily write your codes and see them run. Also, it is one of the
programming languages which provides a simple way to create
programs with slightly more advanced graphics and animation.
' • 1 _- . ' • •

. ,:
f- - ·~ .•

. - .~ - . .. , ,.. \ ,;- -

Whatdoes the term CODE m·ean? --·


The term .CODE means the list of instructions which performs
a program that is written by th_
e programmer using one of the
programming languages:

-~
( Exercises
Mention some of the programming languages you know, or
search to know some.
+± _ /' 91-r. ·. '.: . -~: · i .. ; -:,::._ ·_·. :-:·; .. >:
c.. ... ... ···························~·IJ[)..?.\ ···r·······························································
...
... 3.0:-;V.o.... .......·.................................................................................................. .
..V1i~..... B.ab.~.r;........................................................................................
1,

Class Discussion - - - - - - - - - - - - - - - - - . . .
"You cannot run before you walk!". .
What does this mean? How is this related to programming?
9
___,,,,,,_____esson Introduction to Python

What is IDE in Python and how can we install it?

IDE stands for Integrated D evelopment E nvironment that 'Nil


be used by Python language. I

Its main features are:


Multi window text editor
Uses auto completion
Syntax highlighting

IDE installation:

Step 1:
To download and install Python IDE, visit the official website of
Python: http://www.python.org/downloads ..
and choose your version. We have chosen python version 3.7.3
e, _ _ ,,,_... .
+- 0 , ,__.,.,_II/SI,_ _ ;Oc;rn: zmzrrriliir -

',:t f)LJthon
,\,,r,1JI rir,1,11'.rJ,,d·.

<·r•,ion for Windovr,


Download tllf' latf•\t vn•,ion

• •, f ,1,,,

- D

Install Python 3.7.3 (32-bit)


SMI IMIII Now to lnsllll Pylhon will! dtfaull M1tS19f. or ct100St
Customize to INbll or disable~
Step 2:
Install Now
Once the download C.-\IJMrNmom\AppOat,~~-32

lnduda IOlf, p;p 111d documeralion


is complete, run the C-.. shorlcua llldfile m«illions

.exe file and then


Customize installation
click "Install Now". Choote loc. . . 111d , _

python
flli ti': lnstlll llunchtr for II UMf'I (rlcommended)
windows Add Python 17 to PATH [ CIIIIII ]
- C X

Step 3: Setup Progress


You can see Python IDE
installing at this point. INtJlr9
P'yltlOll 17J pip lootltYlp 132-llill

python
for
windows

Step 4: I> 1'j1Mo11JIII-MIS., - D X

When it finishes, you Setup was successful


will see a screen that Spocill llllntl lo Miff Hammond. - . i wllolt yolll of
....., 111111d Wlndowl . . . PyltlOll laf Wlndowl
Ill bt Pylholl laf DOS.
says the setup was
New lo Pylholl! SIIII wilt, lllt end
successful. Now click dgrum,ntatjpn.

S o t ~ 11 tllil ,._
"Close".
Disablt path length llmlt
· $ °"""'.,..,,-1w,omp_to _ _ _ inclucing Python, to
"""'lhtllOcllot- "MAX,.MTH" llmlltion.

python
for
windows

Step 5:
Installing PyCharm:

Step A
Visit the website: www.jetbrains.com/pycharm/download and
click on the "DOWNLOAD " button under the Community section.
j • OowNotd P)(Nffll!PythonlOI IC l+
4" 0 I jl1bf1IM,com/pyd,ilm/-Dod/f-lOO• -

PyCharm Whll'I New FIIIUrH LHrnlng c,ntar luy

Download PyCharm
( Wlodowl_ ) IM<OI """'"

ProfessIona I Community
VtfllOft• 20113
For both Scientific and Web For pure
l1,11k1 112 1121 101
Python development. With Python development
.J,,JjyJ,4, J01f HTML, JS, and SOL 1upport.

ouwru•J"'LJ
Introduction to P thon

Step B
Once the download is
complete, run the .exe
file to install PyCharm.
The setup wizard should
have started. Click
"Next ".

. -
PyChMm Community Edilion So1up
a--.-a-
0
)(
Step C
In the next screen, ,-----------==
lit ea-._.,. ., 0-lho faldorlnwlidtloinotlll!'yOwo,

Sft41 . . lnltall'y0wac-n!y_ln . . ,..,...


faldor, ddc_ond_ ...._. faldor. Od<Nmct lD::::.-:.0-1,1 ......
fdlo,.

change the installation


path if required. Click
"Next"
!pom~Sl7.trie
!pom......., 40,0GB

-
PyChlffll Community Edllion s.._. - X

Step D
You can create a
desktop shortcut if you · . ~PAlMvnbll~lllldllll
: 0Addllunct.9*tohN1H I

want. Click "Next"

·: ·. ... "; : !: ,. -~ .' ·. .-.'.: .~


\•.· . .

Step E - o X

Choose the start menu


folder. Keep "JetBrains ,, .,_
==----===:.."!""'...:-~--~--.............. -
selected and click on . .• :
,.
"Install".

,.
··. ':-
I .. 1
liiJ PyCham, Community Ed;,;o,, Setup - u
Step F
Wait for the installation
,_de_ ,_..=_::_
~xlract py1han......,..••• 100'11,

to finish. - - - - - -·- - -

1~-__
<- jf ..... > J L Can<d=-:J

Step G Iii PyCMrm Community Edition Setup - 0 X

Once installation is
finished, you should
receive a message , ,
Extract py1han..est.jor ••• 10()'11,

screen that PyCharm is


installed. Click " Finish ".

r Flnllh J

After you click "Finish', the following screen appears:

Py 'h;11 rn

Now, write and enjoy your code...

13
Les~ 2 Python Specials
Outcomes: By this lesson, you should _be_ able to mention sorne 0
Python language characteristics. f

Introduction:
Why should I choose Python as a ~rogramming language">
Python is one of the programming languages that ·
model the real world. It focuses on obje~ts as it is ca~:~
ObJ·ect-Oriented. Below
. . .are some of its unique and
important characteristics.

Easy -+ Easy to code and read


Expressive -+ Focuses on the solution rather than the syntax

Free and open source -+ Freely available to the public

High level -+ Programmer friendly

One of Python's features that wasn't mentioned above is


"Python is GUI Programming". What does this mean and
what does the term GUI stand for?

We hope that you like the features of


Python programmi~g language. ..

14
~ -Lesson
- - - - -3
- - Variables
- - - - _ _in
. .Python
_ ______
-4 Outcomes: By this lesson, you should know the term variable with
its data types and rules.

-4 Introduction:
What is a variable and why do we use it?
A Python variable is a reserved memory location to store
values. In other words, the variable in Python program
gives data to the computer for processing.

If you want to save something so you can use it later,


what do you do? You put it i_n a container in a specific
place. Same for the variable, you can imagine that it
is a container that you put your data in so you can use
it in processing.

Variables in Python: Types and How to Declare


Every value in Python has a data type. Different data types in
Python are: ·
Number _.. Integers: e.g. (1,2, 3, ... )
OR
_.. Floats: Numbers with floating point, e.g.(1.25, 8.9)
String _.. Characters: A mix of symbols, letters and numbers
Boolean _.. Either True or False

There are other data types such as: List, Tuple and Dictionary; but the
focus will be on numbers and strings. ·

Variable syntax:
Variable Name = Value or Variable Name= "Value"

...
The variable name shoul·d be given so you can assign a value.
15
,
al
Leii:on 3 Variables in Python
Let see examples.
Example 1: Variable with Numerical data type
II

We will declare (define) the variable a" as number and print.1


using Python. . 1

II
Here, the variable a" is assigned
with a numerical value: 100

a= 100
Print (a)

16
-
Example 2: Variable with String data type
we will declare the" a" variable as string, and print it using Python.

Here, the variable "a" is assigned with a string


value: "Hello World Kids" ·

. ·-·----- - --- - - - -

a = "Hello World Kids"


Print (a)

17
~
.-
Lesson 3 , Variables in P thon

'Note - - - - - - - - - - - - - - - -
lf you can see, the string ~alue should be assigned With
the symbol " " . If you missed the double quotations
Syntax Error will be shown as the following: a

You can add anything you want for the string value·, it can be letters,
words, symbols, letters mixed with numbers and symbols.
But the main condition is to add the " " sign so Python will understand
that you are declaring a string variable.

e.g:
a= "Hello World Kids teaches programming"
Print (a)

i I ·--
,
l

' !

18
l~ -
Example 3: Variable with Boolean data type
The Boolean data type has the value of either True or False. In
Python, Boolean variables are defined by the True and False
reserved words with the upper case first letter, using a lower-case
value returns an error.

Reserved words: The words that you CANNOT use as


variable names. They are used by Python.

We will declare the "a" variable as Boolean and print it using


Python.

a= True
Print (a)

b~
[ '&) Exercises
Try to assign (true) instead of (True) for the variable "a". What
do you expect? Why?
·· ············ ··········· ····· ··· ·········· ······ ···· ········ ········ ····· ·· ·· ····· ··· ··········· ······· ············ ··········
· ·················································································································· ·········· 19
~1
Lesson 3 Variables in P thon
'\
Python Variable Name Rules l
In any programming language, there are some rules that you s j

follow when you name a variable. Below are some of them: houtd
Must begin with a letter (a-z, A-2) or underscore (_).
Other characters can be letters, numbers or underscore (_).
Case sensitive: It matters if it is upper case or lower case.
Can be any reasonable length.
Should not have spaces.
Never use reserved words. as variable names as they are being used
by Python for other t hmgs.

(
b~ Exercises
Write down five variable names that will be accepted
Python without errors. . ·. -.. •·
.. .. . ... ....... =............................................................... : ........................... ,. ·········· ·· ·· · ··

• • • ,• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • .• • • • • • ·.- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . • • • • • • • • • • • • • • • • • • • •

•'. ' ·
.
........ ................................................
- .
........................................
.
...............................
...............................................................................................................................
... .... ......... ; .............................................................................................................
- _

·•:," .

20
Lesson 4 Input and Output in Python (1/0~
4 outcomes: By this lesson, you should be able to use the built-in
functions, Print() and Input() to perform (1/0) tasks.

4 Introduction:
First let's talk about something called a "parameter".
lm_agine you wan~ to give your friend a gift in a bag, in
~his case the bag 1s the parameter and what's in the bag
1s a value you want to pass from you to your friend.

A parameter is a special kind of variable that is used to


pass values between procedures.

~Input()
·· Input Syntax:

Variable Name= Input (parameter)

As the parameter is a string representing a message before the input.

e.g.:

x = input("Enter your name:") \

Suppose that you want to write a program which needs different data
to be entered in each time you run the code or you need to accept
data directly from the user that runs the code. In this case, the Input
. function is a must. ·

Input means: The function that Python uses to accept data directly
from the user. ·
The value
Example:
entered by the
val= input("Enter your value:" )
user is 123
print(val)
Output:
Enter your value: 123
/
123 21
on 4 .5 In ut and Out ut in P thon (1/0)
String and Numeric Input
The _inpu_t() function, by default, will convert all ~he information i i
receives into a string. Which means that• the data will be• taken as ·t.
I ISt :.
I

What if we want to use the input data in some calculations? ·


In this case, other functions will be used to help.

Integer Numeric Input: Int()


One of the most numeric functions that can be used is Int().
The
• following example demonstrates how numeric type informafIOn
Is received.

User_input = input ("Enter your Age")


Val= int (User_input)
Print (Val)

Output
Enter your Age 19
19

Here, when the int() function is called, the input data will be acce t d
as a number not as a string. Pe

( Exercises
Write a Python code that accepts a student marks in the
Mathematics subject.

22
~ t Nu-meric Input: Float()
floa
float() function will be used to represent th l b .
rhe .
decimal pom . t e rea num ers with

challenge: . _
Can yo_u write the Python code which accepts a Math m k
a floating number? ar as
Hint: You can just replace the "Int" word with "Float".

Boolean input: Bool()


1am trying _to have a user input whether they like school or not, and
the output 1s supposed to ~e true or false. In such case, the input data
type should be Boolean using the Boal() function.

Details for Boal() function will be discussed further later.

Output()
I

·• The output function is used to send data to the output device (Screen) .
. The most used function for Output() is the Print() function .

.Print() Function
The print() function prints the specified message to the screen.

Print () syntax:
Print (Message)
As the message is the value that will be shown on the screen.

Example 1: Printing only one object

print ('This sentence will be shown as output on


the screen')

Output: t n the
This sentence will be _
shown as outpu o
screen 23
~r P thon {1/Q

4 ;
. In ut and Out ut 1n
an one object
Example 2: Printing more th

A = 10
pr int('The value of A is' , A)
Output:
The value of A is 10

inted. Python uses (,) to separate betwee


Here, two objects are pr 11 the
objects.

68~ Exercises
u think the ou tp ut w ill be for the code below:
What do yo
rry ")
X = (" apple ", "banana ", "che
print(x)
.......;.............
Output: ..... ..... ........................................
..... ...................... ..... .. . ... ···········································

... . . . . ·················································· ···

I
I
I
l
I

24

You might also like