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

Python for Kids Easy Guide to Start Programming for Kids and Their

This document is a guide for kids and their parents to learn programming using Python. It covers essential topics such as installation, variables, operators, decision-making, loops, functions, and data types, providing practical examples throughout. The book aims to empower children with programming skills while ensuring a fun and engaging learning experience.

Uploaded by

oakesoe110
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)
3 views

Python for Kids Easy Guide to Start Programming for Kids and Their

This document is a guide for kids and their parents to learn programming using Python. It covers essential topics such as installation, variables, operators, decision-making, loops, functions, and data types, providing practical examples throughout. The book aims to empower children with programming skills while ensuring a fun and engaging learning experience.

Uploaded by

oakesoe110
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/ 77

Python for Kids

Easy guide to start programming for

kids and their parents!

By Dan N.

Copyright©2016 Dan N.

All Rights Reserved


Copyright © 2016 by Dan N.

All rights reserved. No part of this publication may be reproduced, distributed,


or transmitted in any form or by any means, including photocopying, recording,

or other electronic or mechanical methods, without the prior written permission


of the author, except in the case of brief quotations embodied in critical reviews

and certain other noncommercial uses permitted by copyright law.


Table of Contents
Introduction

Chapter 1- Installing Python

Chapter 2- Python Variables

Chapter 3- Python Operators

Chapter 4- Decision-Making in Python

Chapter 5- Loop Executions

Chapter 6- Functions

Chapter 7- Modules

Chapter 8- Time and Date

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

contrary interpretations of the subject matter contained within. The information

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

from the use of this information.

The trademarks that are used are without any consent, and the publication

of the trademark is without permission or backing by the trademark owner.


All trademarks and brands within this book are for clarifying purposes only

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.

Ensure that you download the latest version of Python.

After downloading the file, double-click on it so as to launch the installation.


Click on the button “Next” in the subsequent screens.
After clicking the last “Next,” the installation should begin as follows:
Python can be used in a number of ways. In the first method, we can use the

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

click on it so as to open it.

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

double quotes for enclosing the test which is to be displayed.


The Python Calculator

The Python command line can be used as a calculator for the calculation of

arithmetic operations.

On the Python terminal, type the following:

print (4 + 8)

You can then press the Return (Enter) key and observe what happens.

This will print the following output:

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:

print (650 * 460)

This should give the following output:

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

following on the terminal:

print ("man" + 4)
The above command will give you the following result:

It means that a string object cannot be added to an integer object. However, it is

possible for us to add strings together, and this is referred to as “concatenation.”


The following example demonstrates this:

print ("wo" + "man")

The command should give you the following output:

If you need to get multiple words on the terminal, you just have to multiply
them. This is demonstrated below:

print ("man" * 10)

This will give you the following result:


Chapter 2- Python Variables

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

space will be reserved in the memory.

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

name. Consider the following example:

age = 10

In the above example, we have a variable named “age” which is storing a value
of 10.

Let us have some fun working with variables.


Write the following on the terminal:

>>> 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.

Look at this funny example:

>>> bill = 500


>>> months = 12
>>> total = bill * months
>>> print (total)
6000

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.

That sounds funny!

When giving names to variables, adhere to the following rules:

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:

Write the following program:

x=y=z=1

print (x)

print (y)

print (z)

The program will give you the following as the output:


Multiple objects can also be assigned to different values in a single line. The
following example shows this:

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

respective value. This can be demonstrated in the program shown below:

x, y, z = 1, 2, "mercy"

print (x)
print (y)

print (z)
The program should give you the following result after execution:

That is too funny!

Data Types in Python

Data type refers to the types of data which the memory can store. They

determine the amount of space in bytes that a space will be allocated. An

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

that can be applied on the variables. For example, it is impossible for us to


multiply a string with another string. But you can multiply an integer with

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

assigning some value to them. See the example given below:

number1 = 5
number2 = 20

When you call the variable “number1,” you will get 5, and if you call variable

“number2,” you will get 20 as the result. This is shown below:

number1 = 5

number2 = 20

print (number1)

print (number2)

The program will give the following result:


Python Strings

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.

Let us use an example to demonstrate this further:

name = 'Mercy John'

print (name) # this will print the complete string

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

print (name * 2) # this will print the string two times

print (name + "Student") # this will print the concatenated string

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 program should give you the following result:


When we print “(name),” we will get all the characters in the name. That forms

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.

The following example demonstrates how we can work with lists:

list = [ 'wxyz', 500 , 4.87, 'mercy', 96.2 ]

list1 = [547, 'mercy']

print (list) # Prints the complete list

print (list[0]) # Prints the first element of list

print (list[1:3]) # Prints the elements from 2nd to 3rd

print (list[2:]) # Prints the elements from the 3rd element


print (list1 * 2) # Prints the list two times

print (list + list1) # Prints the concatenated lists

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

elements of different types. We have combined both numbers and characters in


our lists. Lists support this. We have then accessed our elements using the slice

operator. The program should give you the following output:


Just as in strings, the first element of a list is at index 0. In the first list, which is

“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

