Python for Kids Easy Guide to Start Programming for Kids and Their
Python for Kids Easy Guide to Start Programming for Kids and Their
By Dan N.
Copyright©2016 Dan N.
Chapter 6- Functions
Chapter 7- Modules
Conclusion
Disclaimer
While all attempts have been made to verify the information provided in this
book, the author does assume any responsibility for errors, omissions, or
provided in this book is for educational and entertainment purposes only. The
reader is responsible for his or her own actions and the author does not accept
any responsibilities for any liabilities or damages, real or perceived, resulting
The trademarks that are used are without any consent, and the publication
and are the owned by the owners themselves, not affiliated with this
document.
Introduction
Kids love using computers. We should take advantage of that and teach them
some of things which they can do with computers to gain new skills. Any kid
will be proud of being a computer programmer. It is good for you to raise your
kids up with programming skills. This book is a guide for kids on how to
program in Python. Python is a great programming language which one can use
to create amazing apps, such as games.
Chapter 1- Installing Python
Before beginning to program in Python, you should first download and install it.
IDLE Graphical User Interface (GUI), and we will be using it. Click on the Start
menu, and then under the Python, you will see the IDLE (Python GUI). Just
The first thing in any programming language after the installation is writing the
“Hello World!” program. We will use the “print()” Python command so as to
display this on the screen. Just write the following on the Python terminal:
print (“Hello World!”)
You can then press the Enter key. You should see the following output:
Note the syntax used in writing the program. We have used brackets as well as
The Python command line can be used as a calculator for the calculation of
arithmetic operations.
print (4 + 8)
You can then press the Return (Enter) key and observe what happens.
The result shows that the interpreter has added 4 and 8, and it gives the result as
12.
Multiplication on the terminal is done by use of the * operator. Just type the
following on the terminal:
However, the operations can only be done with numbers. If you try to add strings
(words), to numbers, you will get an error. To demonstrate this, type the
print ("man" + 4)
The above command will give you the following result:
If you need to get multiple words on the terminal, you just have to multiply
them. This is demonstrated below:
Variables are used for the preservation of some space in the memory, and this
space will be used for the storage of values. Once you created a variable, some
Whenever we are creating games, web apps, and search engines, we store and
work with data of various types. This is done by the use of variables. The
variable will store a piece of data, and this will then be given some specific
age = 10
In the above example, we have a variable named “age” which is storing a value
of 10.
>>> age = 8
>>> height = 7
>>> weight = 15
>>> print (age + height + weight)
I am sure you are now wondering, “Why am I not adding the named age, height
and weight in quotes?” That is how variables are defined in Python. A value can
be assigned to a variable, and after that, the variable can be used as a number.
That is why we are not enclosing the words or the variables in quotes. After
writing a line, hit Enter so as to move to the next line. The code will give you 30
as the output.
In the above example, we get the result as 6000. The variable “bill” stores a
value of 500, while the variable “months” stores a value of 12. We have then
multiplied these two values using the * operator. This gives us 6000 as the result.
Note that we are multiplying strings, but the result is an integer or a number.
Variables names are case-sensitive, which means that the uppercase and
the lowercase do matter. The uppercase is the capital letter, while the
lowercase is the small letter. Example,
The variables “Age” and “age” are different, as the first one has an
uppercase “A” but in the second one, all letters are in lowercase.
The names of variables cannot start with a number, example, 8Age is not a
valid variable name
Variable names cannot have spaces, example, “student name” is not a valid
variable. You should join the two words or names by use of an underscore
(_). Example, “student_name.”
Multiple Assignment
In Python, it is possible for you to assign some single value to a number of
variables at once. This is shown in the following example:
x=y=z=1
What we have done is that we have created an integer object with a value of 1,
and this has been assigned to the variables x, y, and z, meaning that they are
using the same memory location. Each of these variables, that is, x, y, and z will
have value of 1. Whenever you call the variable, you will get 1. For example:
x=y=z=1
print (x)
print (y)
print (z)
x, y, z = 1, 2, "mercy"
In the example given above, the value of x is 1, the value of y is 2, and the value
of z is mercy. Whenever you call the variables, they will give you their
x, y, z = 1, 2, "mercy"
print (x)
print (y)
print (z)
The program should give you the following result after execution:
Data type refers to the types of data which the memory can store. They
example is an age of a person which will be stored as a numeric value, and his or
her address which will be stored as an alphanumeric character. The Python data
types specify the storage space to be allocated, as well as the kind of operations
another integer. Python supports 5 data types, which include the following:
Numbers
String
List
Tuple
Dictionary
Python Numbers
Numbers are used for storing values which are numeric. We create them by
number1 = 5
number2 = 20
When you call the variable “number1,” you will get 5, and if you call variable
number1 = 5
number2 = 20
print (number1)
print (number2)
In Python, strings refer to a set of characters which are enclosed within quotation
marks. You can choose to use either single or double quotes, and all will be well.
That is good for you as a young programmer. If we need to get some subset of a
string, we will use the slice operator, that is, [], or the [:]. The first string is
stored at index 0.
print (name[0]) # this will print the first character of our string
print (name[2:5]) # this will print the characters starting from the 3rd to
#5th
print (name[2:]) # this will print the string starting from the 3rd
#character
Something new and funny has just happened. We have written some lines which
are beginning with the pound (#) sign. These are known as “comments.” I have
just used these to explain what each line means and what it does, and they have
no effect on your program, except making it big in terms of size. The Python has
a tool called the “interpreter,” which is responsible for the output you get once
you write and run your program. It is also responsible for detecting and
outputting any errors found in your program. Once it meets a line starting with
the # sign, it will ignore and skip it and then move to the next line. This is
because the line will be treated as a comment. If you use it in the middle of a
line, then the code after the sign will be ignored and skipped.
the first part of the output. The characters of a string begin at index 0. Use of
(name[0]) gives us the first character in the string, and this is M. We have
done a repetition on the string using the * operator, and this gives us the string
twice. The use of a + operator and another string joins the two strings, and this is
referred to as “concatenation.”
Python Lists
There form the most versatile data structures in Python. It is made up of items
which are enclosed with square brackets, and these items are separated by the
use of commas. The elements in a list can be of different types. This means that
you can store numeric and character data in a single list.
The list items are accessed using the slice operator, [] and [:], and the items
begin at index 0.
In the example, we have defined two lists. The first one is named “list,” while
the second list has been named “list1.” As shown in the two lists, they have
“list,” our first element, that is, index 0 is “wxyz.” Accessing the element at
index 0 in that list gives us this element. Note that repetition operator (*) and the
concatenation operator (+) have also worked in the same way they did in strings.
Python Tuples
A tuple is also a sequence data type just like the list. It is also made up of a
number of values, and these are separated using commas. Tuples are enclosed
using parenthesis. The values of a tuple cannot be updated, unlike what we have
These resemble a type of hash table. Dictionaries can be used to hold any
arbitrary Python object. This shows that they are versatile. They are enclosed by
the use of curly braces ({}), and the objects are accessed by use of the square
brackets ([]).
dict = {}
3+4=7
In the above example, we have an addition operation. The values 3 and 4 are
the symbol used to manipulate the values of the operands. Python supports
different types of operators.
Arithmetic Operators
These are used for performing the basic mathematical operations such as
addition, subtraction, multiplication, and division. In this case, we use the
The following are the two arithmetic operators which you may not know what
they do:
7%3=1
The following program shows how the arithmetic operations can be done in
Python:
j = 11
k=5
l=0
l=j+k
l=j*k
print ("The value of multiplication, l ", l)
l=j/k
print ("The value of division, l ", l)
l=j%k
print ("The value of remainder is, l ", l)
l = j**k
print ("The value of exponential, l ", l)
which will help us make decisions. This will be even funnier to you, as you will
be able to specify a number of conditions and actions to be taken that will be
Consider the grading system you use in your school. If you get an A in a subject,
the remark is “Excellent,” if you get a B, the remark is “Good.” This is a good
scenario for us to implement some decision making logic.
If grade is A,
Remark is Excellent
If grade is B,
Remark is Good
We can construct a logical construct in Python for the above scenario. This is
demonstrated below:
grade= A
if (grade=A)
Print “Excellent”
if (grade=B)
print “Good”
In the above code snippet, we are telling the interpreter to output “Excellent” if
In this statement, the condition is set using the “if” statement. The condition is
if expression:
statement(s)
made to make decisions. If this expression does not evaluate to true, then the
grade = "B"
if grade=="A":
print ("That is excellent kid, you got an A")
if grade=="B":
print ("That is good kid, you got a B")
if grade=="C":
print ("That is fair kid, you got a C")
if grade=="D":
print ("Hi kid, keep up, you can do better than that!")
Try to run the program and see what you get. You should get the following
output:
That must be exciting to you! We began by setting the value of the grade in the
line “grade = "B".” This shows that our student got B as a grade. The Python
interpreter wants to send a remark to the student and tell him or her that it is
good.
The interpreter will first read the first line of the code, and know that the student
got B. It will then proceed to check the “if” statement. The expression “if
grade== “A”” will evaluate to false. This is because the value of grade is not A.
The print statement below it will be skipped. It will then proceed to evaluate the
next “if” statement. This is “if grade== “B”,” and this statement will be true. The
print statement below it will be executed rather than been skipped, and the
execution of the program will stop there.
Suppose the student had scored another grade, maybe a D. The program would
look as follows:
grade = "D"
if grade=="A":
if grade=="B":
print ("That is good kid, you got a B")
if grade=="C":
if grade=="D":
print ("Hi kid, keep up, you can do better than that!")
Note that we have only changed the value of grade in the first statement to grade
= "D." Initially we had a B. That is how simple one can work with an “if”
statement. If you run this program, you will get the following as the result:
statement. In our previous example for the “if” statement, we had 4 grades.
Suppose the student got none of the 4 grades, what would have happened?
Probably we would have run the program, but gotten no result. This is why we
should come up with another part which will be executed in case none of the
expressions evaluates to true. This is done by using an “else” part at the end of
grade = "E"
if grade=="A":
print ("That is excellent kid, you got an A")
if grade=="B":
print ("That is good kid, you got a B")
if grade=="C":
print ("That is fair kid, you got a C")
if grade=="D":
print ("Hi kid, keep up, you can do better than that!")
else:
print("The student got none of the above grades")
Just run the program, and check the output that you get. It should be as follows:
In the example, we set it so that the student got grade E. However, in the
expressions for the “if” statement, we have only evaluated 4 grades, A, B, C, and
D. The interpreter will check the first expression, and find and compare it with
the value for the grade, which is E. E and A are not equal. The statements below
the first expression will not be executed but skipped. The interpreter will then
proceed to the next expression, which is for B. B and E are not equal, so this will
also be skipped. The “if” expressions for grade C and D will also be skipped and
since none of the expressions has evaluated to a true, then the default “else” part
will be executed.
Even if you had used the “else” statement but one of the “if” expressions
evaluated to true, then the “else” part was not to be executed. This is best
grade = "C"
if grade=="A":
print ("That is excellent kid, you got an A")
if grade=="B":
if grade=="C":
if grade=="D":
print ("Hi kid, keep up, you can do better than that!")
else:
student got a C. Let us try to run the program and see what will happen:
Yes, you now get to see the sweet thing with Python. That is, you can play
around with your program and get the various outputs by changing only a small
part of the program. Also, note that indentation is very key in Python. This refers
to the alignment of the statements. The “print” statements have been written
slightly inside compared to the “if” expressions. That is how it should be in
However, you notice that in the above statement, both the “if” expression for
grade C and the “else” part were executed. Let us solve this problem in our next
statement.
“elif” Statement
With this statement, you can check a block of statements for a True expression,
and once one of the conditions evaluates to a true, then this will be executed. In
this statement, we can have multiple expressions as we want unlike what we
have in the “else” statement. This statement takes the following syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
In Python, the “switch” and “case” statements are not used. However, their
grade = "C"
if grade=="A":
elif grade=="B":
print ("That is good kid, you got a B")
elif grade=="C":
elif grade=="D":
print ("Hi kid, keep up, you can do better than that!")
else:
As shown in the above output, only the statement below the “if” expression for
the grade C was evaluated, which was not the case with the previous “else”
statement. In this case, the “else” part has been used in the last part, but it has not
been executed. This shows that the “elif” statement is more advanced compared
to the “else” statement, and it should be used when you need to evaluate multiple
expressions. You can also play around with the program and see how it behaves.
If we use a grade which is not part of the “elif” expressions, then the “else” part
should be executed. This is demonstrated in the following program:
grade = "E"
if grade=="A":
elif grade=="B":
elif grade=="C":
elif grade=="D":
print ("Hi kid, keep up, you can do better than that!")
else:
print("The student got none of the above grades")
Once you execute the above program, you will get the following output:
Nested Statements
Once some condition has evaluated to a True, you may need to go ahead and
evaluate another condition. In such a situation, you can effectively achieve this
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
if marks<80:
else:
if marks==40:
Once you run the above program, you should get the following output:
The result is due to the fact that the student got 70 marks, satisfying the first
expression in our program. The mark is also less than 80, and the first nested “if”
expression has been satisfied.
Chapter 5- Loop Executions
In programming, the execution of statements is done sequentially, that is, from
one statement to the other. The first statement to be found will be executed,
followed by the statement which is found next, and the sequence will continue.
Despite this, you may need to run a section of code several times. This is done
by the use of loops. There are different types of loops which can be used when
there is a need for several executions of a code. This sounds funny. A loop is just
repetition.
An example is the use of a “print” statement. If you want to print “Hello world”
10 times, you don’t have to write the “print” statement 10 times, but the logic
Notice the use of “\n.” This is referred to as the “new line character.” It will
command the Python interpreter to print in the next line after it has printed.
Execute the program, and check to see the result:
Notice that we have just stated a single line, but it has been printed 10 times.
However, this is tedious and time consuming. At this point, you should be able
to do things as a Python Guru! I mean a young Python Guru!
This loop is used for iterating over a set of items, and these can be of any
sequence. The following is the syntax for the “for” loop in Python:
statements(s)
say x. This should be executed 10 times. In the “print” statement, we have used
the repetitive operator “*” which we discussed earlier. The repetition will be
done for “var” times, and var is 10, meaning that the repetition will be done 10
times.
print()
students = ['john', 'mary', 'tom']
Just run the program, and you will get the following output:
That is very interesting. I am very sure you are enjoying it. In the first “for”
loop, we have defined the variable “letter” which represents each letter in the
element “Mercy.” We then print the letters by invoking the variable. In the
second loop, we have a list of students. The variable “student” represents each
element, that is, student in the list. When we invoke the variable, it prints the
We can also use an index so as to iterate through the elements that we have in
our list. Consider the simple example given below:
Note that we have used two new functions, that is, range and len. The range
function shows the sequence of times for which to iterate the elements in our list.
Now that you have learned how to use the “for” loop, we can go ahead and see
how this can be used together with other Python statements. Let us demonstrate
how this loop statement can be used together with the “else” statement we
discussed earlier. The following code demonstrates this:
nums=[9,31,44,29,6,75,17,28,33,61,13]
for num in nums:
if num%2==0:
break
else:
The main logic in the program is in the “if num%2==0:” line. We have defined
a list of numbers, both odd and even. Our aim is to check whether there are some
even numbers in the list. The use of the % (modulus) operator shows that we are
checking that if there is a number in the list in which we get a 0 after dividing
with 2. This will be an even number. If any such a number is found, then we will
conclude that there are even numbers in the lis, and then print the appropriate
statement. If this is not found, we will print the other statement.
Our list has even numbers, such as 44, 6, and 28. Let us change these numbers to
odd ones, and then observe what will happen after running the program:
nums=[9,31,41,29,7,75,17,29,33,61,13]
break
else:
This is because we do not have any even numbers in our list. When we divide an
even number with 2, the remainder should be a 0. We do not have such a number
in the list, and this explains why we get such an output. Now you have learned
becoming an expert!
while expression:
statement(s)
count = 1
In the above case, we have set the value of count to 1. The value of count will
never change. Since our condition will always be met, that is, count==1, the
program will run forever. Are you 1? Of course you are 1. Then if this is true,
then you will be happy forever. If you run the program, you will see it printing
the output without ending. Also, the second print statement will never be
executed. This is because the first one will be printed continuously.
For us to end the program, we have to set some condition. Let us use the concept
of class position. Of course you are ranked at school after an exam. If you are
above position 10, you will definitely not be happy. Let us implement this logic
programmatically:
position = 1
position = position + 1
The program will give you the following output after executing it:
We have used the “while” loop to set the position to be less than or equal to 10.
If the interpreter evaluates this loop the eleventh time, it will find that the value
of the position is 11. The value of the condition will be false, and the last
statement will be executed, and the program will halt.
An Infinite Loop
In case the condition you set will never become false, then this will become an
infinite loop. When using while loops, you should be careful as your program
var = 1
Just try to run the above program and observe what will happen. You will notice
that it will run forever. However, only the first print statement will run forever.
The second print statement will never get executed.
Nesting Loops
In Python, we are allowed to create a loop inside another loop. With these, you
can achieve a funny and amazing effect! We use the following syntax so as to
nest loops:
statements(s)
statements(s)
The good thing with this concept is that you can nest any type of loop inside any
other type of loop. An example is a while loop inside a for loop and the vice
versa is true.
Consider the following example which shows how “for” loops can be nested:
for a in range(10,15):
for b in range(1,5):
c=a*b
print (c, end=' ')
print()
together into a function and when we need to use the code, we will just have to
To define or create a function in Python, you have to begin with the “def”
keyword. The name of the function should then follow, and this should end with
parenthesis ( () ) and colon.
def functionname():
Inside the brackets, we pass in the parameters, but you will learn what these are
later on. Consider the example function given below:
function. This will “sink” into you might shortly. Just be patient!
Function Calls
With a function definition, you will just create the name of the function, pass
some arguments to it, and then structure the block a bit. This is not enough for
The function has to be executed by calling it, and this can be done from some
other function or by doing it from the Python command prompt. Let us use our
Consider the following code, which shows the advanced form of our previous
functions:
return
#The function call can now be done as follows
At the bottom of the above program, we have two statements, and each of these
statements begins with the name of the function we had defined. A string has
then been passed inside this in both cases. The string will then be copied to the
first line of the code, and it will act as the “mystring.” The use of the statement
“print (mystring)” will then give us those strings. That forms the simplest way
for us to call functions in Python.
Passing by value vs. by reference
In our previous example, you saw how we send our parameters back to the
function. In Python, parameters are passed by a reference method. If the what the
parameter is represented in the function, the change will also be reflected in the
return
list = [11,12,13]
myfunction( list )
passed, and then we have joined or appended the values to the same object.
What if we need to pass by reference and then overwrite the reference inside the
function which has been called? The following example demonstrates this:
return
myfunction( list )
print ("The values outside to the function: ", list)
within the function, the list will not be affected. The function has accomplished
nothing, and that is why we get the above result.
Chapter 7- Modules
Modules are used for organizing Python code in a logical manner. It makes it
possible for us to group related data. It has named attributes, and we can refer
and bind.
return
That is just a simple module. For now, do not worry. You will learn how to use it
shortly.
If you need tose u a Python source file as a module in your program, you use the
“import” statement so as to make it accessible from that program. The import
statement in Python takes the following syntax:
import module1[, module2[,... moduleN]
directories from which you can search for modules which you need to use or
make them locally available in the Python program you are writing. Suppose we
had named our previous module “printfunction.py.” Note that the file should
have been given this name. The function “print_func” was defined in this file,
now a module. For us to make use of this function, we have to import the file, or
the module to our program. I am sure that sounds funny, but it is also amazing.
import printfunction
# Now that we have imported the module, we can use its function freely
printfunction.print_func("Mercy")
Note that we used the “import” statement so as to make the module locally
available.
To import a module into a program, you do it only once, but you can use it for as
many times as you want. This means that we don’t use multiple imports for a
single module. This prevents a repetitive execution on a module, hence saving
the interpretation time for the Python interpreter.
Sometimes, you may not need to use the entire module, but only some of its
attributes, most probably a single attribute. In such a case, you are allowed to
import only that attribute from the module using the “from…import” statement.
The “modulename” represents the name of the module from which you are to
import the attributes. The name1, name2, up to nameN represents the names of
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
The file with the above code should be saved with the name “fib.py.” Note that
the use of a “.py” extension in the file name shows that we are creating a Python
file. The file now becomes a module. In it, we have defined a function named
“fib.” For us to use this function in our program, we have to import it. However,
we only need to use the “fib” function from the module. Instead of importing the
entire module into our program, we can import the function, which is now
>>> fib(50)
That makes your work easy, and you a more professional Python programmer.
The “from…import *”
Sometimes, you may need to import all the names which are available in a
particular module into your current namespace. This is done by use of the
following statement:
With the above statement, you don’t have to name all the names or functions
which you need to import from the particular module. The (*) operator can be
In a module, the name of the module is used as the value for a global variable.
The module code will be executed normally as if it had been imported, but the
name will be “_main_.” The code will be added to the end of our module:
x, y = 0, 1
while y < n:
result.append(y)
x, y = y, x+y
return result
if __name__ == "__main__":
f=fib(50)
print(f)
graduation. You can also convert the date from one format to another in Python.
Python has a module which helps us work with modules and work with the
conversions. Time is represented in ticks, which are seconds which have elapsed
since 12:00am of January 1st 1970. When we use the “time.time()” function, we
will get our current time in terms of ticks. Consider the following example:
import time; # We are importing the time module into our namespace
ticks = time.time()
Working with time in ticks is very easy. However, representation of time in this
format is a bit tough for one to understand. Of course even you at this age, do
you find it easy to understand what the actual time is from the ticks? Definitely
NO.
TimeTuple
import time; # We are importing the time module into our namespace
print (time.localtime())
The output shows the year, the month, the day, and the time in hours, seconds,
However, the above format is also a bit complex. We need to convert the time we
get since epoch time, that is, 1st January 1970. To do this, we have to pass the
floating-point value to some function. This can be done as shown below:
import time
localtime = time.localtime(time.time())
It is also possible for you to format the time according to the way you need. The
format which is more readable. Of course, you need to know the day of the
week, the month, and the date of the month, as well as the time in hours,
minutes, and seconds, as this is what we are used to. This function helps you get
import time
the monthly and yearly calendars. The following demonstrates how one can print
a specified calendar for a particular month:
import calendar
the values for the month and the year. You can check to confirm it from another
source!
Conclusion
We have come to the end of this book. It can be concluded that Python is a good
programming language. Even kids can learn how to program in Python. As a kid,
you just have to develop your interest in Python programming, and all will run
smoothly. You can write some programs which are funny, and you will play
around with them. Examples are loops which run forever, and others which will
terminate under certain conditions. This is funny. Finding you instructing the
programming, and Python makes it easier. You can even create your own
module, and then use it in any program. My hope is that you remember how to
do it! You can’t have forgotten how to do this that quick! Make sure that your
lines of code are indented well. If you are used to other programming languages,
where no indentations are used, but they use curly braces, then you have to put
this aside, as Python works differently. With proper indentations and proper
constructs for your programs, your program experience will be smooth. Enjoy
coding in Python!