Learning Python The Ultimate Guide For Beginners To Coding With
Learning Python The Ultimate Guide For Beginners To Coding With
Author Name
Oliver Soranson
Table of Contents
Introduction
Who Is This Book For?
Brief History of Python Language
Why Python
Features of Python Language
How Python Runs Program
Python Implementations
Installation and Configuration on a Different Operating System
Installing Python on the Mac Operating System
Window Installation
Linux and UNIX installation
Chapter 1: Basics in Python
Keywords
Indentation and Lines
Multiple Line Statements
Variables
Rules to Variable Naming
Avoiding Variable Name Errors
Data Types in Python
String
Using Quotes Inside Strings
Using Methods to Change Case in String
Using Variables in Strings
Comments
How to Avoid Syntax Errors When Using Strings
Operators in Python
Arithmetic Operators
Comparison Operators
Assignment Operators
Logical Operators
Membership Operators
Summary
Sample Program to Illustrate Operators in Python
Numbers in Python
Integers
Summary of Number Data Types
Floating-Point Numbers
Complex Numbers
Chapter Review
Chapter 2: List & Tuples in Python
Definition of List
Accessing a List Item
Index Positions
Adding, Changing, and Removing Elements in a List
Modifying Elements
Adding Elements
Append an Element to the List End
Inserting Elements
Removing Elements
Remove Items Using del Statement
Using the pop() Method to Remove an Item
How to Remove an Item Using Value
Organizing a List in Python
Using the sort() Method
List Length
Summary
Looping Through a Complete List
Looping in Python
More actions on a “for Loop”
Performing Actions After a for Loop
Dealing with Indentation Errors
Forgetting to Indent
Numerical Lists
range() Function
Making a List Using range() Function
Performing Statistics on Number List
List Comprehensions
Working with List Part
Slicing a List in Python
Using Loop in a Slice
Tuples
What is a Tuple?
Using loop in a Tuple
Writing Through a Tuple
Summary
Chapter 3: Dictionary
What is a Dictionary?
How to Access Values
Adding Key-Value Pairs
How to Modify Values
How to Remove key-value Pairs
Dictionary with Similar Objects
Looping Through Dictionaries
Looping Through Keys Only
Looping Through Values Only
Nesting Dictionary
How to Use a List Inside a Dictionary
Summary
Chapter 4: Conditional or Decision Statements
Introduction
Conditional Tests in Python
Checking Equality
Numerical Comparison in Python
Creating Multiple Conditions
Using “AND”
Using “OR”
Boolean Expressions in Python
If Statements
Simple if Statements
if-else Statements
The if-elif-else Chain
Chapter 5: User’s Input and Loop
Using the input() Function
Compare the Two Programs Below
Multi-Line String When Using input() Function
Accepting Numerical Input in Python
Modulo Operator
Closing and Opening Files
Open Function
Introduction to While Loops
Using While Loop
Giving the Users a Choice
Flag in a Program
Exiting a Loop
Using “continue” in a Loop
Avoiding Endless Loop
Using While Loop Condition with Dictionaries and Lists
How to Move Items from a List to Another
How to Remove Instances of Particular Values from a List
Using User Input to Fill a Dictionary
Summary
Chapter 6: Functions
Defining a Function
How to Pass Information to a Function
Arguments and Parameters
How to Pass an Argument in Python
Positional Arguments
Calling Multiple Functions
Keyword Arguments
Default Value
Chapter 7: Classes in Python
Creating a Class
Example – Creating the Cat Class
__int__() Method
Key Terms
Conclusion
Introduction
Why Python
Interestingly, a beginner can choose from various programming languages.
In spite of this, Python is an important option to consider because it is easy
for anyone to use. Additionally, it can be used on various platforms without
any need to change things. The following are benefits that make people love
using Python.
Readability: The language is designed in such a way that it
works with the English Language. This makes it easier for
anyone to read without requiring any aid. Python also has strict
rules as regards the punctuations.
Libraries: The language has been in existence for over 30 years
and contains codes that other programmers can use effectively.
Community: The community for Python is large because of its
popularity. There are workshops where you can meet people to
ask questions and learn more about the language. As a beginner,
such a community can help you to learn faster and meet others
who are experienced more than you are.
Different platform: Python works on various operating systems
such as Mac, UNIX, Windows, etc.
Python Implementations
Don’t get confused about python implementation because is the program or
environment that provides the support needed for the execution of your
program. This is represented by the CPython reference implementation.
What this does is to help you while executing the various statements and
codes needed in the program. We have various variants of CPython, with
each making a big difference. The following are some features, which are
available in these various variants. They include:
Stackless Python – This has an importance on concurrency while
using tasklets and channels. It is mostly used programs such as
Nintendo DS
CrossTwine Linker – This is a combinational feature between
any add-on library you choose and CPython. It offers better
performance, especially when the codes come with it.
Wypthon – This involves the re-implementation of certain
aspects of Python that doesn’t allow the use of byte code.
With this, Python will be installed. The standard location and libraries are
located at /usr/local/bin and /usr/local/lib/Python respectively
Chapter 1: Basics in Python
Once you have the software installed on your system, it is time to begin
your programming adventure with Python. I will start with the
fundamentals such as variables, strings, and keywords. In this chapter, you
will learn and write your very first program in Python, the different data
you can work with, how to use variables, and keywords. Let us begin with
the basics to get your coding started right away.
Keywords
Some terms don’t require much explanation. The word represents what they
mean. The same applies to keywords. Keywords are reserved words that are
used specifically by the programming language. Each programming
language has its unique keyword, which is meant for a particular purpose.
Furthermore, avoid using these keywords elsewhere in your code. If you
decide to neglect this instruction, you will end up with your program not
working properly or receive an error alert. The following are reserved
keywords used in Python Programming Language:
async assert as and
def from nonlocal while
continue for lambda try
elif if or yield
else import pass
global not with del
in raise false await
return none break except
true class finally Is
Let us begin with the fundamental “Hello” program that is the first step for
any programmer.
Print (“Hello, Welcome to Python Programming!”)
Python programs always end with the extension .py Let us save this
program as Hello.py. Please always remember to save each example
using its name in order to recall them when necessary . When you use
your editor or IDE, the file is run via the interpreter, which then determines
the words used in the program. For instance, in the program below, the
interpreter will see the word encircled in parenthesis and prints what is
inside the parentheses. In the course of writing Python codes, the editor
may highlight certain parts of the program. For instance, it recognizes that
print () is a function name and uses a particular color to differentiate it.
However, when it gets to the word “Hello Welcome to Python
Programming!” it recognizes that it is a Python program code. Therefore, it
uses a different color to differentiate it from the other code. This unique
feature is known as syntax highlighting and is useful for beginners.
if False:
print "False"
else:
print "True"
Consequently, all continuous lines you indent using the same number of
spaces will for a block. Let us use another example to show various
statement blocks. I will advise you not to try to understand the logic of the
program. However, your aim is to understand the various blocks
irrespective of their structure.
import sys
try:
# open file stream
file = open(fileName, "w")
except IOError:
print "Error when writing to", fileName
sys.exit()
print "Enter '", fileFinish,
print "' When finished"
while fileText != fileFinish:
fileText = real_input("Enter text you want: ")
if fileText == fileFinish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
fileText = real_input("Enter filename: ")
if len(fileName) == 0:
print "Next time input something"
sys.exit()
try:
file = open(fileName, "r")
except IOError:
print "Error reading file requested"
sys.exit()
fileText = file.read()
file.close()
print fileText
Total_Number = number1 + \
number2 + \
number3
Variables
A variable is a storage location, which has a name assigned to it. In Python,
we can assign a value to a variable and recall these variables. I believe an
example will make things clearer. Remember our first program (hello.py),
let us add an additional two lines. Consider the program below:
print(outcome)
When you run the program, your output will be the same as the previous
one, which was:
print(outcome)
When such an error occurs, the Python interpreter figures the best way to
solve the problem. It provides a traceback once the program cannot run
successfully. Not many programming languages have this feature to
traceback an error. Let us look at how the interpreter will respond to our
program above
print(outcome)
You must understand that programming languages are strict; however, they
disregard bad and good spellings. Because of this, you don’t need to
contemplate about grammatical and spelling procedures when creating a
variable name.
Exercises to Try
Write a program that intends to perform the following things. Ensure to
save the file and following the variable naming rules.
Write a program that assigns a message to a variable name of
your choice and print the message
In this second program, change the value and use a new
message. Then print the message.
Tick the wrong variable names from the list below
1_school
Fred Love
Fred_love
_exercises
Firsttwoletters
Note, I will emphasize on the first two while the list, tuple, and dictionary
will be included in a single chapter.
String
This is a series of characters, which is enclosed in quotes. In Python,
anything in quotes is regarded as a unique character. Both single and double
quotes can be used to form a string in Python.
‘Hello World’
“Hello World”
The two statements would produce the same output if we were to run it.
Once you write the code, save the file as name.py before running it. The
output will be as follow:
Johnson Boris
johnson boris
JOHNSON BORIS
first_name = “johnson”
last_name = “boris”
1. full_name = f “{first_name}
{last_name}”
print(full_name)
If you want to insert a variable value to a string, you have to add the letter
“f” directly before the opening quotation mark
Consider the code below
United Nation!
U
United
Nations!
United Nation! United Nation!
United Nation! United State
Comments
If you observe in the program above, we use the symbol # to begin a
statement after declaring a variable. Nevertheless, it shouldn’t be used
within a string literal. The Python interpreter ignores comments because
they are not part of the program but provide an explanatory note for the
programmer. Let us look at this example below:
In this situation, the apostrophe is inside the double quote. The interpreter
won’t see anything wrong with this program. However, consider the code
below.
If you run it, the interpreter will indicate a syntax error. Ensure you avoid
this kind of mistake
Exercise to try
1. Use a variable name of your choice to represent your name and
print the message “Python Language is the best!”
2. Declare a variable name and assign a name to it. Furthermore,
print the name in title case, uppercase, and lowercase.
3. Write a simple program, which uses four variables. The variables
must be address, phone_number, age, and sex. Then assign
values to each variable in the program.
Bonus Answer for Exercise 3
Simple and short, your program is ready for execution. Remember to save it first before running.
If you have done that, your output will be as follows:
Operators in Python
Operators in a programming language are used to carry out various operations on variables and
values. These operators allow programmers to manipulate variables and return results based on
the operator used. In this section, you will learn various operators you need to manipulate
operands.
Arithmetic Operators
These operators are by far the simplest you will find in any programming language. With these
operators, you can perform arithmetic calculations such as addition, division, subtraction,
multiplication, exponent, modulus, etc. Let us see how these operators can be used in a python
program.
number1 = 6
number2 = 3
print(number1 + number2)
print(number1 –number2)
print(number1 * number2)
print(number1 / number2)
print(number1 % number2)
print (number1 **2)
9
6
1
8
2
0
2
5
Arithmetic operators are very easy to use and straightforward for any beginner to understand.
Comparison Operators
From the name, you can easily understand what these operators are used for. They compare
values on both side of an operand and determine the relationship between them. At times, they
are known as relational operators. These operators include <>, <=, >=, !=, == etc. They compare
values and return the results in true or false. let us rewrite our previous arithmetical operator
example.
number1 = 6
number2 = 3
print(“number1 > number2”, number1 >number2)
print(“number1 < number2”, number1 <number2)
print(“number1 != number2”, number1 !=number2)
print(“number1 >= number2”, number1 >= number2)
print(“number1 <= number2”, number1 <= number2)
Output
True
False
True
True
False
Assignment Operators
The primary function of these operators is to assign a value to a variable. You assign what is on
the left-hand side to the right. These operators include +=, *=, -=, /=, etc.
number1 = 6
number2 = 3
print(("The value of number1 is : ", number1))
print(("The value of number2 is : ", number2))
6
3
There are also compound assignment operators where you can subtract, add, multiply a right
operand to the left before assigning it to the left. In the next program, we will add the value of
number1 and number 2 before assigning the results to another variable and print out the output.
number1 = 6
number2 = 3
result = number1 + number2
print((“ The result of number1 and number2 is:”, result))
In the program above, we just perform a simple assignment. Our output will be 9.
Logical Operators
These operators are used to test if a particular conditional statement is true or false. They include,
NOT, OR, and AND. However, there are rules that apply to these operators for them to either
return true or false. These rules are:
A NOT operator will return True only when the operand is false
An OR operator returns true if one of the operands is true
The AND operator returns true when both the operands are true
Here is an example. We will use number1 and number2 to represent true and false respectively.
number 1 = True
number2 = False
print ((“NOT number2 is: ” NOT number2))
print ((“number1 OR number2 is: ” number1 OR number2))
print ((“number1 AND number2 is: ” number1 AND number2))
True
True
False
Membership Operators
Although not commonly used, however, they are used in sequences like strings, lists, and tuples.
In Python, we have two membership operators – “not in” and “in.” The operators give you the
result depending on the variable available in the string or sequence you specified. Let us see how
you can use them in a program.
number1 = 15
number2 =56
new_list = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ];
if ( number1 in new_list ):
print("number1 is available in our given list.")
else:
print("number1 is unavailable in our given list")
if ( number2 not in new_list ):
print("Number2 is not available in our given list.")
else:
print("number2 is available in our given list")
Let see how the program runs line by line. In the first and second lines, we declare two variables
and assign values for them. In the third line, we created a list “new_list” before using an if-else
statement to test the membership operator on our list. we check if number1 is available in our
list; depending on the number, it prints the expression based on the condition it fulfills. It does
the same for number2 before printing out the desired result. In our program above, our output
will be:
Summary
Operators are important functions used in programming languages to perform various operations
on operands. However, in Python, we use operations such as:
Arithmetic operators to perform operations on operands; these operators include
addition, subtraction, multiplication, division, exponent, and modulus. Python also
uses the call functions, declare variable $ calculate, and eval function.
Comparison operators used to compare operands on both sides before determining
the relationship between them
Assignment operators to assign values to variables; we also have a compound
assignment operator, which allow you to assign the result of an operand
Logical operators, which include NOT, OR, and AND. They are used to return
either true or false, depending on the condition set.
number1 = 8
number2 = 4
print(number1 + number2)
print(number1 –number2)
print(number1 * number2)
print(number1 / number2)
print(number1 % number2)
print (number1 **2)
#Comparison Operators
number3 = 13
number4 = 9
print(“number3 > number4”, number3 >number4)
print(“number3 < number4”, number3 <number4)
print(“number3 != number4”, number3 !=number4)
print(“number3 >= number4”, number3 >= number4)
print(“number3 <= number4”, number <= number4)
#Assignment Operators
number5 = 9
number6 = 6
print(("The value of number5 is : ", number5))
print(("The value of number6 is : ", number6))
#Logical Operators
number7 = True
number8 = False
print ((“NOT number8 is: ” NOT number8))
print ((“number7 OR number8 is: ” number7 OR number8))
print ((“number7 AND number8 is: ” number7 AND number8))
#Membership Operators
number9 = 5
number10 =63
new_list = [17, 5, 9, 7, 20, 63 ];
if ( number9 in new_list ):
print("number9 is available in our given list.")
else:
print("number9 is unavailable in our given list")
if ( number10 not in new_list ):
print("Number10 is not available in our given list.")
else:
print("number10 is available in our given list")
Numbers in Python
Numbers are used in programming to store information, represent data, and keep scores, etc., In
Python, numbers are treated in several ways, depending on what they are used for. In this
section, we will look at how Python supports various numerical types, such as integer, float, and
complex numbers. Integers are easier to work with when writing programs.
Integers
You can perform operations such as addition, subtraction, multiplication, and division on
integers. In the later chapter, we will explore more on these operators. I just want you to be
familiar with them. For instance:
>>> 3+8
>>> 8 -7
>>>8*2
>>>8/4
If you want to use an exponent, then you have to use two multiplication symbol.
>>5**2
>> 12**5
Python follows the order of precedence when performing operation; with this, you can use
several operations in a single expression. Additionally, if you want to modify an order of
operation, you can use parentheses. Python evaluates the expression in the order you specify.
>>3+2*4
>>(3 + 2) * 4
In the first expression, the output will be 11. However, for the second, it will be 20. Note that
spacing doesn’t have an effect on how expressions are evaluated in Python. Notwithstanding, it
allows you to identify the operation with the highest priority when going through the code.
Floating-Point Numbers
A float is a number with a decimal point, and Python language has its way of managing decimal
numbers. They can be written in scientific notation; the letter “e” represents the 10th power.
Examples of floating numbers include 4.5e2, 0.25, 154.05588 etc. An important advantage of
using floating-point values instead of integers is that they allow bigger storage space than
integers. Additionally, they can also store numbers of smaller value. You can consider floating
point numbers as those with unlimited storage space. Interestingly, they can contain numbers as
much as 2.4548899981236585 X 10-452 and as little as ± 4.4879541268971562 × 10-452
There are various ways of allocating values when using floating-point values. You can assign
them directly or decide to use scientific notation. Don’t forget that negative exponents will result
in fraction equivalents.
Complex Numbers
Another type of number data types we have in Python is complex numbers, which include both
real and imaginary numbers. They are usually in this form – a + cJ where “a” represents a float
and a real part of the complex number. Alternatively, the “cJ” comprises of the float “c” whereas
“J” is the square root of an imaginary number. In this situation, this makes c to be the imaginary
part of the number.
This may look complex but let us use an example to make it simple
x = 5 + 9j
y= 9 – 5j
z=x+y
print(z)
Chapter Review
A variable is a storage location, which has a name assigned to it
Variables must begin with a letter. However, they can have underscores and
numbers
Variable declaration: variable_name = value
Strings are a series of characters enclosed in quotation marks
Python data types include numbers, tuple, dictionary, list, and string.
Python number data types comprise of integer, floating numbers, and complex
numbers.
Chapter 2: List & Tuples in Python
In this chapter, you will learn everything you need to learn about a list in
Python programming. Lists give you the opportunity to store a particular set
of information in a place irrespective of the number of items in such a list.
They are important features in Python that are accessible to programmers.
Definition of List
A list refers to a data type that contains a collection of items in an orderly
manner. For instance, a list can comprise the alphabets, digits, or names of
the street in a country. Below is the syntax structure for a list:
list = [item1, item2, item3, itemN]
Consider the list of items in a kitchen in this code.
dishwashe
r
Index Positions
The first index position in Python is not 1 but 0. If you observe in the
example above, you will see that when indexed the third item, we started
counting from 0. You can see that pot (0), kettle (1), fridge (2), while
dishwasher (3). Peradventure, you run a Python program and get a different
result; you have to check if you are making a number error.
Always remember that the second element in any list starts with an index of
1. A simple way of knowing what the particular index number will be is to
substrate one from the item you want to index. Does that sound simple?
For instance, we want to access only the item “microwave. To do that, you
have to count the number of items to get to “microwave” and subtract one.
from the code, if you count first, you will discover that “microwave” is the
5th element. However, to index it to print only “microwave,” you have to
substrate one from the element. Your code will be like this:
Let us use another example to index the third and sixth items.
dishwashe
r
bowls
Assuming you only want to access the last element, Python has a unique
way of doing that. You can do this by using an index of -1. With this,
Python returns the last item.
In this example, the code will return “bowls.” It is easy to remember this
syntax. You do not have to know the particular length of the list. This also
applies to other negative index values. It is like going backward. You can
use the negative index to access the second or third items in a list. For
instance,
knife
microwav
e
Exercise to Try
Write a Python program, which contains a list of all your special
friends. Then print their names by accessing each element in
your list.
From the list, you created above, print a greeting message to
each name you access in the list.
Think of any means of transportation you can remember and
write a list of items used within them. Then make a statement on
some of these elements in the list and print it.
Modifying Elements
You can modify elements in an element similar to how you can access it.
Furthermore, the same syntax applies to when you want to access an
element. To modify an element, you will use the list name, followed by the
index element that you want to modify, and then provide the new value to
want to change. Well, this may sound foreign; however, let me use a simple
example to illustrate how you can do this. For instance, we want to change
dishwasher to spoon in the example below, how can you do that.
kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”
“knife,” “bowls”]
print(kitchen_item)
kitchen_item[3] = “spoon”
print(kitchen_item)
The first two lines of code define our original list, which contains the word
“dishwasher.” The third line changes the element from dishwasher to spoon.
If you do it correctly, you will get the output as:
kitchen_item.append(“spoon”)
print(kitchen_item)
The append()method allows us to add an element at the end of the list. The
output will be:
If you have an empty list, you can utilize the append() method to add a new
list. Assuming we want to add a new list element such as pot, kettle, and
microwave, we can do that as follows:
kitchen_item []
kitchen_item.append(“pot”)
kitchen_item.append(“kettle”)
kitchen_item.append(microwave”)
print(kitchen_item)
It is very common to build the list this way because you may not know the
particular data type the users want to keep track of in the program.
However, to give the users full control, first define an empty list, which will
hold values of the users. With this, you can use the append method to add
new elements to the list created.
Inserting Elements
The second way of adding an element in a list is by inserting the element to
the position you want through the insert() method. You have to specify the
index of both the new element and the value, respectively. For instance, we
want to insert a “spoon” after the microwave item on the list.
kitchen_item.insert(3, “spoon”)
print(kitchen_item)
What happened in the example above is that I inserted the value “spoon” at
the third index. The insert method enables us to create a space between the
“dishwasher” and the “microwave” while storing the value “spoon” to the
location created.
Removing Elements
There are situations that may warrant you to remove an item in a list. For
instance, a player may decide to remove a bird; he shoots down from the
sky from the active list. Perhaps, you want to delete a customer’s account or
cancel their account. You can remove such detail from the list. You can use
the following two ways to remove elements in a list.
What did you think will be deleted from the snippet above? If your answer
is a dishwasher, then you are wrong. Remember that Python index begins at
0. This means we start counting 0 from the first element. Therefore, the
final output will be:
You can remove any item from the position of your choice.
Using the pop() Method to Remove an Item
There are situations where you want to use an item value after removing it from the list. For
instance, you want to know the coordinates of the bird you shot, to enable you to draw an
explosion in such a position. The function of the pop()method is to remove the last item in the list.
For clarity, let us pop an example.
popped.kitchen_item = kitchen_item.pop()
print(kitchen_item)
print(popped.kitchen_item
I won’t explain the first two lines since you are already conversant with it. However, if you forget,
I will refresh your memory. The first line begins by declaring “kitchen_item” as a variable with
values including pop, kettle, fridge, dishwasher, microwave, knife, and bowls. The second line
prints out the items in the kitchen_item list.
In the third line, we popped a value from our list and store the value to the new variable
“popped.kitchen_item” additionally, we print out the remaining items in the kitchen_item list.
From the code above, our output will be:
The first line shows the complete kitchen_items, whereas the second shows the remaining items
after the popped method was used. Finally, line three shows the item removed from our list.
kitchen_item.remove(kettle)
print(kitchen_item)
In the example above, our aim was to remove the kettle from the list of kitchen items. The output
will be as follow:
Exercise to Try
The following exercises to try may seem complex; however, the offer you a huge opportunity to
include all the lists we have described in this section.
First list – If you are given the opportunity to invite 10 persons (dead or alive) for a
love feast, who will you invite. Then print a message for each individual, inviting him
or her to your love feast.
Alter the first list – Due to unforeseen circumstances, two of your invitees fell ill and
won’t make it. It means you have to send a new invite to replace the absentees. Using
a print call, list the invitees that won’t make it. Furthermore, replace the list with new
invitees and print out the full list.
Special list – Now create a new list by using the insert() method to add your best five
invitees to the love feast.
The output will be as follows when the sort method operates on the list items. Remember, it sorts
the item in alphabetical order.
What do you think will happen to our list? Well, the kitchen items will be reversed, and your
output will be:
List Length
Another important thing you can do with a list is to determine the length. To do this, you have to
use the len() function. Using our kitchen item list, we can demonstrate this.
This function comes handy, especially when you want to determine the number of birds that
remains to be shot.
Summary
I am convinced that you know what lists are, how to work with them, including adding and
removing elements in a list. Furthermore, you know how to determine the length of a list; however,
I want to go a step higher by introducing how you can work with items in a given list effectively.
We will loop through these items with a few line codes. With looping, you can work with any list,
irrespective of how many items contained in it.
In the first line, we began by assigning elements to the variable name “magicians_name.” You
should be familiar with this by now if you have been following. The second line tells the
interpreter to bring a name from our magicians_name list and assign the element to the variable
magician. Then the third line prints the name assigned to the variable magician. The interpreter
repeats the process for the remaining items in the list and produces the output. If you type the code
properly, your output will be as follow:
Greg
Perpetual
Amos
Looping in Python
The theory of looping is significant in any programming language, including Python, because it
provides an easier way for a computer to perform automatic repetitive tasks. For instance, in our
previous magician program, in the second line, the interpreter reads the line (magician in
magicians_name). The line informs the interpreter to retrieve the first value of the magicians_name
list. It further assigns it to the variable magician. The first value is “Greg,” and the interpreter goes
to read the next line – print(magician) .
The interpreter goes back to the second line and retrieves the second name “Perpetual” before
assigning it to the variable magician. Then the last line is executed, which prints the name
“Perpetual.” Once this is completed, the interpreter repeats the loop again to evaluate the last value
and print “Amos.” Since that is the last loop, there is no more instruction to execute, the program
halts. In the course of using a loop in Python, remember that the steps are repeated once for each
element in the list, irrespective of the number of elements in the list you created. Additionally, you
have the liberty to select the name you desire to store your values in the program. However, it is
important to use a meaningful name. For instance, let us use a list of lions, horses, and cars.
This kind of naming convention will enable you to follow the actions performed on each item in
the loop. You can also identify the section of the code with errors when you use singular and plural
names.
More actions on a “for Loop”
You can perform whatever thing you want on each item when using a for loop. Instead of using a
new example, I will use our magician example. In this example, I will print a message indicating
that each magician did perfectly well.
The first two lines do not require any explanation. However, the only alteration in the code is the
third line, where we created a piece of unique information to every single magician, beginning with
his or her name. During the loop, it goes through the first value, which is “Greg” and prints the
message after the name. it does the same thing for the value “Perpetual” before running through the
loop for the third time to print the value “Amos” with the message. The output will show a
customized message as follows:
You can write many codes as possible inside a for loop. Each indented line that follows the line
“for magician in magicians_name” is regarded to be within the loop with each indented line
performed once for every single item. For instance, let us add another line to our previous example,
telling the magicians to keep the good work going every day.
If you observe clearly, each print() method is properly indented; therefore, each line will be
executed once for the element in the list. However, (\n) in the second print line is a newline, which
requests for a blank line to be inserted after the last statement before going through the loop. With
this newline, the message becomes neatly grouped for the magician list. Let us see how the output
of the program will be.
You see how neatly the output is; this makes your program understandable. You can add as many
lines of codes you want in a “for loop.” Ensure to include some lines of codes in this program to
understand the concept behind looping in Python.
The only inclusion of this line of codes is the last statement. If you look closely, the first two
print() methods were properly indented. However, the third one is different; hence, it will be
printed once. The output will be as follows.
Forgetting to Indent
A for loop always require indentation; however, if you forget it, Python will remind you. save this
program with magic.py Let us look at the example below.
In this code, the third line should be indented but wasn’t. Once the Python interpreter encounters
such statement that should have an indented block but didn’t find any, it indicates an error with the
code as follows:
To solve this error, you have to indent the line of code properly. As simple as this mistake may be,
it can keep you from getting an error each time you run a program.
Besides forgetting to indent, you may forget to indent statements in a loop. Your loop may run
successfully without any errors, but your output will be different from what you expected. When
this happens, it signifies you are doing several tasks inside your loop and didn’t indent some of the
lines of codes. For instance, you didn’t indent the second line in the magician code that says, “keep
the good work going every day, (magician.title()}. \n”)
The line in bold and italicize should have been indented, but the interpreter finds at least a
statement indented after the “for magician in magicians_name” a statement. However, it doesn’t
indicate any error; when the first print() method takes action for each name contained in our
magician list, it prints the same message to the names. However, for the second print() method,
because it is not indented, it executes the loop once before halting the program. Among the three
magicians (Greg, Perpetual, and Amos), only Amos will receive the message, “Keep the good
work going every day.” The output of this program will be as follow:
This error is also known as a logical error because the syntax is an acceptable Python code.
However, it doesn’t produce the result we expected because of the logic error in the code.
Therefore, if your goal is to repeat a certain code once for every item in a list, then you can do that
with indentation.
Exercise to Try
Fruits – Consider at least four of your much-loved fruits. Store these preferred fruit
names in the list of your choice and use a “for loop” to generate each fruit’s name.
Then modify the “for loop” to produce a statement using the fruit name rather than
printing the name of your favorite fruit only. Additionally, for every fruit in the list,
you should generate an output that says, I like apple fruit.
Animals – Think of four animals with common features in life. Store their names in a
list of your choice. Furthermore, implement a conditional test using “for loop” to
display every animal you on your list.
Modify your line of code to produce a sentence about each animal. For
instance, you can say, A lion is the bravest animal I have ever known
Add another line to your program, indicating the unique features of these
animals. For instance, you can print a general statement like; these
animals are dangerous to human beings.
Note: These programs are very simple to write if you have followed our previous examples above.
Study them properly and write your own code. Practice more, and you will be perfect when it
comes to writing Python programs.
Numerical Lists
So far, we have been dealing with string as it relates to the list. However, in this section, you will
learn how to perform certain operations on numerical values. In Python, there are many reasons
that may warrant us to store a number. For storing numbers, lists are very important, and Python
provides various tools to perform such action effectively. If you can understand these tools
effectively, you can work perfectly well even if the list contains thousands of items in it. let us look
at certain operations you can perform on a number as it relates to the list.
range() Function
This function is a unique function that allows a programmer to easily generate a sequence of
numbers. In the example below, we can print a range of numbers from 6 to 15.
In as much as the code seems like printing the numbers from 6 to 15, however, it doesn’t print the
number 15. Our output will be as follow:
6
7
8
9
1
0
11
1
2
1
3
1
4
In our example below, the range() function prints only the numbers from 6 to 15. Well, this is the
product of the off-by-one behavior, which exists in most programming languages. The function
makes the interpreted to start the counting process at the initial number but stops at the second
number before reaching the number indicated. However, if you wanted to print out the number 15,
that means you have to extend the stopping point by one. In this case, it is 16. Therefore, your code
will be as follows:
6
7
8
9
1
0
11
1
2
1
3
1
4
1
5
If your output doesn’t match what you wanted when using the range() function, then you have to
adjust the ending value by 1.
Making a List Using range() Function
You can exchange a number list by using the list() function. Nevertheless, you need to wrap the
list() within the range() function. With this, your final outcome will be similar to a number list. We
will use our previous example of a number range to illustrate this example. You will see the
difference between the previous program code and this new one.
It is also possible to skip some numbers in the list by using range() function. If we add a third
argument to the range(), the interpreter uses that value to perform a step size. For instance, we want
to print even numbers from 1 to 16. What the program does is, to begin with, the value 2 and
increases that value by 2. In order words, it starts at 2 and repeatedly adds 2 to the initial number
and continue until it reaches the last number.
2, 4, 6, 8, 10, 12, 14
1, 3, 5, 7, 9, 11, 13, 15
number_squares=[]
for numb in range(1, 15)
numbers = numb**2
number_squares.append(numbers)
print(number_squares)
Besides getting even and odd numbers, you can generate any set of numbers or operations you can
envision. Programming is about thinking outside the box. For instance, you can find the square of
any number of your choice. In this example below, we will make a list comprising of the first 15
square numbers. When you want to represent exponents in Python, we use double asterisks (**).
This is the program to illustrate the first 15 square numbers.
Initially, the program will look confusing; however, I will explain it line by line. We began by
creating an empty list and called it “number_squares.” In line two, we created a loop and request
each “numb,” ranging from 1 to 15, by using the range() function. Then, in line three, we raised the
current “numb” to its second power before assigning it to the variable “numbers”; in line four,
every new “numb” of numbers is joined to our list number_squares. Lastly, the list of
number_squares is printed when the loop is finished. Then, the outcome of the program will be:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225
We can rewrite this code concisely by omitting the variable “numbers” while appending each new
“numb” directly to our list. Let us see how that is possible.
number_squares=[]
for numb in range(1, 15)
number_squares.append(numb**2)
print(number_squares)
As you can see, the two different approaches create a complex list. Remember, we omitted the
temporary variable “numbers” in the last approach. With this method, you make your program
easier to read. However, the goal is to focus on the one you understand and not to rush things.
Review the two approaches and look for the one that is more efficient.
Performing Statistics on Number List
Python has certain functions that allow you to perform statistics operation on a number list. For
instance, you can execute operations such as finding the sum, minimum, and maximum numbers in
a particular list.
>>>numbers= [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>>min(numbers)
11
>>>max(numbers)
20
>>>sum(numbers)
155
This example is just to show you how possible you can manipulate numbers in a list. You can do
the same even if the list contains a million numbers.
List Comprehensions
Previously, I explained how you could create a list of squares using four lines of code. However,
there is a simpler approach, which allows you to use a single line. A list comprehension comprises
of a “for loop” with the creation of new elements in the list, and repeatedly append each new
element. Although it is advisable for beginners to use the list comprehension, however, I included
them for you to be aware of them. let us use an example to show you how you can rewrite this
program on a line to create a square of the first 15 numbers.
We started by creating a descriptive name (number_squares) for our list. We then open a set of
square brackets, which allows us to define the expression “[numbers**2 for numb in range(1, 15)]”
for the numbers we want to keep track of in our new list. Furthermore, a loop is created to repeat
the expression pending when the condition is completed. The loop goes through the
range()function, with values from 1 to 15. If you observe carefully, we didn’t include a colon at the
end of the loop. When we run the program after saving it, our output will be as what we got in our
previous example.
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225
Because the list comprehension isn’t advisable for beginners, it doesn’t mean you can’t give it a
try. It takes consistent practice to understand the list comprehension before it will be worthwhile to
create lists comfortably.
Exercise to Try
Counting to forty – Write a program using a “for loop” to create and output numbers
ranging from 10 to 60 with 60 inclusive.
One hundred – Create a list of numbers ranging from 1 to 100. Furthermore, use the
conditional test “for loop” to display the numbers on the screen.
Summing one hundred numbers – After creating your 100 numbers, save using
another name, and perform the following tasks on it. Find the minimum, maximum,
and sum of the 100 numbers with 100 excluded.
Four – Compile a list of multiples of 4 from 4 to 40. Ensure to use a for loop for this
program and print the output
Cube – Calculate the cube of the first 10 numbers. A cube is the third power of a
number. Use a “for loop” to generate the number and print the value of the cube.
Working with List Part
In the course of learning this tutorial, you have understood how to easily access single elements in
a list, perform manipulations on numbers, and strings. However, I want to go a step ahead into
ways how you can work with specific elements in a list. In Python, we call them a slice. Consider a
full loaf of bread, which is in slices. Depending on the same, you may not finish a full loaf;
therefore, when you take four slices and wrap up the other, you have taken a specific number of
slice instead of all the slices in the full loaf.
The second line prints a slice of the element in the list, which comprises of the following players.
If you mistakenly forget the first index when slicing a list, Python spontaneously begins your slice
at the start of your list. For instance,
The same thing applies if you omit the last index of the list. For instance, you want to start your
index at 2 while omitting the second index.
With this, you can print out all elements in a list irrespective of the length and its position. You can
use a negative index, but it recalls a number from list end. For instance, our goal to display the last
four United players in our list
united_players =[ “Rashford,” “Young,” “Pogba,” “James,” “De Gea”]
print(united_players [-4:]
Rather than the interpreter looping through the full list of players in line 3, it loops only through
the first four players in the team. Then our output will be:
Slice comes handy in various situations, such as when you want to add the final score of a player in
a game when working with data or building a website application.
Tuples
If you want to store items, which can change during the course of the program, then the list works
perfectly for this situation. Modifying data or a list is very important when working with various
applications or creating web applications. Notwithstanding, at times, you may want a list of items
whose value doesn’t change throughout the program. In such a situation, you can use a tuple to
replace using a list. In Python, we call values, which cannot change throughout the life of the
program as immutable. Therefore, an immutable list can also be known as a tuple.
What is a Tuple?
A tuple is similar to the list I explained earlier. However, we use parentheses for tuple as an
alternative to square brackets used in a list. You can access each element after defining a tuple by
using each index. It is similar to what you would do if you want to access a list.
For instance, let us take the length and width of a room to be 200 by 100, which will always remain
the same size unless the building is destroyed. Therefore, putting the length and width into a tuple,
we have ensured that its size won’t change.
What we have done in the first line is to define the tuple size by using parentheses rather than
square brackets. Then in the second and third lines, we print the elements individually. Then save
and run the program, your output will be:
20
0
10
0
Let me modify the program to show you when Python recognizes an error when you try to alter the
tuple value.
In the second line, I try to change the value from 200 to 220. However, Python will return an error.
We try to change a tuple, which isn’t possible with such an object.
20
0
10
0
Writing Through a Tuple
As already stated, you cannot modify or alter a tuple; however, you can allocate new values to the
variable representing the tuple. Assuming something happens and you decide to change the size of
the room, you can redefine the entire tuple.
Summary
So far, in this chapter, you have learned everything you need to know as it concerns lists and tuple.
I am convinced that you can efficiently work with elements in a list. We also went through how to
use a “for loop” in a list, the structure of indenting a Python program, and popular indentation
errors to avoid. You learned how to make numerical lists and perform certain operations such as
finding the maximum, minimum, and sum in a list. Additionally, we learned more about slicing a
list and getting only the details you want in a list.
Finally, you learned about tuples. You also know what makes it different from a list. The values of
a tuple cannot change, whereas that of a list can be changed in the course of the program. In the
next chapter, you will learn about using various conditional statements in Python. Endeavor to
practice the exercise provided in this chapter, as it will enhance your programming skills in Python.
If peradventure you encounter an error, take your time to go through the line indicated.
Congratulations on your promotion to the next chapter of this course.
Chapter 3: Dictionary
print(team1 [‘color’])
print(team1 [‘scores’])
The dictionary team1 stores the color and scores whereas the last two lines
access the dictionary before displaying the information as seen below
red
3
New programming concepts require consistent practicing to perfect it. Since
you are learning a new language, it is important to painstakingly understand
this concept. If you understand it, you can apply it in all real-world
situations.
What is a Dictionary?
From the program above, you can have an idea of what dictionaries are. A
dictionary is a group of key-value pairs. Every single key in the dictionary
has its corresponding value; the key enables you to have access to the value,
and it can be a list, string, number, or dictionary. Dictionaries are usually
enclosed in braces with the keys and values placed inside the braces. For
instance:
team1 ={‘color’: ‘red’, ‘scores’ : 3}
A key to value pair always have values corresponding to each other. Once
you provide the key in a dictionary, Python returns the value corresponding
with such key. Each key is linked to a value by a colon, whereas individual
key-value pairs are disconnected by a comma.
team1 ={‘color’: ‘red’, ‘scores’ : 3}
The program above has only one pair, with each matching its value,
respectively. The color matches red, whereas scores match the value 0.
The output for this code will return the corresponding key value from the
dictionary “team1,” which in this situation is red.
Python allows us to have an unlimited number of key-value pairs. We can
add more codes to illustrate this. Additionally, we can decide the particular
key-pair to print or display on the screen. In this code, it will display
‘London’
team1 ={‘color’: ‘red’, ‘scores’ : 3, ‘S/N’ : 1, ‘place’ : ‘London’}
print(team1[‘place’])
London
team1[‘home_team’] = left
team1[‘away_team’] = right
print(team1)
We began by defining a dictionary “team1” and included its key and values,
respectively, before printing the dictionary. In the second phase of the code,
we assign the home team to be on the left position while the away team is
on the right. If we print the program, our output will be:
{‘color’: ‘red,’ ‘scores’ : 3}
{‘color’: ‘red’, ‘scores’ : 3, ‘home_team’: left, ‘away_team’ : right}
In our final program, we have four key-value pairs, where we added two
positions, whereas the original two specifies only color and score.
At times, most programmers find it convenient, to begin with, empty
dictionary unlike what we did by adding elements first. To fill an empty
dictionary, you have to define the dictionary without adding any key-value
pairs. The dictionary will be empty with a set of braces. For instance, if we
are to define the color and scores dictionary, that will be as follows:
team1 = {}
team1[‘color’] = ‘red’
team1[‘score’] = 3
print(team1)
What we did here is to define an empty team1 dictionary before adding
color and score values, respectively. We will get the same results as what
we got in our previous examples.
{‘color’: ‘red,’ ‘scores’ : 3}
How to Modify Values
Besides adding and creating an empty dictionary list, you can also modify a
value in your dictionary. To do this, you have to specify the dictionary name
before adding the new value. Let us change the color from red to blue.
team1 ={‘color’: ‘red’}
print(f “The color of the team is {team1[‘color’]}.”)
What we did is to first define the team1 dictionary, which contains only the
team’s color. We then print the team’s color before changing the value of
the corresponding key from red to blue. The output shows that we have
changed the team color from red to blue.
The color of the team is red.
The team’s new color is blue.
To make the program more interesting, I will track the position of the team
based on their speed in the opponent’s direction. With the ball speed, we
can determine if the team is on the left or right.
team1 = {‘home_team’ : ‘left’, ‘away_team’: ‘right’, ‘ball’: ‘ neutral’
print(f “Original direction: {team1(‘home_team’)}”)
#The team is on the left position
#Current speed of the team
if team1[‘ball’] == ‘slow’:
home_incre = 1
elif team1[‘ball’] == ‘medium’:
home_incre = 2
else:
#in opposition half
home_incre = 3
If you observe, I intentionally avoided the color and its point value in order
to make the program simple. We began by defining a team with the left and
right position, a ball speed set medium.
In the line “if team1[‘ball’] == ‘home’:” we use an if-elif-else conditional
statement to test the position of the ball. If the ball is slow, then it is on the
home team, if it is medium, then it is positioned in the middle. Run the
program and notice what the output will be. Towards the end of this chapter,
I will unveil the outcome of this program.
del team1[‘color’]
print(team1)
The only difference to our original program is the last two lines we added.
We use the del statement to delete the “color” key from our team1
dictionary. This will eventually remove the corresponding value of the key.
Our initial output will display the keys and its corresponding value, but
after the “del” statement, it will print only the scores. Let’s see how that
will be:
{‘color’: ‘red,’ ‘scores’ : 3}
{‘scores’ : 3}
If you observe, there is a difference from our previous list as we broke this
list into several lines, unlike the team1 dictionary, where everything is
written on a single line. Each candidate corresponds to his or her party;
additionally, there is always an opening and closing brace. Don’t forget to
add a comma to signify the end of a pair. With this, you can add another
key-value pair. Let us pick a candidate of our choice
list = election_list[‘Donald Trump’].title()
print(“Our Vote will be for {list}.”)
In this portion, we see that the user picked Donald Trump as their favorite
candidate.
Our Vote will be for Donald Trump.
Exercise to Try
Create a new dictionary to keep information about people you
know about living in your country. Then store the last name, first
name, city, and age of each individual. Ensure you use a unique
key for this information and print each information in the
dictionary.
Store the favorite food of 8 people in a dictionary, you know.
Print their names and corresponding food.
If you remembered what you have learned, you could easily access every
information in our user dictionary. However, what will you do if you want
to see all the information stored in our dictionary? Well, to do that, you
have to use a “for loop” to go through the dictionary. Let see how you can
put that into action.
user = {
‘last_name’:
‘Trump,’
‘first_name’:
‘Donald,’
‘username’:
‘dotrum,’
}
for k, v in user.item():
print(f “\nK: {k}”)
print(f “V: {v}”)
As you can see, for you to loop through a dictionary, you have to create
names for our two variables, which will hold last and first names in our
key-value pair. You can use any variable name of your choice. In this case,
we use k and v to represent key and value, respectively. Our output will be:
K: last_name
V: Trump
K:
first_name
V: Donald
K: username
V: dotrum
Looping through a dictionary works perfectly for a program like the list of
candidates in an election we wrote previously. Remember, it stores the
name and party of candidates approved to participate in the election. If we
were to loop through the list, we will get the names of every candidate and
generate their respective parties. Since the keys represent the person’s
name, whereas the value is the party, we can use variable names such as
name and party in our loop rather than using key and value. This will make
it easier for you to fully understand.
election_list = {
‘John Campbell’ : ‘Freedom Party’,
‘Eric Longman’: ‘Sovereign Nation Party’,
‘Amanda Drill’: ‘ Women Liberation
Movement’,
‘Condolence Rice’: ‘Democratic Party’,
‘Donald Trump’: ‘Republican Party’,
}
for name, party in election_list.item():
print(f “{name.title()}’s party is the
{party.title()}.”)
The program loops through every key-value pair in our election_list. As it
goes through, every pair of the key is assigned to the name variable while
the value is assigned the party variable. With only the last two lines, we can
generate a full list of all candidates in the election.
John Campbell’s party is the Freedom Party.
Eric Longman’s party is the Sovereign Nation Party.
Amanda Drill’s party is the Women Liberation Movement.
Condolence Rice’s party is the Democratic Party.
Donald Trump’s party is the Republican Party.
With this, you can display from a single name to millions of names in a list
to the screen.
Looping Through Keys Only
We can use the keys() method to display only the key values while omitting
the values contained in the dictionary. Let us use our election_list to
demonstrate this feat.
election_list = {
‘John Campbell’ : ‘Freedom Party,’
‘Eric Longman’: ‘Sovereign Nation Party,’
‘Amanda Drill’: ‘ Women Liberation
Movement,’
‘Condolence Rice’: ‘Democratic Party,’
‘Donald Trump’: ‘Republican Party,’
}
for name in election_list.keys():
print(name.title())
The line after the closing brace is the beginning of the “for loop,” which
tells the interpreter to pull only the keys from our election_list. Remember,
we assign names as the key. The output will be as follows:
John Campbell
Eric Longman
Amanda Drill
Condolence Rice
Donald Trump
The “for” statement pulls all the value in our dictionary list and assigns it to
the party. The print statement then prints all the values in the election_list.
This is the list of Political Party for the election:
Freedom Party
Sovereign Nation Party
Women Liberation Movement
Democratic Party
Republican Party
This approach prints all the value available in the dictionary without
verifying any repetition. Although this may work perfectly in a small list,
however, when you have to pull a large name or item, there may be room
for repetition. To avoid such repetition, there is a way out. We can use a set,
which is a group where every item is unique.
election_list = {
‘John Campbell’ : ‘Freedom Party,’
‘Eric Longman’: ‘Sovereign Nation Party,’
‘Amanda Drill’: ‘ Women Liberation Movement,’
‘Condolence Rice’: ‘Democratic Party,’
‘Donald Trump’: ‘Republican Party,’
‘Nicolas Fred’: ‘ Sovereign Nation Party,’
}
print(“The following Political Parties have been mentioned already:”)
for party in set(election_list.values()):
print(party.title())
We added another name and party to the list – Nicolas Fred. Assuming we
are printing only the value list and don’t want a repetition of the party. Once
you use the set() around the list, you don’t want duplicate; python identifies
this as a unique item in the list. In the end, there won’t be any repeated
detail.
The following Political Parties have been mentioned already.
Freedom Party
Sovereign Nation Party
Women Liberation Movement
Democratic Party
Republican Party
Nesting Dictionary
There are situations that may warrant you to store several dictionaries on a
particular list. This is referred to like nesting in Python because you can
include a dictionary in another dictionary. Nesting is very powerful if you
understand them properly, and we will use an example to explain it better.
The team1 dictionary list comprises of a single team but doesn’t have the
space to store additional information concerning a second team. How can
you control a group of teams? You can do this by making a list, which has
each team in a dictionary. Consider the program below:
team1 = {‘color’: ‘red’, ‘scores’ : 3}
team2 = {‘color’: ‘black’, ‘scores’ : 5}
team3 = {‘color’: ‘blue’, ‘scores’ : 0}
team4 = {‘color’: ‘brown’, ‘scores’ : 9}
If you observe, the teams all have the same features – color, scores, and
positions. However, it doesn’t mean that Python sees them as one item
rather a separate object. With this, we can modify any team of our choice
without affecting the other.
How possible is it to work with a collection of teams like we have?
Assuming a particular team decides to change their color and scores, how
can you do this? If you decide to change the color of a team, you can use
the “for loop” conditional test with an if statement. For instance, let us
change the first four teams' colors to black, scores to 5, and position to
center.
#Create an empty list to store the teams.
teams =[]
#create 40 teams.
for team_num in range(40):
new_team = {‘color’: ‘red’, ‘scores’: 3, ‘position’:
‘middle’}
teams.append(new_team)
Easily done in such a way that you can understand each line. Besides this,
you can also nest your list in a dictionary when you want a key to have
more than one value. Let us look at our previous election_list program,
where candidates can choose two political parties. Assuming we have to
store their responses in a list, a particular person can belong to more than
one political party.
election_list = {
‘John Campbell’ : [‘Freedom Party’],
‘Eric Longman’: [‘Sovereign Nation Party’],
‘Amanda Drill’: [‘Freedom Party,’ ‘ Women Liberation
Movement’],
‘Condolence Rice’: [‘Democratic Party,’ ‘ Sovereign Nation
Party’],
‘Donald Trump’: [‘Republican Party,’ ‘Democratic Party’],
‘Nicolas Fred’: [‘Sovereign Nation Party’],
}
for name, party in election_list.items():
print(f “\n{name.title()}’s party are: ”)
for party in parties:
print (f “\t{party.title()}”)
In the first bolded line, we create a list. If you observe, some names have
one political party, while others have two. We then loop through the
dictionary to run through the political party of each candidate.
John Campbell’s party are:
Freedom Party
Exercise to Try
Write a program that creates three dictionaries, which represent
three different meals with each person choosing at least a meal
of their choice. Use “for loop” to scan through the list and prints
the choice of each individual.
Make a dictionary list comprising of your favorite pets. The
dictionary must contain the type of pet, owner’s name, best food,
and unique sound. Next, loop through your pest list and display
two of this information in the list.
Create a list of your favorite cities in the world. Create a key-
value dictionary system that includes the name of the city,
population, currency, and contact details of the mayor.
Furthermore, print each city with at least three of the information
you want people to know.
Summary
In this section, you have learned what dictionaries are, how to work with
them and store information in it. Undoubtedly, you can write a program that
can access and modify each item in a dictionary. Additionally, you can loop
through the information contained in your dictionary. You can also loop
through a dictionary key, value, and key-value pairs. Furthermore, you can
nest multiple dictionaries in a list, nest dictionary in a dictionary, and nest
list in your dictionary.
Chapter 4: Conditional or Decision Statements
Introduction
In programming, we normally set certain conditions and decide which
particular action to perform depending on the conditions. To do this, Python
uses the “if statement” to check the program current state before responding
suitably to that state. However, in this chapter, you will be exposed to
various ways to write conditional statements. Furthermore, you will learn
basic “if statements,” create complex if statements and write loops to
handle items in a list. There is so much more loaded in this chapter for you
to learn. Without further ado, let us begin with a simple example.
The program below shows how you can use “if statement” to respond to a
particular situation correctly. For instance, we have a list of colors and want
to generate an output of different colors. Furthermore, the first letter should
be in the title case of the lower case.
Green
Blue
Red
Yello
w
The loop first verifies if whether the current value of the car is “kia.” If that
is true, it then prints the value in uppercase. However, if it is not kia, it
prints it in title case. The output will look like this:
Toyota
KIA
Audi
Infinit
y
The example above combines different concepts, which at the end of this
chapter, you will learn. However, let us begin with the various conditional
tests.
Checking Equality
At times, we may test for the equality of a particular condition. In this
situation, we test if the value of the variable is equal to the other variable
we decide. For instance:
>>>color = “green”
>>> color == “green”
True
In this example, we first assign the variable color with the value “green by
using the single equal sign. This is not something new, as we have been
using it throughout this book. However, the second line checks if the value
of color is green, which has a double equal sign. It will return true if the
value on the left side and that on the right side are both true. If it doesn’t
match, then the result will be false. When the value of the color is anything
besides green, then this condition equates to false. The example below will
clarify that.
>>>color = “green”
>>> color == “blue”
False
Note: When you test for equality, you should know that it is case sensitive.
For instance, two values that have different capitalizations won’t be
regarded as equal. For instance,
>>>color = “Green”
>>> color == “green”
False
>>>color = “Green”
>>> color.lower() == “green”
True
This code will return True irrespective of how to format the value “Green”
is because the conditional tests aren’t case sensitive. Please note that the
lower() function we used in the program does not change the value
originally stored in color.
In the same way, we can check for equality; we can also check for
inequality in a program code. In checking for inequality, we verify if two
values are not equal and then return it as true. To check for inequality,
Python has its own unique symbol, which is a combination of the
exclamation sign with an equal sign (!=). Most programming language uses
these signs to represent inequality. The example below shows the use of if
statement to test for inequality
color = “green”
if color != “blue”
print(“The color doesn’t match”)
In the second line, the interpreter matches the value of color to that of
“blue.” If the values match, then Python return false; however, if it is true,
Python returns true before executing the statement following it “The color
doesn’t match”
>>>myage = 25
>>>myage == 25
True
Additionally, we can also test if two numbers are unequal. Consider the
code below.
number = 34
if number != 54:
print(“The number does not match. Please retry!”)
The first line declares number as a variable and stores the number “34” in it.
The conditional statement begins in line two and passes through the line
because the number 34 is not equal to 54. Since the code is indented, the
code is then executed to produce
Besides this, you can perform various mathematical comparison inside your
conditional expressions including greater than, greater than or equal to , less
than, and less than or equal to.
>>> number = 22
>>> number <25
True
>>> number <= 25
True
>>> number > 25
False
>>> number >= 25
False
Using “AND”
If you want to verify that two expressions are both true at the same time, the
keyword “and” serves that purpose. The expression is evaluated to be true
when both conditions test to return true. However, if one of the condition
falls, then the expression returns false. For instance, you want to ascertain if
two students in a class have over 45 score marks.
>>> score_1 = 46
>>> score_2 = 30
>>> score_1 >=45 and score_2 >= 45
False
>>> score_2 = 47
>>> score_1 >= 45 and score_2 >= 45
True
Using “OR”
The “OR” keyword allows you to check multiple conditions as the “AND”
keyword. However, the difference here is that the “OR” keyword is used
when you want to ascertain that one expression is true for multiple
conditions. In this situation, if one of the expression is false, the condition
returns true. It returns false when both conditions are false.
Let us consider our previous example using the “OR” keyword. For
instance, you want to ascertain if two students in a class have over 45 score
mark.
>>> score_1 = 46
>>> score_2 = 30
>>> score_1 >=45 or score_2 >= 45
True
>>> score_1 = 30
>>> score_1 >= 45 or score_2 >= 45
False
We began by declaring two variables score_1 and score_2 and assign values
to them. In the third line, we test the OR condition using the two variables.
The test in that line satisfies the condition because one of the expressions is
true. Then, it changed the value of the variable score to 30; however, it fails
both conditions and therefore evaluates false.
Besides using the “And” and “OR” conditional statements to check multiple
conditions, we can also test the availability of a value in a particular list.
For instance, you want to verify if a username requested is already in
existence from a list of usernames before the completion of online
registration on a website.
To do this, we can use the “in” keyword in such a situation. For instance, let
us use a list of animals in the zoo and check if it already on the list.
In the second and fourth lines, we use the “in” keyword to test if the request
word in a double quote exists in our list of animals. The first test ascertains
that “monkey” exists in our list, whereas the second test returns false
because the rat is not in the animal's list. This method is significant because
we can generate lists of important values and check the existence of the
values in the list.
There are situations where you want to check if a value isn’t in a list. In
such a case, instead of using the “in” keyword to return false, we can use
the “not” keyword. For instance, let us consider a list of Manchester United
players before allowing them to be part of their next match. In order words,
we want to scan the real players and ensure that the club does not field an
illegible player.
The line “if player, not in united_player:” reads quite clearly. Peradventure,
the value of the player isn’t in the list united_player, Python returns the
expression to be True and then executed the line indented under it. The
player “Messi” isn’t part of the list united_player; therefore, he will receive
a message about his qualification status. The output will be as follow:
change_content =
False
light_on = False
light_off = True
Boolean values provide the best means of tracking the particular condition
of a program.
Exercises to Try
Conditional Testing – Write various conditional expressions.
Furthermore, print a statement to describe each condition and
what the likely output of each test will be. for instance, your
code can be like this:
car = “Toyota”
print(“Is car == ‘Toyota’? My prediction is True.”(
print (car == “Toyota”)
If Statements
Since you now know conditional tests, it will be easier for you to under if
statements. There are various types of if statements to use in Python,
depending on your choice. In this section, you will learn the different if
statements possible and the best situation to apply them, respectively.
Simple if Statements
In any programming language, the “if statement” is the simplest to come
across. It only requires a test or condition with a single action following it,
respectively. The syntax for this statement is as follows:
if condition:
perform action
The first line can contain any conditional statement with the second
following the action to take. Ensure to indent the second line for clarity
purposes. If the conditional statement is true, then the code under the
condition is executed. However, if it is false, the code is ignored.
For instance, we have set a standard that the minimum score for a person to
qualify for a football match is 20. We want to test if such a person is
qualified to participate.
person =21
if person >= 20
print(“You are qualified for the football match against Valencia.”)
In the first line, we define the person’s age to 21 in order to qualify. Then
the second line evaluates if the person is greater than or equal to 20. Python
then executes the statement below because it fulfills the condition that the
person is above 20.
Indentation is very significant when using the “if statement” like we did in
the “for loop” situations. All indented lines are executed once the condition
is satisfied after the if statement. However, if the statement returns false,
then the whole code under it is ignored, and the program halted.
We can also include more code inside the if statements to display what we
want. Let us add another line to display that the match is between Chelsea
and Valencia at the Standford Bridge.
person =21
if person >= 20
print(“You are qualified for the football match against Valencia.”)
print(“The match is between Arsenal and Valencia.”)
Print(“The Venue is at the Emirate Stadium in England.”)
The conditional statement passes through the condition and prints the
indented actions once the condition is satisfied. The output will be as
follow:
Assuming the age is less than 20, and then there won’t be any output for
this program. let us try another example before going into another
conditional statement.
if-else Statements
At times, you may want to take certain actions if a particular condition isn’t
met. For example, you may decide what will happen if a person isn’t
qualified to play a match. Python provides the if-else statements to make
this possible. The syntax is as follows:
if conditional test
perform statement_1
else
perform statement_2
Let us use our football match qualification to illustrate how to use the if-
else statement.
person =18
if person >= 20:
print(“You are qualified for the football match against Valencia.”)
print(“The match is between Arsenal and Valencia.”)
Print(“The Venue is at the Emirate Stadium in England.”)
else:
print(“Unfortunately, you are not qualified to participate in the match.”)
print(“Sorry, you have to wait until you are qualified.”)
The conditional test (if person>=20) is first evaluated to ascertain that the
person is above 20 before it passes to the first indented line of code. If it is
true, then it prints the statements beneath the condition. However, in our
example, the conditional test will evaluate to false then passes control to the
else section. Finally, it prints the statement below it since it fulfills that part
of the condition.
station_numbers = 10
if station_numbers >=12:
print(“We need additional 3 stations in this company.”)
else:
print(“We need additional 5 stations to meet the demands of our
audience.”)
As you can see, there are three possible situations because the following set
of people can attend the cinema to watch the movie of their choice. In this
situation, how can you ascertain a person’s rate? Well, the following code
will illustrate that point and print out specific price rates for each category
of people.
person_age = 13
if person_age < 5:
print(“Your ticket cost is $0.”)
elif person_age < 17:
print(“Your ticket cost is $30.”)
else:
print(“Your ticket cost is $50)
The first line declares a variable “person_age” with value 13. Then we
perform the first conditional statement to test if the person is below the age
of 5. If it fulfills the condition, it prints the appropriate message, and the
program halts. However, if it returns false, it passes to the elif line, which
tests if the person_age is less than 17. At this post, the person’s minimum
age must be 5 years and not above 17. If the person is above 17, then
Python skips the instruction and goes to the next condition.
In the example, we fix the person_age to 13. Therefore, the first test will
evaluate false and won’t execute the block of line. It then tests the elif
condition, which in this case is true, and will print the message. The output
will be:
Nevertheless, if the age is above 17, then it will pass through the first two
tests because it will evaluate to false. Then the next command will be the
else condition, which will print the statement below.
We can rewrite this program in such a way that we won’t have to include
the message “Your ticket cost is..”. all we need is to put the prince inside
the if-elif-else chain with a simple print() method to execute after the
evaluation of the chain. Look at the line of code below:
person_age = 13
if person_age < 5:
cost = 0
elif person_age < 17:
cost =30
else:
cost = 50
print(f “Your ticket cost is ${cost}.”)
In the third, fifth, and seventh lines, we defined the cost based on the
person’s age. The cost price is already set within the if-elif-else statement.
However, the last line uses the cost of each age to form the final cost of the
ticket.
This new code will produce the same result as the previous example.
However, the latter is more concise and straightforward. Instead of using
three different print statement, our reverse code only use a single print
statement to print the cost of the ticket.
Multiple elif Blocks
You can also have more than one elif block in your program. For instance,
if the manager of the cinema decides to implement special discounts for
workers, this will require additional, conditional tests to the program to
ascertain whether the person in question is qualified for such a discount.
Assuming those above 55 years will pay 70% of the initial cost of each
ticket. Then the program code will be as follows:
person_age = 13
if person_age < 5:
cost = 0
elif person_age < 17:
cost =30
elif person_age < 55
cost = 50
else:
cost = 35
print(f “Your ticket cost is ${cost}.”)
The cost is identical to our previous example; however, the only including
is the “elif person_age < 55” and is respective else condition. This second
elif block checks if the person’s age is less than 55 before assigning them
the cost of the ticket for $50. However, the statement after the else needs to
be changed. In this situation, it is applicable if the person’s age is above 55
years, which is this situation fulfills the condition we want.
The “else” statement isn’t compulsory because you can omit it and use the
elif statement instead. At times, it is better to use additional elif statements
to capture specific interests. Let us see how to implement it without using
the else statement.
person_age = 13
if person_age < 5:
cost = 0
elif person_age < 17:
cost =30
elif person_age < 55:
cost = 50
elif person_age >= 55:
cost = 35
print(f “Your ticket cost is ${cost}.”)
The additional elif statement helps to assign the ticket cost of “$30” to those
above 30 years. This format is a bit clearer when compared with the else
block.
print( “\ Team list completed for the match against Manchester City!”)
If we decide to use the if-elif-else block, the code won’t function properly
because once a particular test returns true, the program will stop. Let us try
it and see.
if “Young” in united_players:
print(“Adding Young to the team list.”)
elif “De Gea” in united_players:
print(“Adding Dea Gea to the team list.”)
elif “Messi” in united_players:
print(“Adding Messi to the team list.”)
print( “\ Team list completed for the match against Manchester City!”)
In this code, Python will evaluate the first condition, and once it is true, the
program stops. The output for this program will be:
Exercise to Try
Consider the list of colors we have in the world. Create a
variable name color and assign the following colors to it – blue,
red, black, orange, white, yellow, indigo, green.
Use an “if statement” to check if the color is blue. If
the color is blue, then print a message indicating a
score of 5 points.
Write a problem using the if-else chain to print if a
particular selected is green.
Write another program using the if-elif-else chain to determine
the scores of students in a class. Set a variable “score” to store
the student’s score.
If the student’s score is below 40, indicate an output a
message that such student has failed
If the student’s score is above 41 but less than 55, print
a message that the student has passed.
If the student’s score is above 56 but less than 75, print
a message that the student did well
If the student scores above 76, print a message that the
student did excellently.
Chapter 5: User’s Input and Loop
The primary purpose why most programs are written is to solve a particular
problem. In order to solve these problems, users must input certain
information while interacting with the program. For instance, a player that
determines if someone is eligible to vote or not will require input from the
user. Such a program will request the user to input their age, which will
enable the program to compare their value with the laid down condition of
the program before displaying the outcome.
In this chapter, you will learn the different ways of accepting input from the
users and how it works. Additionally, you will learn how to prompt users to
provide input by using the input() function. Furthermore, I will guide on the
way to keep your code running using a while loop pending when the
condition becomes false. If you can learn how to ask for input from users
and control how long a program should run, then you can effectively write
interactive programs that will solve many problems.
The simplest means of displaying output on the screen in Python is through
the “print” statement, which allows you to pass expression or zero separated
by commas. It can also convert expressions passed through a string and
returns the results. For instance, consider the string below.
print “Learning is part of Life. Python is life”, “Does that sound good?”
Besides this, python provides two means of accepting keyboard input into
the program. You can either use the raw_input function or the input()
function. Let us begin with the input function, as it is the most widely used
input function in Python.
Using the input() Function
Have you ever stopped a moving vehicle? Do you remember what
happened? You waved your hand, and the vehicle stopped. The driver opens
the door, and you enter before he zoomed off. Yes, as simple as that
illustration is, that is what the input() function works. It pauses and waits
for an input from the user. In a similar pattern, the driver stops, the car door
opens before you hop into it. In Python, the moment the user inputs the
information, the value or information is assigned to a variable.
For instance, the program below requests the user to insert their first name
and surname. It further displays both names on the screen.
The input() function here prompts a message on what the user should do. In
this situation, it requests the users to enter their first name and surname. The
program will wait pending when the user has responded to the prompt, and
once the “Enter” key is pressed, the information is assigned to the variable
“full_name” before printing the content of the information. Assuming the
user's inputs, “Amanda Norman,” the output will be:
As simple as this, you have created your first program that requests input
from the user. Whenever you use the input() function, endeavor to include
an understandable prompt message on what the user should do or what
particular type of information you want. Additionally, it should be as brief
as possible and very instructive.
Compare the Two Programs Below
full_name = input(“Enter Name:”) full_name = input(“Please what is your first
print(full_name) name and surname?”
print(full_name)
If you observe clearly, the first program on the left hand requires a name but doesn’t explain what
type of name. it could be the full name of a street, football team, business, or drink. The instruction
isn’t concise. However, the code on the right hand clearly states what is required from the user. This
makes it easy for the user to input the information required from him or her.
message = “Please tells us your full name, to enable us to provide a personalized message.”
message += “\nWrite your full name”
full_name = input(message)
print(f “\Welcome, {full_name}!”)
This example simply shows you a way of building a multi-line string. In the first line, we assign the
variable message with the information we want the user to respond to. however, the second line
included the += operator to take the first string stored in a message and attach it with this second
one. With this, our message spans two lines. When you run the program, you should have something
like this, depending on the name you insert.
You can include as many messages you want on different lines. You can begin by practicing this
little exercise. Create a Python program that allows you to write a multi-line string with input
requests for the names of your family members.
The users enter 45; however, when we request for the value of the age from the interpreter, it returns
“45”, which is an illustration of the string value we inputted. As we already know, Python interprets
the input() function as a string since the number has double-quotes. Notwithstanding, if you decide
to print only the input, that will work well. However, printing the input as a number when it is in
string format will generate an error.
If you run this program, you will get an error. This is what you will see.
What happened in this code is that you try to use the input() function to perform a numerical
evaluation in line 3. Python generates an error message because you are trying to compare a string
with an integer type. The string in this situation is 45, which is assigned to the variable my_age,
which can’t be compared to the number value of 40.
To solve this issue, we have to use the int() function then informs the Python interpreter to accept it
as a numerical value. Therefore, it then converts the “number string” into a numerical value, as
shown below.
if basketball_height >= 7:
print( “\nYou have what it takes to participate in a basketball match!”)
else:
print(“\nYou do not meet up with the requirement for this match!”)
This program compares the height of the person to 7 inches because we already convert as a
numerical value. If the user inserts anything below 7, the message “You do not meet up with the
requirement for this match!” will display. However, let us assume the user input 8, the output will be
as follow:
Modulo Operator
Already, you should know that we have an important operator to use in manipulating numerical
values. Besides the popular addition, subtraction, multiplication, and division, we also have a unique
operator called the “modulo operator.” It is represented by the percentage (%) sign and returns the
remainder of a number divided by another.
>>> 10 % 4
2
>>> 7 % 4
3
>>> 20 % 5
0
>>> 5 % 4
1
>>> 3 % 3
0
Note: The operator does not tell us the number of times the number fits in the other number, rather
it tells us the reminder of the operator. For instance, the first example, which is 10 divided by 4, what
the module operator does here is to return the reminder when the division takes place. In this
situation, it returns the value 2 because 4 can only go into 10 twice and with 2 remaining.
Interestingly, you can use this to ascertain if a particular number is odd or even. Let see how that
works out:
num = input(“Key in a number of your choice, and I will let you know if it is odd or even: “)
num = int(num)
if num % 2 == 0:
print (f “\nThe number you enter {num} is an even number.”)
else
print( f “\nThe number you enter {num} is an odd number. “)
Even numbers are numbers we can divide by two. Therefore, when a number modulo and two are
equivalent to zero, then the number is even. However, if it turns out otherwise, then it is even. Let us
run the program and assume that you insert 46.
Key in a number of your choice, and I will let you know if it is odd or even: 46
The number you entered is an even number
Closing and Opening Files
Since you have been learning how to use the input and output functions to
display output on the screen. It is time to learn how to use data files when
writing a program. Python has basic methods and functions, which are
essential to manipulate files without you performing any operation on them.
We will explore some of these functions:
Open Function
Before you think of writing or reading a file in Python, you have to open it
through the inbuilt open() function. This creates a file object, which you can
use to call other methods related to it. The syntax is as follow:
number1 = 10
while number1 <= 20:
print(number1)
number1 += 1
Before generating the output of how the program will be, let me explain
what happens in each line of code. In the first line, we assigned the variable
number with the value 10. This is where the number begins counting. In the
second line, the while loop takes operation and runs pending when the
number is less than or equal to 20; in each loop, it prints the number to the
screen. However, the last line adds 1 to the number and returns to the loop.
In Python, to perform increment, we can use the “+=” operator. It is akin to
saying number = number + 1.
Therefore, the loop repeats because the first number 1 is less than 20. It
then prints 1 and adds 1 to test the next line. It continues this process up to
the tenth number before stopping. Finally, our output becomes:
1
0
11
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
The various programs you use nowadays involves the use of while loops.
For instance, the game you play contains or uses a while loop to continue
playing pending when you want to quit it. It would be awkward and painful
when playing a game, and it abruptly stopped without you making any
request.
In the first line, we define a variable request and give them two options on
what to do. The first is to enter a message, whereas the second is to exit the
program by entering stop. Them in line three, we defined any variable
“prompt” with an empty string. During the first time, the interpreter checks
on the variable and compare the value of the prompt1 to see if the user has
input “stop.” However, the user hasn’t inputted any value yet. The while
loop will continue to run as long as the prompt isn’t equal to ‘stop.’
During the first loop, a prompt1 is just a string without any value, so the
loop begins. Then at prompt1 = input(request), it shows the request and
waits on the user to respond. Whatever message the user enter is printed out
on the screen, and the interpreter reevaluates the condition to ascertain that
the condition is still within the while loop statement. Since the user hasn’t
entered the word ‘quit,’ the program further asks the user to make an input.
However, once the user enters “stop,” the program stops executing the loop
and halts the program.
Let assume the users in his interaction with the program entered the
following statements.
I am new to Python Programming!
Programming in Python is the best for beginners!
I am in an advanced learning phase in Python Programming!
My Python course will soon end!
stop
prompt1 = “”
while prompt1 != ‘stop’ :
prompt1 = input(request)
if prompt1 != ‘stop’:
print(prompt1)
Now reenter the statements you entered the first time and observed the
difference. If properly done, your output will be as follow
Flag in a Program
In our last example, we performed a task pending when the condition is
true. However, what if it is a more complicated program, which has
numerous events that can make the program stop?
For instance, a game can have several exit points. Do you remember the
famous snake game in Nokia phones? Remember each time the snake
touches the wall or touches itself, the game terminates. The game can also
terminate if you intentionally or mistakenly exit the game application. All
of these come with different possible events that might terminate the games.
Therefore, in testing these different conditions using a while loop statement
becomes difficult and complicated.
If you want to run a program that continues running pending when the
condition is false, then you have to define a variable, which will determine
if the program is active or not. This kind of variable is known as a flag
because it acts as a pointer to the program. With this, we can create codes
that run while the variable “flag” is positioned to be True and stops when
any of the different event's value of the flag is False. All of these sound
complicated, however, let us upgrade our previous example by using the
flag in the program.
start = True
while start:
prompt1 = input(request)
if prompt1 == ‘stop’ :
start = False
else:
print(prompt1)
In the program above, we set “start” to be “True,” and this is where the
program begins. This makes the while loop easier because there is no
comparison tested within our while statement. However, the logic of the
program is done in another part of the program. The loop will continue to
run pending when the expression becomes false.
The if a statement is contained within the while loop, which checks the
value of the prompt1 whenever the user enters their request. However, once
someone enters “stop,” we set the variable “start” to False thereby
triggering the loop to stop. Notwithstanding, anything besides the quit
statement will print the request, which the user enters.
The program here will produce the same output as the previous one, where
we directly test the condition inside the while loop. However, with the flag,
we indicate when the program is an inactive state and makes it simpler to
include additional, conditional tests.
Exiting a Loop
Well, Python allows us to use the break statement to direct the flow of our
program. For instance, let us look at a program, which asks the user about
the country they have visited in their life. In our previous program, we can
use the “break” statement to halt the program once the user enters ‘quit.’
Let see how that works.
while True
country = input(request)
if country == ‘quit’ :
break
else:
print(f “ I have visited {country.title()}.”)
The loop begins with the “while True” statement, which runs continually
pending when it reaches the break statement. The loop will continue to ask
the user to input the country they have visited pending when they enter
“quit.” The break statement takes effect when the user enters “quit” and
causes the program to exit the loop. Our output will be as followed if the
user entered Canada, Hungry, and Portugal.
even_number = 10
while even_number < 20:
even_number +=1
if even_number %2 == 0:
continue
print(even_number)
1
0
1
2
1
4
1
6
1
8
2
0
number = 10
while number <= 15:
print(number)
number +=1
When this program is run, you will get the output as follow:
1
0
11
1
2
1
3
1
4
1
5
However, let us assume that you accidentally forget to include the line
“number+=1) in the program. What will happen when Python encounters
this program?
number = 10
while number <= 15:
print(number
The program will run continuously and never stop. The value of the number
will start at 10 but won’t change. Because of this, the conditional statement
number <=15 will evaluate to True at all times. Additionally, the while loop
will not stop because it will be printing 1o upon 10 throughout the program.
Don’t beat yourself up if you face such an issue because virtually all
programmers have accidentally written an infinite loop. If you find yourself
stuck in such a situation, take a glass of cooled water and quench your taste.
There is nothing to stress yourself about; you can use the CTRL+C button
to escape from this endless loop. Additionally, you can close the Python
program. To avoid such an endless loop, you should test each while loop
and ensure the loop ends where it should.
Exercises to Try
Write a simple looping program, which asks the user to input the
names of their family members pending when the user input a
“stop” value to halt the program. In each name, it should print
what makes that person special.
Write a program that offers four different meals to customers
depending on their choice. If a person decides to take water, then
the meal should be $20. If the meal is a plate of rice, then the
ticket is $30. If the meal is a chicken pile, then the ticket is $40.
If the person doesn’t choose anything, then the ticket should be
$0. Write a loop to ask the user what meal they want and print
the price of the meal on the screen.
Use a conditional statement on the above program within the
while statement to halt the loop
When writing the second program, use a break statement to stop
the loop whenever the users enter “stop”
while unapproved_student:
user = unapproved_student.pop()
The logic of the program is very easy to understand. We assign the variable
footballers with various value, but “Oscar” repeated thrice. It prints the
names of the footballers. Then the code enters the while loop because we
have Oscar in our list in more than one instance. Inside the loop, the first
instance of Oscar returns to the while line before it reenters the loop to
ascertain if there is another Oscar. It continues in such a manner until the
list is empty. The output for our program will be”:
remarks ={}
# let set a flag to indicate that the polling is active
poll_active = True
while poll_active
# request for the name of the user and their remark
fullname = input(“\Enter your full name:”)
remark = input(“What is your country of residence?”)
Summary
In this User’s input and loop, you have learned how Python language
accepts inputs from users by using the input() function. Furthermore, you
have been equipped with the knowledge of how to work with both
numerical and text inputs. Additionally, with the looping lessons you
learned in this chapter, you could easily write programs to control a
decision. With the while loop conditional test, you can move items from a
particular list to another. Then, you learned how to create your own
dictionary using the while loop.
In the next chapter, you will learn about functions in Python. Functions give
you the opportunity to break your programs into parts; each of these parts
carries out a specific job. Additionally, functions can be called as many as
you want in the program. I know you are excited, so see you in the next
chapter.
Chapter 6: Functions
In this chapter, you will know how to write functions easily in Python.
Functions are a line of codes, which are designed to perform a particular
job. When you want to write a program that will perform a specific task,
then you have to define the function and call the function. Furthermore, I
will teach you how to pass information to functions and display them on the
screen.
Defining a Function
At times, the best way to explain a thing is to provide an example. The
program below is a welcome program that prints a message.
def welcome_user():
“ “ “ Transmit a Welcome Message.”””
Print (“Welcome to Learning Python Programming.”)
welcome_user()
def welcome_user(name):
“““Transmit a Welcome Message.”””
Print (“Welcome to Learning Python Programming, {name.title()}!”)
welcome_user(“Thomas”)
Positional Arguments
This argument is the simplest way of passing an argument in Python
because each argument in the function must match with a parameter in the
function declaring section. To see how this works, let us write a program
that shows information about animals. The function in this situation tells us
the particular type of animal and the name of the pet.
The first block of line defines a function. It indicates that the function
requires a particular animal’s type and its pet name. After defining the
function, we provided the animal kind and pet name. for instance, in the
function call (animal_list), we assign Cat as animal kind while Lucy is the
pet’s name. Our output will display the detail about the animal Cat with the
pet name Lucy.
This is a Cat.
My Cat’s name is Lucy.
Calling Multiple Functions
We can call the function as many times as we want. All we need is to add
another parameter to our function. Check the code below:
The program follows the same sequence and performs the output. However,
in this situation, we added two more parameters to the list. Therefore, our
output will look like this:
This is a Cat.
My Cat’s name is Lucy.
This is a Dog.
My Dog’s name is Bruce.
This is a Rat.
My Rat’s name is Chase.
Calling a function several times is an efficient way when you have several
parameters. The code about the details of the animal is written once inside
the function. However, whenever you want to describe a new animal, all
you need is to call the function by providing information about the animal.
Keyword Arguments
This is a name/value pair, which you pass to a function. You have to
directly link the value and the variable name inside the argument. With this,
there won’t be any confusion when you pass the argument to the function.
let’s rewrite our previous code using the keyword arguments to call our
animal_list()
This is a Cat.
My Cat’s name is Lucy.
This is a Rat.
My Rat’s name is Chase.
When using keyword arguments, ensure that the right parameter names are
used in the function definition to avoid any error.
Default Value
Besides using the keyword parameter and position argument, each
parameter can have a default value in a function. if you provide a parameter
that is providing in the function, Python uses the value. However, if there is
no parameter value, then Python uses a default value for the parameter.
I have a Cat.
My name is Lucy.
Observe that the parameter order inside the function definition must be
changed since the default value makes it pointless to stipulate the particular
animal kind as an argument. Therefore, the only argument available in the
function is the name of the pet.
Chapter 7: Classes in Python
Creating a Class
You can model anything you want using classes. The best way to explain it
is to show you an example. Let us write a simple class, Cat, which
represents a cat. Note this is not just a particular cat in question but also any
cat. What information do you want to know about the cat? Cats all have a
name; some can sit while others can spit. With this, we have important
information such as their names, ages, and behaviors (sitting and spitting).
We can use this to create a class since it is common with most cats. Once
we write our class, we can use it to make individual instances.
There are many things you will notice in this program, but don’t worry
because, at the end of this chapter, you will be familiar with this structure.
The first line of code is a class definition called Cat. The second line is a
docstring, which describes the role of the class.
__int__() Method
You may be surprised because this is the first time we are using this method
in this book. Well, a function that is part of a class is called a method. All
you have learned about functions is applicable to methods.
Notwithstanding, the primary difference between them is how a method is
called. The __int__() method is a unique method, which runs automatically
once an instance is created in a class. A method has the keyword “int” being
preceded and succeeded by two underscores. It is important to use two
underscores on both sides because if Python sees only one, the method
won’t be automatically called when you need to use the class. As a result,
may cause errors in your program.
Our __int__ () method has three parameters, which are data, name, and age.
We need the data parameter, and it must come before other parameters. You
have to include it in the definition because when the software calls this
method, it will automatically pass the data argument. In our program, we
will pass Cat() a name and an age argument. With this, whenever we make
an instance of the Cat class, we will only provide values for the name and
age parameters.
The line “data.name=name and data.age=age” contains two variable
definitions, with each having the prefix data. Any variable that is prefixed
with data is available to all methods in the class and can access them
through any instance we create in the class. What happens in
“data.name=name” is that it takes the value connected with the parameter
name and assigns it to the variable name. The same thing happens to the
data.age=age. Our cat class contains two methods – spit() and sit().
class NewClass:
"This is another example of a class"
area = 15
def room(size):
print('To ascertain the size of a room’)
# Output: 15
print(NewClass.area)
1
5
Exercises To Try
Write a function known as Television(), which accepts different
television names and names of the television to be printed.
Additionally, use a positional argument to make the television.
Also, use keyword argument to call the function
Write a function called country() that accepts the capital and
country name. Your function must print a simple sentence such
as New York is in the United State of America. Call at least four
different cities
Key Terms
Learning a new programming language comes with the knowledge of new
terms as it relates to this language. Understanding these terms will help fast
track your learning process. This section contains some important but
common Python programming terms that will equip you in his quest. To
avoid any form of confusion, and help you kick-start your learning process,
let us begin with the key terms.
Dictionary - A dictionary is a group of key-value pairs. Every
single key in the dictionary has its corresponding value; the key
enables you to have access to the value, and it can be a list,
string, number, or dictionary
Floating point - A float is a number with a decimal
Function - Functions are a line of codes, which are designed to
perform a particular job.
Keywords - Keywords are reserved words that are used
specifically by the programming language. Each programming
language has its unique keyword, which is meant for a particular
purpose
List - A list refers to a data type that contains a collection of
items in an orderly manner
String - This is a series of characters, which is enclosed in
quotes. In Python, anything in quotes is regarded as a unique
character
Tuple – A tuple is similar to the list I explained earlier; however,
we use parentheses for tuple as an alternative to square brackets
used in a list. You can access each element after defining a tuple
by using each index
Variable - A variable is a storage location, which has a name
assigned to it. In Python, we can assign a value to a variable and
recall these variables
Before thinking of giving up, try one more. Take a step backward to retrace
where you got it wrong. If you are trying to write a program to achieve
using “for loop,” it won’t harm you to check through similar examples. Go
through your codes, perhaps you have omitted a colon, inserted a single
quote where there should be double. Review your work carefully.
If, after this, there is no solution, it is time to take a break. Maybe, you are
stressed and cannot stay focus when looking for the solution. When we
work for a long period, our brain gets tired, and we need to refresh or reboot
the brain. In this situation, take a nice shower, nap, or go have fun. Most
programmers take a long break because once they resume, they become
filled with enthusiasm to find what the problem was. Programming is
interesting and shouldn’t stress the hell out of your life.