in lists. Consider the example given below:

tuple = [ 'wxyz', 500 , 4.87, 'mercy', 96.2 ]


tuple1 = [547, 'mercy']
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints the first element of our tuple

print (tuple[1:3]) # Prints elements from 2nd to the 3rd

print (tuple[2:]) # Prints the elements from the 3rd element


print (tuple1 * 2) # Prints the tuple two times

print (tuple + tuple1) # Prints a concatenated tuple

The program should give the following output:


Python Dictionary

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 ([]).

Consider the example given below:

dict = {}

dict['5'] = "A five"


dict[10] = "A 10"

dict1 = {'name': 'mercy','code':12444, 'dept': 'IT'}

print (dict['5']) # Prints the value for 'five' key


print (dict[10]) # Prints the value for 10 key

print (dict1) # Prints the complete dictionary


print (dict1.keys()) # Prints all keys

print (dict1.values()) # Prints all values


This will give you the following output:
Chapter 3- Python Operators
Consider the following expression:

3+4=7

In the above example, we have an addition operation. The values 3 and 4 are

referred to as operands. The + is the operator. In programming, the operator is

the symbol used to manipulate the values of the operands. Python supports
different types of operators.

It is funny, as one can do some mathematics while programming. Let us discuss

some of the operators which are supported in Python.

Arithmetic Operators

These are used for performing the basic mathematical operations such as
addition, subtraction, multiplication, and division. In this case, we use the

operators +, -, * and / respectively.

The following are the two arithmetic operators which you may not know what
they do:

% (Modulus) - this operator returns the remainder after division. Example

7 divided by 3 (7/3) is 1. 3 goes into 7 two times to get 6, and 7 subtracted


6 is 1.

7%3=1

** (Exponential)- this will do an exponential operation on the operands.

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)

The program will give you the following result:


Chapter 4- Decision-Making in
Python
In programming, it is always good for us to come up with logical constructs

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

determined by those conditions.

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

the grade is found to be A, and “Good” if the grade is found to be B.

Python supports various decision-making statements. Let us discuss these.


“if” Statement

In this statement, the condition is set using the “if” statement. The condition is

evaluated and once it is found to be true, the statements below it will be


executed. It is created using the following syntax:

if expression:

statement(s)

The “expression” is checked, and if it is found to be true, the statements below it


will be executed. Isn’t this funny? This shows how the Python interpreter can be

made to make decisions. If this expression does not evaluate to true, then the

interpreter will proceed to interpret the next if statement in the program.

Consider the example given below:

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":

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!")
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:

The “if…else” Statement

In this statement, we combine an “else” statement together with the “if”

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

the “if” expressions. Consider the following example:

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

demonstrated in the following example:

grade = "C"

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")


In the above example, the value of the grade has been set to C, meaning that the

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

Python, otherwise, you will get an indentation error.

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

functionality can be achieved by use of the “if…elif” statements. This can be

used as shown below:

grade = "C"
if grade=="A":

print ("That is excellent kid, you got an A")

elif grade=="B":
print ("That is good kid, you got a B")

elif grade=="C":

print ("That is fair kid, you got a 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")

Execution of the program will give the following result:

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":

print ("That is excellent kid, you got an A")

elif grade=="B":

print ("That is good kid, you got a B")

elif grade=="C":

print ("That is fair kid, you got a 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

by the use of a nested “if” statement.

A nested “if...elif...else” statement can take the following syntax:

if expression1:

statement(s)
if expression2:

statement(s)

elif expression3:

statement(s)

else

statement(s)
elif expression4:

statement(s)
else:

statement(s)

Consider the example given below:


marks=70;
if marks==70:

if marks<80:

print ("Mark is 70 and less than 80 ")


else:

print ("The marks is not 70 and not less than 80")

else:

if marks==40:

print ("You scored 40 marks")


else:

print ("Your mark is not 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

can be implemented simply by use of a loop. Consider the following example:

for var in [10]:

print ('Hello world\n' * var)

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.

This is amazing! We could also have done it manually as follows:

print ("Hello world")

print ("Hello world")


print ("Hello world")

print ("Hello world")


print ("Hello world")
print ("Hello world")

print ("Hello world")


print ("Hello world")
print ("Hello world")
print ("Hello world")

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!

Let us discuss the Python Loop statements in detail.

“for” Loop Statements

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:

for repetitive_var in sequence:

statements(s)

A good example of this is our previous Hello world example:

for var in [10]:

print ('Hello world\n' * var)


We have defined a variable named “var.” We could also give it another name,

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.

Consider the following example, which demonstrates how we can write an


advanced “for” loop:

for letter in 'Mercy':

print ('Letter:', letter)

print()
students = ['john', 'mary', 'tom']

for student in students:

print ('Student name :', student)

print ("Good bye!")

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

names for us.

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:

students = ['john', 'mary', 'tom']

for index in range(len(students)):


print ('Student name :', students[index])

print ("Good bye!")

This will give you the following result:

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.

The len function gives us the entire elements of the 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:

print ("Even numbers were found")

break
else:

print ('There are no even numbers in the list')

Execution of the program gives you the following result:

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]

for num in nums:


if num%2==0:

print ("Even numbers were found")

break

else:

print ('There are no even numbers in the list')

This will give you the following result:

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

how to combine a decision-making statement, in this case the “else” statement


with a loop statement, specifically the “for.” I hope you are enjoying this and

becoming an expert!

The “while” Loop


In this type of loop statement, we set a condition and some statements which will

be executed. The statements will be executed as long as the condition evaluates

to a true. This loop statement takes the following syntax:

while expression:

statement(s)

The “statement(s)” in this case can be just a single statement or a block of


statements. Consider the example given below:

count = 1

while (count == 1):

print ("You must be happy because you are number:", count)

print("You are still happy")

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

while (position <= 10):


print ('You must be happy because you are position:', position)

position = position + 1

print ("Now you are not happy! Work hard in class!")

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

may run forever due to an always true condition.

Consider the example given below:

var = 1

while var == 1 : # This condition will create an infinite loop

print ("The value of var is 1")

print ("Good bye!")

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:

for repetitive_var in sequence:

for repetitive_var in sequence:

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()

Just run the program and observe what will happen:


Chapter 6- Functions
A function is a block of code which can be reused and is used for some multiple
actions as a single action. With functions, a large group of code can be grouped

together into a function and when we need to use the code, we will just have to

call the function. This creates a property called “code reuse.”

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:

def printstring( mystring ):

#This is the string to be passed to the function


print (mystring)
return

In the above example, we have defined a function named “printstring.” We have


passed “mystring” to this function, and this will be the parameter for the

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

you to get a complete working program.

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

previous “printstring()” function so as to demonstrate this. Oooh! Did I use () in


the function name? Yes, that is why we write functions. Whenever you see those

brackets, know that it is a function. Good!

Consider the following code, which shows the advanced form of our previous
functions:

def printstring( mystring ):

#This is the string to be passed to the function


print (mystring)

return
#The function call can now be done as follows

printstring("I called the user defined function first!")

printstring("I called the user defined function second")

This will give you the following output after execution:

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

function which it is calling. Consider the following example:

def myfunction( list ):

"This changes a passed list into this function"

print ("Function values before the change: ", list)


list[2]=20

print ("Function values after the change: ", list)

return

#the function can be called here

list = [11,12,13]
myfunction( list )

print ("The values outside function: ", list)

The program will give you the following output:


In the above example, we have just maintained a reference to the object which is

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:

def myfunction( list ):

"This changes a passed list into this function"


list = [5,2,8,4] # This would assi new reference in mylist

print ("The values in the function: ", list)

return

# Now you can call changeme function


list = [20,10,70]

myfunction( list )
print ("The values outside to the function: ", list)

This should give the following result:


The parameter “list” is local to our function myfunction(). If list is changed

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.

You should view it as a file which has Python code.

Consider the simple Python module given below:

def print_func( par ):

print "Hello : ", par

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]

In Python, we have what we call a “search path.” This is simply a list of

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.

We can import the module as shown below:

# Import module printfunction

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.

Importing Specific Attributes

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.

This statement takes the following syntax:

from modulename import name1[, name2[, ... nameN]]

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

attributes which are to be imported.

Consider the module given below for Fibonacci numbers:

# Module for Fibonacci numbers

def fib(n): # will return the Fibonacci series till n


result = []

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

treated as an attribute. This is a good scenario for us to use the “from…import”

statement. We can do it as follows:

>>> from fib i


mport fib

>>> 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:

from modulename import *

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

used and it will import all of them into your namespace.

Execution of Modules as Scripts

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:

# A module for Fibonacci numbers

def fib(n): # return the Fibonacci series till n


result = []

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)

The program should give the following result:


Chapter 8- Time and Date
There are several ways that you can handle time and date in Python. Imagine
writing your program and it gives you the current date and time, or a future date

when you are planning to have an event, maybe a birthday or a school

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()

print ("Ticks number since 12:00am, January 1, 1970:", ticks)

Execution of the program will give the following result:

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

In Python, time is handled as 9 tuples. Consider the following example:

import time; # We are importing the time module into our namespace

print (time.localtime())

This will output the following:

The output shows the year, the month, the day, and the time in hours, seconds,

etc. This is a bit advanced.

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())

print ("Local current time is :", localtime)

This will give you some output related to the following:

It is also possible for you to format the time according to the way you need. The

“asctime()” function provides us with a simple mechanism of getting time in a

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

this, as demonstrated below:

import time

localtime = time.asctime( time.localtime(time.time()) )

print ("The Local current time is :", localtime)

This will give you the following result:


Python also has the “calendar” module, which can help us to play around with

the monthly and yearly calendars. The following demonstrates how one can print
a specified calendar for a particular month:

import calendar

cal = calendar.month(2016, 11)

print ("This is the calendar for November 2016:")


print (cal)

The output is as follows:


That is the calendar for the month. You must be laughing at this point. That is
how sweet Python is. You can play around with the above program by changing

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

computer to perform some tasks and it obeys! That is the concept of

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!

You might also like