SUMMER TRAINING REPORT
PROGRAMMING WITH PYTHON
Carried out with
Submitted by
Rupal Gandhi
41196302817
In partial fulfillment for the award of the degree
Of
BACHELOR OF TECHNOLOGY
In
ELECTRONICS AND COMMUNICATION ENGINEERING
MAHARAJA SURAJMAL INSTITUTE OF TECHNOLOGY,
NEW DELHI
C-4, Janak Puri, New Delhi-58
Affiliated to Guru Gobind Singh Indraprastha University, Delhi
summer t.pdf
ABSTRACT
This report presents basic information about python programming.
It includes info on the origin of python language / platform and its development, different data types and
their syntax and their implementation with different functions and commands. In this we have some
sample programs to teach and learn basic programming on python platform.
Similarities and advantages of python in comparison with C, C++ and java are given in this report.
i
ACKNOWLEDGMENT
To learn various technical and non-technical courses on the online platform. It helped me to complete
my summer training with ease and flexibility to learn. It is indeed a great pleasure for me to present
this Summer Training report on Python programming language given by Internshala Trainings. As a
part of the curriculum of the B.Tech course (Electronics and Communication Engineering) in MSIT
(Maharaja Surjmal Institute of Technology), Janakpuri, New Delhi.
I take this golden opportunity to thank.Mr Sarvesh Aggarwal, founder and CEO of Internshala and the
course provider. I express my sincere thanks to Mr. Sarvesh Aggarwal and content setup team for my
course.
There is no denying the fact that Internshala Trainings is a huge platform.
RUPAL GANDHI
(41196302817)
ii
summer t.pdf
TABLE OF CONTENTS
Title Page no.
Chapter 1: Introduction to Python. 1-8
What is Python? 1
Some facts related to Python programming 2
Detailed History 3
Why Python? 4
Installing Python 6
The Python shell 8
Install a text editor 8
Chapter 2: Hello World and the Basics of Python 9-13
Interactive Programming Mode 9
Script Programming Mode 9
Running the HelloWorld.py script file 9
Python Identifiers 10
Reserved Words 11
Lines and indentation 12
Comments in Python 12
Quotation in Python 13
Blank Lines 13
Chapter 3: Variables and Basic Operators in Python 14-23
Types of Variables in Python 14-16
• Declaring a variable 14
• Assigning a single value to multiple variables 15
• Assigning multiple variables multiple 15
Basic Operators 16-22
Operators Precedence in Python 23
Chapter 4: Working with Strings and Numbers 24-30
Strings in Python 24
iii
Creating a string 24
String escape sequence 25
String Methods 26
String formatting 26
Numbers in Python 27
Chapter 5: Lists and Tuples and Dictionary 31-37
Python Lists and Tuples 32
Python Dictionaries 35
Chapter 6: Input, Output, and Import 38-41
Capturing keyboard input using input() 39
Arguments of the print function 40
Python Import 40
Chapter 7: Decision Making and Looping 42-47
Decision making in Python 43
Loops in Python 45
Chapter 8: Functions and function arguments 48-49
Defining a function in Python 49
Calling a function 49
Function arguments 49
Chapter 9: File Operations 51-52
Opening a file 51
Project
iv
LIST OF FIGURES AND TABLES
Fig / Table Page no.
Fig.1-Python logo 1
Fig.2- The python.org/downloads/ download page 7
Table 1: Reserved keywords in Python 11
Table 2: Arithmetic operators in Python 18
Table 3: Assignment operators in Python 19
Table 4: Relational (comparison) operators in Python 20
Table 5: Logical operators in Python 20
Table 6: Membership operators in Python 21
Table 7: Identity operators in Python 21
Table 8: Bitwise operators in Python 22
Table 9: Operators precedence in Python 23
Table 10: String literal escape characters in Python. 25-26
Table 11: String methods in Python 26
Table 12: String formatting symbols 27
Table 13: Mathematical Functions 30
Table 14: List and tuple functions 33
Table 15: List methods in Python 33
Table16: Dictionary methods in Python. 36
Table 17: Dictionary functions in Python. 36
v
Chapter 1: Introduction to Python
Fig.1-Python logo
What is Python?
Python is an interpreted, high level, general-purpose programming language. Created by Guido van Rossum
and first released in 1991, Python's design philosophy emphasizes coded readability with its notable use of
significant whitespace. Its language constructs and object-oriented approach aim to help programmers write
clear, logical code for small and large- scale projects.
1
Some facts related to Python programming:
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms,
including procedural, object-oriented, and functional programing. Python is often described as a “batteries
included” language due to its comprehensive standard library.
Python was named after the Monty Python Flying Circus comedy group that was popular in the UK between
1969 and 1974.
Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0 released in 2000,
introduced features like list comprehensions and a garbage collection system capable of collecting reference
cycles. Python 3.0 released in 2008, was a major revision of the language that is not completely backward-
compatible, and much Python 2 code does not run unmodified on Python 3.
The Python 2 language i.e. Python 2.7.x, was officially discontinued on 1 January 2020 after which security
patches and other improvements will not be for it. With Python 2‟s end-of-life, only Python 3.5.x and later
are supported.
2
Detailed History
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica
(CWI) in the Netherlands as a successor to the ABC language, capable
of exception handling and interfacing with the Amoeba operating system. Its implementation began in
December 1989. Van Rossum shouldered sole responsibility for the project, as the lead developer, until
12 July 2018, when he announced his "permanent vacation" from his responsibilities as Python's
Benevolent Dictator for Life, a title the Python community bestowed upon him to reflect his long-term
commitment as the project's chief decision-maker. He now shares his leadership as a member of a five-
person steering council. In January 2019, active Python core developers elected Brett Cannon, Nick
Coghlan, Barry Warsaw, Carol Willing and Van Rossum to a five-member "Steering Council" to lead
the project.
Python 2.0 was released on 16 October 2000 with many major new features, including a cycle-
detecting garbage collector and support for Unicode.
Python 3.0 was released on 3 December 2008. It was a major revision of the language that is not
completely backward-compatible. Many of its major features were back ported to Python 2.6.x and 2.7.x
version series. Releases of Python 3 include the 2 to 3 utility, which automates (at least partially) the
translation of Python 2 code to Python 3.
Python 2.7's end-of-life date was initially set at 2015 then postponed to 2020 out of concern that a large body
of existing code could not easily be forward-ported to Python 3
3
Why Python?
If you did your research well before choosing to buy this eBook, you probably discovered that Python is
by far the most studied and the most widely used high level programming language today. This is not
just because it emphasizes on code readability and simple syntax, or because it requires fewer lines of
code to create a program compared to other languages; here are the top seven reasons why you should
see your decision to take on Python programming studies to the end:
1. Python opens up endless opportunities for programmers
Python developers are making a killing freelancing and taking up permanent jobs because the language
is very popular among companies and organizations. Once you get comfortable with coding sing Python,
you will be in a good position to consider job opportunities and even gigs that pay you to apply the
concepts you learn in this book.
2. Python is a preferred language for web development
The number of websites on the World Wide Web is approaching the 1 billion mark and one facet of this
evolution is the growing scope of Python in web development. Python brings a lot of flexibility and an
array of ready-to-use framework (such as django, Zope2, Pylons, Grok, and web.py) that are
revolutionizing how the front and back end of websites are built. Learning to create websites in Python
is the best way to position you on the right side of history.
3. Learning computational thinking with Python is easy
Python is a high-level programming language that reads like regular English. Because of this, many
English-speaking learners find it very easy to understand its syntax and how to use the various
components of the language with minimal complexity. If you are a beginner, you will be surprised how
easy it is to tell the computer what to do in Python and to think in ways that helps you conceptualize
computer code.
4
4. Python has a rich and vibrant online community
As you enter the world of programming, you will discover soon enough how important the developer
community is to the language and to its learners. The Python community is the 5th largest on Stack
Overflow community and the fourth most used language on Github. When you venture to the cyberspace
to interact with other learners and with professionals, you will be taken aback by the huge number of
people ready to help you learn by answering your questions and checking your code.
5. Python has one of the most mature package libraries
Most programming, as you will discover soon, is repetitive. When you start writing code on a commercial
scale, you will appreciate the fact that Python is backed by repositories such as PyPI with hundreds of
thousands of free modules and scripts that you can grab and use in your code. These modules and scripts
bring pre-packaged functionality to your Python environment to solve a myriad of problems that you
would otherwise have to deal with one-by-one. With Python, there is no need to re-invent the wheel.
6. Python is cross-platform and open source
Python has been around for over 20 years and throughout that period, it has been developed as a cross-
platform and open source software that runs on Linux, Windows, and MacOS. Besides, the language is
backed by over 2 decades of kink-straightening and bug-squashing which has turned it into a power
house that makes your code run like you intended it on whichever platform.
7. Learning Python is the ideal stepping stone to other languages
There aren‟t many languages today that offer the simplicity and versatility of Python, but different people
choose their languages of specialty for their own reasons. Even if you intend to specialize in some other
high-level programming language e.g. C#, C++, or Java, Python is a great language to learn first before
diversifying into another language.
5
Installing Python
In order to begin writing Python scripts and execute them on your computer, you must first set up the
right software on your computer. Nothing is complicated at this stage, just as long as you follow the
right steps. If you already know how your computer works, how to navigate around the computer
storage structure, download software and files, and install programs, this should be a straightforward
process.
If you already have Python 3 installed on your computer, you can skip this section and proceed at
the next section, The Python shell.
Download the right software you can download the official Python programming tools from
python.org. On your computer browser, go to http://www.python.org/download/and get the latest
version of Python (it should be version 3).
Before you can begin the installation, take some time to read the resources on
https://wiki.python.org/moin/BeginnersGuide and make sure that you know the operating system (and
version) of your computer and whether it is a 32-bit or a 64-bit. This is important to ensure that you
download the right software.
The python.org/downloads/ download page. At the time of writing this book, the newest version of
Python is Python 3.6.1. If you are unsure which version to download, click on the name of your
operating system to access more options.
Windows installation Installation is pretty straightforward on a Windows 10 or 7 computers. Simply
download the right version of Python and open the installation wizard when the download is complete.
When the installation is complete, make sure that you check the “Add Python 3.6 to PATH” option in
the last step of setup.If the installation went well, you can launch Python from the Windows Start
menu. The Python Integrated Development Environment (IDLE) shortcut is placed here: Start ➤
Programs ➤ Python2 ➤ IDLE
6
Fig.2- The python.org/downloads/ download page.
7
The Python shell
Python offers a graphical user interface programming environment (Python IDLE) whose shortcut
is placed on the desktop, start menu, or the app dock. This environment includes a text editor
where you can write your code. When you properly set up the Python Interpreter, you should be
able to run any python files with the extension .py in any location from the command line. This is
the approach we will use in this eBook. We believe it is best to learn using the terminal (command
line) and a text editor of your choosing because it helps you master concepts and even exercise
them with minimal distractions.
Install a text editor
Python code is entered in a plain text editor and saved in a file with the extension .py. There are
quite a number of text editors popular with programmers that you can download and use for
free. Word processor such as MS Word or WPS Writer does not work in creating scripts because
they introduce special characters in the code that interfere with its execution.
8
Chapter 2: Hello World and the Basics of Python
Python shares many similarities with other object-oriented programming languages especially
Perl, C, C++, and Java.
Interactive Programming Mode
On top of the list of similarities that Python shares with other top programming languages is the
Interactive Programming Mode. This simply means that you can invoke the Python interpreter without
passing a script file as a parameter.
One can execute commands on the Python interpreter without saving the syntax in a script file. The
Python interpreter can carry out arithmetic operations and other commands entered directly into the
terminal. Note, however, that in this mode, nothing will be saved permanently.
Script Programming Mode
The script programming mode is used to execute program instructions and commands. What this means
is that we will write the code in a script file (in this case a .py file) then save it and run it from the
interpreter.
Creating the HelloWorld.py script file. Start your text editor and enter the following code exactly as it
appears. Ex1: Hello World print ("Hello World!") print ('I am now a Python programmer!')
This is a simple Python script with two lines. You can save this script as
“HelloWorld.py” in your preferred location.
Running the HelloWorld.py script file
Now run the HelloWorld.py script from the command line (terminal) by following these steps: When
the python script file is saved, you can run it by invoking the Python interpreter in the location that the
file is stored. For instance, if you saved it in the folder „ExFiles‟ within the installation directory of
Python or the desktop, and you invoke the
9
Python 3 interpreter using the keyword python, your command to run the HelloWorld.py script
on the terminal (command line)
Python Identifiers
When writing a program in Python, you will get used to entering common English words you are
used to in everyday language, but with sometimes subtle noticeable differences and rules. When
specifying a variable, a class, a module, a function or some other object (all of which we will
learn later), you need to assign it an identifying name or simply an identifier.
Identifiers in Python must begin with an alphabetic letter (A-Z, a-z) or an underscore (_), followed
by other letters and digits (0-9) or underscores. You cannot use punctuation characters and other
symbols e.g. @, #, $, % and others within the identifier.
Also, because Python is case sensitive, uppercase and lowercase letters are different. For
instance, Hello is not the same as hello. Here are very vital conventions used to name identifiers
in Python that you should know:
A Class name must start with an uppercase letter. Every other identifier may start with a lowercase
letter.
An identifier that starts with a single leading underscore indicates that the identifier is
private e.g. _private.
An identifier that starts with two underscores is a strong private identifier.
If an identifier ends with two trailing underscores, then it is a language-defined special name
10
Reserved Words
Python has a set of English and non-English words reserved for the interpreter that you cannot
use as variable, constant, or any other identifier names. Here is a table of these words:
and As
asse
rt
brea
k
Clas
s
conti
nue Def
Del Elif else
exce
pt
Exe
c
Fina
lly For
Fro
m
Glo
bal if
Imp
ort In Is
Lam
bda
Not Or pass print
Rais
e
Whil
e
Retu
rn
Try
Wit
h
Yiel
d
Table 1: Reserved keywords in Python
11
Lines and indentation
In other programming languages, curly braces ({}) or square brackets ([]) are used to group blocks of
related code for function or class definition. In Python, blocks of code are denoted by a line indentation.
This indentation rule is rigidly enforced and you can use a tab or a number of spaces, just as long as there
is uniformity and consistency in their use. Consider these two blocks of code:If True: print ("True") print
("Proceed") else: print ("False")The statements print (“True”) and print (“Proceed”) are indented with the
same number of spaces. This means they form a block.
Comments in Python
Comments in a Python script are notes left by the programmer for later or for other programmers to
understand the code. Comments in Python have the # sign at the beginning. Anything beyond the # sign
to the end of the line will be ignored by the interpreter.print ("Hello World!") # Displays “Hello World!”
on the screen.# This line will also be ignored by the interpreter.print ('I am now a Python programmer.')
# This is another comment.A comment can be typed on a new line or on the same line after an expression
or a statement. You cannot write a comment that spans multiple lines on Python.
12
Quotation in Python
You can use a single ('), a double ("), or triple (''' or """) quotation marks to denote string literals in
Python. The only rule is that you must start and end with the same type of quotation on a string. Triple
quotations are used when the string of text spans over multiple lines. Print ('Hello World!') # Double
quotation marks. Print ("I am now a Python programmer.") # his line will also be ignored by the
interpreter. Print ("""I am now a Python programmer. This means I should be able to create a simple
Python Script and run it with no difficulty.''')
Blank Lines
A blank line is a line that contains only whitespace, commonly inserted into code for aesthetic purposes
and to keep the code organized. The Python interpreter completely ignores a blank line in the script.
There must be a blank line after a multi-line string block to terminate the statement.
13
Chapter 3: Variables and Basic Operators in Python
Types of Variables in Python
In object-oriented programming, a variable is a space in computer memory that is reserved for storing
values of a specified type. When you declare a variable in your Python script, you are essentially asking
the interpreter to allocate computer memory for the type of data expected and you assign that memory
location a name. This name is what we call a variable name and it may be assigned any of the following
five data types supported by Python:
1. Numbers
2. Strings
3. Lists
4. Tuples
5. Dictionary
The interpreter decides which data will be stored in the reserved memory based on the data type
declaration. It is therefore important to specify the type of data the variable will store so that the interpreter
can allocate sufficient memory space.
Declaring a variable you declare a variable in Python by assigning a variable name a value. Unlike
various other high level programming languages, with Python, you do not need to explicitly declare a
memory space reservation, it happens automatically when a value is assigned to the variable using the
equal sign (=) called the assignment operator in programming.
14
Ex2: Enter the following code in your editor and run it from the command line:
name = "Peter"
age = 22
score = 97.21
print (name, "is", age, "years old.") print (name, "scored", score, "percent.")
The print statement is to display the values of the variable as proof of the assignment.
In the statement name = “Peter”, the operand „name‟ on the left side of the equal sign is the
variable name while that on the right, in this case “Peter”, is the value of the variable.
Assigning a single value to multiple variables One of the things that make Python such an
efficient and simple languages is that you can assign several variables a single value in one
statement.
Ex3:
x = y = z = 10
print (x) print (y) print (z)
When you run the code in Ex3, you will realize when the values of variables x, y, and z are
displayed on the screen, are all the same (10). The integer objects x, y, and z are created in the same
memory location when the value 10 is assigned to them. This is how you associate one value with
multiple variables.
15
Assigning multiple variables multiple values Just the way you can assign multiple variables one
value using one statement in Python, you can also assign multiple objects to multiple variables
with ease.
Ex4:name, age, score = "Peter", 22, 97.21
print (age, "year old", name, "scored", score, "percent.")
16
Basic Operators
An operator is a construct that is used to manipulate the value of an operand. Most of the operators you
will encounter while learning Python will look familiar to you from math class, and most serve the same
purpose as it did when you were introduced to them in school.
In the expression 5 + 6, 5 and 6 are the operands and the + (plus) is the operator
The Python language supports seven types of operators:
• Arithmetic operators
• Assignment operators
• Relational or comparison operators
• Logical Operators
• Membership operators
• Identity operators
• Bitwise operators
17
Arithmetic operators
As the name hints, arithmetic operators are the same ones you learned in Math, albeit with a few changes.
They are:
18
operaOperation Name Function
+ Addition Adds the values of both operands
- Subtraction Subtracts the value of the right operand
from the value of the left operand.
* Multiplication Multiplies the values of both operands
/ Division
Divides the value of the left operand
by the
/ value of the right operand
% Modulus
Like division above, except that it
returns
the remainder value after division
// Floor Division
Like division above, except that it
returns
the quotient value without the decimal
point
digits
** Exponent Calculates the exponential calculation
(power) on the operands
Table 2: Arithmetic operators in Python
Assignment operators
Assignment operators in Python do just what the name suggests: assign values. An assignment
operator will assign the value of the right operand to the left operand.
symbol Name Function
= Equal
Assigns the value of the right operand to the left
operand.
+= Add AND
Adds the value of both operand and assigns the result
to the
left operand.
-=
Subtract
AND
Subtracts the value of the right operand from that of
the left
and assigns the result to the left operand
*=
Multiply
AND
Multiplies the value of both operands and assigns the
result
to the left operand.
/=
Divide
AND
Divides the value of the left operand with that of the
right
and assigns the result to the left operand.
%=
Modulus
AND
It takes modulus using the two operands and assigns
the
result to the left operand
**=
Exponent
AND
Finds the power (exponential) of the left operand by
the
right and assigns the result to the left operand.
//=
Floor
Division
Performs a floor division on the operands and assigns
the
AND result to the left operand
Table 3: Assignment operators in Python
19
3. Relational (comparison) operator
A comparison operator simply compares the value of the left operand with that of the right
operand and determines how they relate.
operaOperator Name Function
== Equal to Condition becomes True if the value of the left
operand is equal to the value of the right operand
!= Not equal to Condition becomes True if the value of the left
operand is not equal to the value of the right
operand.
> Greater than Condition becomes True if the value of the left
operand is greater than the value of the right
operand
< Less than Condition becomes True if the value of the left
operand is less than the value of the right
operand.
>=
Equal to or
greater than Condition becomes True if the value of the left
operand is equal to or greater than the value of
the right operand.
<=
Equal to or
less than Condition becomes True if the value of the left
operand is equal to or less than the value of the
right operand
Table 4: Relational (comparison) operators in Python.
Logical operators
Also called Boolean operators, logical operators are statements that evaluate to either of the two
Boolean conditions: True or False. The not keyword introduced as a reserved keyword earlier
reverses a Boolean type, True to False and vice versa
Operator Function
and Returns True if both operands are True
or Returns True if either of the operands are true
Not Returns True if operand False and False if it is True.
Table 5: Logical operators in Python
20
Membership operators
The two membership operators in Python check for the operand‟s presence in a sequence of values
such as strings (alphanumeric characters), lists, or tuples.
Operator Function
In
Returns True if the operand is found in the specified
sequence
and False if it is not found.
not in Returns True if the operand is not found in the specified
sequence and False if it is found.
Table 6: Membership operators in Python
Identity Operators
An identity operator compares the memory locations of two objects. There are two identical
operators:
Operator Function
Is
Returns True if both operands point to the same
object
and False if they do not.
is not
Returns False if both operands point to the same
object
and False if they do not.
Table 7: Identity operators in Python
21
Bitwise operators
Bitwise operators are used bit-by-bit operators that execute operations on operands in binary
form.
Symbol
Oper
ator Function
&
AN
D Copies a bit if found in both operands
| OR Copies a bit if found in either of the operands.
~
NO
T
Complements an operand by flipping ones for zeros
and
zeros for ones
^
XO
R Copies a bit if set in only one operand
>>
Shift
right The value of the left operand is moved right by the
bits in the left operand.
<<
Shift
left
The value of the left operand is moved left by the
number
of bits in the right operand
Table 8: Bitwise operators in Python
22
Operators Precedence in Python
The Python interpreter follows a very strict order of execution when presented with multiple operations.
The table below summarizes all the operations in order of precedence from the highest to the lowest
Order Operation Function
1 () Operations enclosed in brackets are executed first.
2 ** Exponentiation (raise to the power)
3 ~ + - Complement, unary plus (+@) and minus (-@)
4 * % / Multiply, divide, modulus and floor division
5 + - Addition and subtraction
6 >> << Bitwise shift right and left
7 & Bitwise AND
8 | ^ Bitwise AND
9 <=<>>= Comparison operators
10 <> == != Relational operators
11 =%==/=- Assignment operators
=+=*=
**=
12 is is not Identity operators
13 in not in Membership operators
14 not or and Logical operators
Table 9: Operators precedence in Python
23
Chapter 4: Working with Strings and Numbers
In Chapter 2, we touched lightly on the five basic data types that you will be learning to work with in the
course.By the end of this chapter, you will be able to work with the two most popular data types:
Strings in Python
The first data type we encountered in the first exercise of this book. It is a sequence of characters including
symbols and alphanumeric characters. In chapter 2, you learned that you can use a single ('), a double ("),
or triple (''' or """) quotation marks to denote a string.
If you have been practicing what you have learned so far, I am sure you have created countless string
variables in your scripts. However, so far we have only touched on how to display them using the method
print. In this section, we will look at a number of other great things you can do with strings.
Creating a string
You create a string by enclosing characters in quotation marks and assigning it a variable name. In the first
exercise, we created a string object and displayed its contents on the screen. In Ex2, we created one string
object called name with value “Peter”.
You can also create a string object by formatting a user‟s input using the method str() (we will cover this
later). In Ex11 below, for instance, the user will be prompted to enter a string of text which is assigned the
variable name.
Accessing the values of a string In Python, you can access the individual characters of a string using slicing,
indexing, and a range of other operations. If you try to access a character that is out of index range, you will get
an IndexError. The indexes of the characters start at 0 for the first character and you can only use positive
integers. If you try to use any other number type such as a decimal (float) you will encounter a Type Error.
24
String concatenation and iteration You can join two or more strings to make them one using the plus
operator (+) or separating named string variables with a comma
You can repeat multiple copies of one string to create new strings using the asterisk operator *
String escape sequence
You can now work with almost any type of text, after all, you just need to enclose them in quotation marks
and split, slice, iterate etc. But what do you do when you want to work with a string that has quotation
marks. For instance, how would you print a text that reads: “I am sorry,” he said, “the „Transformers‟ toys
are out of stock”.Notice that this sentence has both double and single quotation marks that create a string.
If you slap quotation marks on this string and try to print it, you will encounter a Syntax error. Try it.
In such a case, we can either use triple quotation marks or escape sequences to get around this problem.
An escape sequence begins with a backslash (). You will place the backslash in front of all double quotes
inside a string if the string is created with double quotation marks. You will do the same for single quotation
marks if the string is created with single quotation marks.
There are quite a few of other escape sequences that you will encounter as you practice working with
strings. Here is a tabulated list of the most popular escape sequences you will encounter and what they
do.
25
Character Sequence Description
 Backslash Prints one backlash.
” Double Prints a double quote.
quote
‟ Single Prints a single quote.
quote
a Bell Sounds the system bell.
b
Backs
pace Moves the cursor back one space
t Tab Moves the cursor forward one tab.
n
Newli
ne
Moves the cursor to the beginning of the next
line
Table 10: String literal escape characters in Python.
String Methods
There are quite a number of methods you can use to manipulate strings in Python. Some of the most
popular are included in the table below:
Metho
d Description
upper(
) Returns the uppercase characters of a string.
lower(
) Returns the lowercase version of a string
swapc
ase()
Like toggle case in word processing, it returns a new string with the
case of
each character in a string switched
capital
ize() Capitalizes the first letter of string.
title()
Returns a string with the first character of each word capitalized and
the
rest lowercase.
trip()
Returns a string with all white spaces including spaces, newlines, and
tabs
at the beginning and the end removed.
split() Splits all words into a list
join() Joins all words into a string.
Table 11: String methods in Python
26
String formatting
In Python, you can format a string by placing the string formatting operator (%) to the left of the
conversion specifier, and the values to the right. You can use this formatting operator on a string
containing different data types including tuples, lists, and dictionaries.
27
Ex
name = "Peter"
score = 75
print ("My name is %s and I scored %d percent!" %(name, score))
In this example, we use the placeholders %s and %d to format the strings using placeholders
%s for string and %d for decimal integer. The table below presents the format symbols you
will use on different data types.
Format Conversion
symbol
%c Character
%s string (converted using str() before formatting)
%i or
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase characters)
%X hexadecimal integer (UPPERcase characters)
%e exponential notation (lowercase 'e')
%E exponential notation (UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Table 12: String formatting symbols
Numbers in Python
After strings, numbers are the next most popular value types in Python. Python supports three types
of numbers: integers, floating point numbers, and complex numbers defined as int, float, and
complex respectively. Just like strings, number data types are immutable.
An integer is a whole number without a decimal point while a floating point number has a decimal.
For instance, 2 is an integer while 2.0 is a floating point number. In Python, integers can be of any
length and floats are accurate up to 15 places.
Complex numbers are in the form x + yj where x is the real part of the number and y is the
imaginary part. Complex numbers is beyond the scope of this book so we will cover only integers
and floats.
We deal with decimal (base 10) numbers in our everyday lives. However, as you become a
proficient programmer, you will need to know how to program systems using only binary (base 2),
octal (base 8), and hexadecimal (base16) num
Using mathematical operators on numbers With Python, you can carry out almost any
calculation with numbers without adding any extra code. For instance, on IDLE or the Terminal,
you can enter mathematical operations directly and the interpreter will return the result
Ex
my_math = 10 * -5
print (my_math) print ("10 + 12 * 3 = ", 10 + 12 * 3) print ("15 + 8 = ", 15 + 8)
print ("15 + 8.0 = ", 15 + 8.0) print ("217 %5 = ", 217 %5)
A number variable is created by assigning a number a name using the equal sign (=). In the
above example, we created a variable called my_math with the value 10*-5.
Number coercion The process of converting from one type of number to another is called
coercion. You already discovered that operations such as addition, subtraction,
29
division, multiplication, and others implicitly coerce an integer to a float if one of the operands is a
float.
You can also use the built-in functions int(), float(), and complex() to explicitly coerce between
number types and from strings.
Ex
number1 = 12
number2 = 2.5
string1 = "10"
print (float(number1)) #convert number1 to float and print print (int(number2)) #Convert number2 to
integer and print print (int(string1) * number2) YoB = int(input("Enter your year of birth as YYYY: "))
age = 2017 – YoB
print ("You are %d years old!" %age)
In Ex, the variable number1 is an integer, number2 is a float, and string1 is a string. The 5th line of the
script converts number1 to the type float, the next converts number2 to an integer, and the 7th line
converts string1 into an integer before multiplying by number2. Note that when converting a number
from a float to an integer, it gets truncated at the decimal point, not truncated.
In the same example, notice that we created the variable YoB by asking the user to “Enter your year of birth
as YYYY: ” then converting it to an integer before working with it.
Mathematical Functions There are many inbuilt Python functions that perform mathematical
operations on numbers. To use mathematical functions in the standard module, you will have to
import the math module using import math.
Some of the most common you should know about are tabulated in Table 13:
30
Function Description
fabs(x) Returns the absolute value of x (positive distance between 0 and x)
ceil(x) Returns the ceiling value of x (the smallest integer that is not less than x)
floor(x) Returns the floor value of x (largest integer that is not greater than x)
cmp(x, y) Compares x and y and returns 1 (if x > y), 0 if x == y, or -1 if x < y
exp(x) Returns the exponential of x (ex)
Pow(x,y) Returns the value of x**y
min(x,y) Returns the smallest of the numbers x and y
max(x,y) Returns the largest of the numbers x and y
sqrt(x) Returns the square root of x when x > 0
pi Mathematical constant pi
e Mathematical constant e
Table 13: Mathematical Functions
31
Chapter 5: Lists and Tuples and Dictionary
Lists and tuples are popular compound data types that generally fall into the sequences category
alongside strings, byte sequences, byte arrays, and range objects (you will learn about these at
intermediate and advanced stages). Strings may look a lot different from lists and tuples as you will
notice, but they are similar in that:
• Their elements are placed in a defined sequence.
• The elements can be accessed via indices
• They can be manipulated via slicing using []
Python, unlike other object-oriented programming languages, uses the same syntax and function names
to manipulate list and tuple sequential data types. These operations include indexing, slicing, iteration,
concatenation, and checking for membership. We will cover each of these in greater detail in this
section.
32
Python Lists and Tuples
A list in Python is a mutable type that is made up of a collection of ordered objects. The objects
contained in a list do not have to be of the same type and may include other lists (nested sublists).
A tuple, on the other hand, unlike a list, is an immutable type. This means that the objects (items) in a
tuple cannot be changed once created. Just like a list, the objects in a tuple can be of different types.
Creating a list and tuple A list is created by placing all the objects (or items) inside a square bracket
[] and separated by commas. A tuple is created by separating its values with a comma only but it is
a good practice to enclose them in parentheses (brackets).
You can also create a list by splitting the elements of a string. You can also create a list by splitting
the elements of a string
Accessing values in lists and tuples you access the values of lists and tuples (separated by commas)
the same way we did the characters of a string: using indices and slicing with square brackets
Updating list objects because lists in Python are a mutable type, you can update a single or multiple
elements using the assignment operator (=). You can also add new items on the list using the append()
method
Tuples are immutable and cannot be updated. However, you can take the values of a tuple and create a
new tuple by adding new items or combining with an existing tuple.
Deleting list objects there are two ways to delete items from a list in Python. If you know the exact
items to delete, you can use the del statement but if you don‟t know you can use the remove() method.
Basic list and tuple operations Much like strings, lists and tuples respond to the concatenation
(+) and iteration (*) operations.
33
Python comes with a range of in-built functions that you can use to manipulate lists and tuples.
Some of them are:
Function Description
cmp() Compares the objects of two lists or tuples.
len() Returns the total length of a sequence
max() Returns the item with the highest value in a sequence
min() Returns the item with the lowest value in a sequence
list(seq) Converts from a tuple type to a list.
tuple(seq) Converts from a list type to a tuple.
Table 14: List and tuple functions
Python list methods: Here is a table of list methods in Python and what they do.
Method Definition
append() Adds an item to the end of the list
remove() Removes an item from the list
extend() Adds all elements of a list to another list
insert() Inserts an item at the defined index
copy() Returns a shallow copy of a list
pop() Removes an item at the given index and returns it
index() Returns the index of the first matched item
clear() Removes all items on a list
count() Returns the number of items passed as an argument
reverse() Reverses the order of items in a list
sort() Sorts items in a list in ascending order
Table 15: List methods in Python
34
Advantages of tuples over lists: We have established that lists and tuples are similar in many ways,
and they can be used interchangeably in many situations. Considering that lists are mutable while tuples
are not, most beginners often wonder under what situations a tuple is more applicable compared to a
list. There are four:
1. When working with heterogeneous (different) types of data, it is better to use a tuple. A list is
more practical when sequencing data of the same type.
2. Where the sequence will be iterated, it is more advantageous to use a tuple because it is
immutable and will be iterated faster by the interpreter.
3. A tuple can be used as a dictionary key because its data is immutable. A list cannot be used as
a dictionary key.
4. When you have data that does not change, the best way to make sure that it does not change is to
implement it as a tuple.
35
Python Dictionaries
It would be impractical to write a functional computer program in Python without using the sequential
data types we have covered so far (strings, lists, and tuples) and dictionaries.
Like lists, dictionaries are a mutable data type whose objects can easily be deleted, updated, and added
at runtime and they can also contain different types of data (including lists). The difference between the
two is that dictionaries contain items not in any order, unlike lists whose items are ordered. This means
that the items on a dictionary are accessed using keys and not their positions.
We can therefore say that a dictionary in python is an associative array or hash in which each value is
mapped to (associated with) a key.
Creating a dictionary A dictionary in Python is created by pairing values with keys using a colon in
the format (key:value). The key:value pairs of items are separated by commas and are enclosed in curly
braces ({}). A dictionary can also be created or converted from another data type using the built in
function dict().
Accessing dictionary elements As mentioned earlier, while indexing is used to access the values of
sequential data types, keys are used to access the values of a dictionary. You can use just the key inside a square
bracket but it is recommended that you make it a habit to use the get() method.
Using get() has the advantage of returning a None value when a key is missing and not a KeyError
you would encounter using the keys in square brackets. Updating the dictionary Because the
dictionary is a mutable type, you can add new items, delete existing ones, or update keys and values
using the assignment operator (=).
Dictionary methods Here is a table of the methods available with the dictionary type in Python
alongside their definitions. Be sure to try out each of them to see that it does what is described.
36
Method Description
dict.clear() Removes all items form the dictionary.
dict.copy() Returns a shallow copy of the dictionary.
dict.items() Returns a new key:value view of the items in the dictionary.
dict.keys() Returns a new view of the dictionary's keys.
dict.pop(key[,d]) Removes the item with key and return its value or d if key is
not found
dict.popitem() Removes and returns an arbitary key:value item).
dict.update() Updates the dictionary with the key:value pairs, overwriting
existing keys
dict.values() Returns a new view of the dictionary's values
Table16: Dictionary methods in Python.
Dictionary functions Python comes with a number of built-in dictionary functions that you
can practice with to gain a deeper understanding what they do. They are:
Function Description
all() Returns True if all dictionary keys are true or if the dictionary is empty.
any() Returns True if any key of the dictionary is true and False if the dictionary
is empty.
len() Returns the length of the dictionary (the number of items).
cmp() Compares the items of two dictionaries.
sorted() Returns a new sorted list of keys in the dictionary.
type(var) Returns dictionary type if passed variable is of type dictionary.
str() Produces a printable string of the dictionary items
Table 17: Dictionary functions in Python.
37
Properties of dictionary keys in Python Dictionary values can be arbitrary objects - standard or
user-defined - there are no restrictions. However, there are two vital considerations to bear in mind
about dictionary keys:
1. You cannot have two or more similar keys. Keys must be unique. When there are more than one
similar keys, the last to be assigned is the only valid one.
2. Dictionary keys must be immutable. You can use numbers, strings, or tuples as keys but you
cannot use something like [„key‟].
38
Chapter 6: Input, Output, and Import
Python comes with numerous built-in functions readily available at the Python prompt to enable you
write programs that accept user input and can output processed information.
39
Capturing keyboard input using input()
The input() function reads data from the keyboard as a string, no matter whether it is enclosed in quotes
(“” or „‟). You can convert the captured text into a specified data type using a casting function (see
Example18 script) or using the eval function.
When the input() function is called, the interpreter will stop the program flow until the user provides
an input and ends it by pressing the return key. The function offers an optional [prompt] parameter of
text to print on the screen input([prompt])
The prompt text will be displayed to the left of the line where the user will need to enter keyboard
characters. It is a good habit to end the prompt text with a colon and a space (: ) to properly format the
input area for the end user
There is more you can do with input() besides capturing a single string of text. For instance, you can
capture a sequence of data and save it as a list.
40
Printing to the screen using the print() function
we have used the print() statement to display text on the computer screen. In principle, for any computer
program to be useful, it must be able to communicate with the user by displaying requested information
on the screen. In Python 3, we use the print() function to convert expressions separated by commas into
a string and display the result to the standard console output.
Arguments of the print function
The print function takes the following arguments:
print(value1, value2.., sep='', end='')
You can print an arbitrary number of values separated by commas as you can see in almost all the
examples so far. The separator (sep) argument defines what separates the printed values and the end
argument defines what characters or symbols are placed at the end of the string to print. Other arguments
you will discover in the advanced stages of learning to write code in Python are file and flush.
Python Import
So far, the program examples we have been creating have been very small, only a few lines long. As you
create longer scripts and bigger programs, you will find it necessary to break it into modules.
A module is a python file containing statements and definitions. Every Python module has a filename
and ends with the .py extension, just like the scripts you have been creating so far. There are countless
modules distributed with the standard Python installation package or created by individuals and
downloadable from the internet.
To import a module in Python, you use the keyword import.
41
We use the value of pi to calculate the area and circumference of a circle whose radius the user is
prompted to enter and converted to a float number.
When we import a module, all the definitions it contains are available in the program’s scope. As you
practice using import, you will discover that you can also import specific attributes or functions using
keywords. For instance, in our above example, we could have just imported the value of pi using the
statement:
import math pi
You can also write the import statement like this:
from math import pi.
42
Chapter 7: Decision Making and Looping
When writing a program, you will have to include decision making structures in anticipation of
conditions that will occur during the execution of the program. In this chapter, you will learn how to use
the if statement to write a program that makes decisions and how to create a program that iterate
particular block of code until or when a condition is met
43
Decision making in Python
Decision making structures evaluate one or multiple expressions that can return True or False
outcomes then use the response to determine which action to take or block of code to execute when
the outcome is True or False
The following types of decision making statements are available in Python:
1. If
2. if...else
3. if...elif...else
4. Nested if
The if statement The if statement tests a condition such as if two variables are equal, then executes a
block of code if the result is True. The most basic syntax of this statement is:
if : statement(s)
Take note of the trailing colon (:) after the test condition and the indentation of the next line of
statement(s).
The statement(s) in this case is an indented block that may be made up of one or more statements. The
indentation is very important in Python because this is how the interpreter determines which lines of
code belong to what block. Make it a habit to indent your lines of code to one level using a Tab or four
spaces.
The if statement tests the Boolean expression which will return either a True or False. If the condition
is True, the statement(s) are executed and if it is False, the interpreter will ignore the indented
statements and continue with the program execution at the first line after the indented block of
statement(s).
The if...else statement The if statement has one downside: that there is only one block of code to
execute when the test condition evaluates to True.
44
Here is the Python syntax for this decision making structure:
if : statement(s) else: statement(s)
If the test condition returns True, the first block of statements is executed, and if the test condition returns
False, the block of statements under the else: statement are executed.
The if...elif statement t The if...elif statement is a complex construct of the if...else conditional statement,
elif being a shorthand for else if. With the if...elif statement, there are more than one conditions to test
and at the end of the tests is an optional else: statement. Beneath else:, just like with the previous if...else
statement, is a block of code to execute if all the previous conditions return False.
The syntax for the if...elif decision making structure looks like this:
if : statement(s) elif: statement(s)
Nested If statements When you begin creating even more complex programs in Python, you may find
it necessary to place any of the three if decision making structures inside another if structure to form a
structure of nested if statements.
Because nesting if statements can form a complex, even confusing structure, you will need to pay close
attention to indentation to differentiate the levels of each if statement. The syntax of this type of conditional
statement would take a structure like this:
if : statement(s) if : statement(s) elif statement(s) else: statement(s) elif : statement(s)
else: statement(s)
45
Loops in Python
Loops or loop statements are used to iterate one or more statements multiple times. Python offers
three mechanisms for repeatedly executing one or more blocks of code either for a defined number
of times or continuously until a defined condition is met.
The three types of loops we will cover in this section are: the for loop, the while loop, and the nested
loop.
The for loop The for loop is the most popular loop structure in Python used to iterate over a sequence
such as a list, string, tuple, or range (this is discussed further at the end of the chapter). The for loop
takes the following general form:
for var_name in sequence: statement
In the syntax above, var_name is the variable that assumes the value of the item inside the sequence in
every round of iteration. The loop will continue until the last item in the sequence is reached.
The while loop The while loop is used to iterate over a block of code as long as a test condition
returns True. The while loop is used when you do not know the number of times to iterate in advance.
The syntax of the while loop takes this form:
while : statements
With the while loop, the test condition is checked first and the body executed only if the test condition
evaluates to True. This type of loop checks the test condition after each cycle of iteration until the test
condition evaluates to False.
Nested loop Just the way we put an if statement inside another to create a nested if structure, we can also
put a loop a while or for loop inside another loop. The rules and structure for a nested loop in Python is
pretty much the same as the rules of nested if.
An important note about nesting loops is that you can put any type of loop inside any other type of loop.
This means a for loop can fit inside another for loop or while loop and vice versa. The syntax of a basic
nested loop would look like any of these:
46
for var in sequence: for var in sequence statements statement
for var in sequence: while : statements
while : for var in sequence: statements
while : While : statements
Loop control statements In the previous section, we learned that loops iterate over a block of code until
a certain condition is met, or until the test condition returns False. However, sometimes, you may wish
your program to terminate an ongoing iteration or an entire loop without necessarily checking the test
condition. In such a case, you use a loop control statement.
Loop control statements are used to alter the normal flow of a looped block of code.
Python supports three control statements: break, continue, and pass.
The break statement The break statement terminates the loop it is contained in and transfers the flow
of execution to the statement immediately following the body of the loop. If the break statement is
contained inside a nested loop, its use will cause the innermost loop to terminate. The syntax for the
break statement is simply break.
The continue statement Unlike break, the continue statement does not terminate the loop and instead
breaks the current loop and skips the remaining loop statements. It then moves control back to the
beginning of the loop to retest the condition and resume iteration. The syntax for this loop control is
continue.
The pass statement In Python, the pass statement is a null statement such that nothing happens when it
is executed (a state called NOP or no operation). It is used as a placeholder where a statement is required
syntactically but there is no code or command to execute.
Pass is used as a placeholder for a future function or loop that has not been implemented yet. Note,
however, that unlike a comment that is completely ignored, the pass statement is not ignored by the
interpreter.
47
Using else: with loops in Python The else statement that we used in decision making structure if can
also be optionally used with both the for and while loops. Just like with the if statement, loops can
have the else: block that is executed when test conditions return a False.
The syntax for the for and while loop with else: would look like these:
for var_name in sequence: statement else: statement
while<condition> : statement else: statement
The range command In the examples we used in this chapter, we ask the interpreter to loop over a
specified range of integers or characters. The range command is used with the for loop to iterate the
loop a fixed number of times. There are three ways to use the range command: range(i): This generates
a sequence of integers that begin at 0 and end at i-1 (not i), increasing by 1 with each iteration.
range(i, j): This command generates a sequence of integers starting at i and ending at i-j, increasing by
1 with each iteration.
range(i,j,k): This range command generates a sequence of integers that start at i and end at j-1,
increasing by k with each iteration.
48
Chapter 8: Functions and function arguments
When you create a block of code that carries out a specific calculation or an action, a useful way to
refer to it is a function. In Python, you will be able to call one instance of code many times and reuse
it to avoid having to write similar code over and over in one or more programs you create.
A function takes some input, referred to as input parameters or arguments, and do something with it. It
may or may not return a result (value) depending on what you wrote it for. Consider it a way to break
down a complex program into modular or smaller chunks for better organization and manageability.
Predefined functions such as sqrt() and cos() are good examples of in-built functions that come with
Python. You can also define your own functions
49
Defining a function in Python
A function is defined using the keyword def and assigning it a name. Its syntax takes the following
format:
def function_name(arguments): """docstring""" statement(s)
The keyword def marks the beginning of the function header followed by the function name, a unique
identifier that must follow the standard rules of writing identifiers in Python. The arguments section in
parentheses is where the optional values or parameters are passed to the function . Note that the end of the
function header is marked by a colon (:). The optional documentation string (docstring) describes what
the function does. The statements that make up the body of the function are entered below the docstring
and must be indented at the same level, typically one tab or four spaces. The return statement at the
very end of the function exits the function back to the last position from where it was called. Note that
return may contain an expression or expressions that get evaluated and a value returned.
Calling a function
Once you define a function, you can call it from the Python prompt, program, or another function by
simply typing its name with appropriate parameters
Function arguments
If the function is run without the argument it expects, the interpreter will return an error. The same
will happen if you provide two arguments when the function needs only one.Python offers multiple
options for passing arguments of functions including
1. Positional arguments
2. Optional or defaulted arguments
3. Keyword arguments
4. Arbitrary number of arguments
5. . Arbitrary number of keyword arguments
50
Chapter 9: File Operations
You have learned a lot so far, but all the examples we have been using either have static data (the data
types that we typed into the script for demonstration) or can take temporary user input that is lost when
we exit the shell. Practical programming involves working with files to read and store permanent data
for the program scripts. This is what you will be introduced to in this chapter.
A computer file can be defined as a named storage location on a volatile memory device, such as the
hard disk, where data is recorded to be accessed and/or modified later. File operations or file handling
in Python is a three-step process that includes:
1. Open a file object.
2. Using the file object to read and write data.
3. Closing the file object.
51
Opening a file
A file must be opened before it can be read or written into. Python comes with the inbuilt open()
function that returns the file object or handle that is used to read and write the file. The syntax for
opening a file is:
file object = open(file_name, [access_mode], [buffering], [encoding])
File object: Using the open() function creates a file object that is used to call other associated
methods.
file_name: This is a string argument that contains the name of the file you want to open.
access_mode: Access mode is an optional parameter that determines how the file will be accessed or
manipulated.
[buffering]: If a value of 1 is set, the interpreter will buffer lines while accessing the file. If the value
is greater than 1, buffering will depend on the buffer size. When the value is set to 0 or a negative
number, the default action which is no buffering will run.
[encoding]: This option is included in this list but it only applies to text files. Different operating systems
use different encoding standards for text files. For instance, Linux uses “utf-8” while Windows uses
“cp1252”. It is a good programming practice to specify the type of encoding when manipulating text
files.
52
PROJECT
MUSIC PLAYER APPLICATION USING TKINDER
MUSIC PLAYER Libraries used for Music Player Application:
1. Tkinter
We had already told you in the title of this page that we are going to use the Tkinter library, which is a
standard library for GUI creation. The Tkinter library is most popular and very easy to use and it
comes with many widgets (these widgets helps in the creation of nice-looking GUI Applications).
Also, Tkinter is a very light-weight module and it is helpful in creating cross-platform applications(so
the same code can easily work on Windows, macOS, and Linux)
2. Pygame module
Pygame is a Python module that works with computer graphics and sound libraries and designed with
the power of playing with different multimedia formats like audio, video, etc. While creating our
Music Player application, we will be using Pygame's mixer.music module for providing different
functionality to our music player application that is usually related to the manipulation of the song
tracks.
3. OS module
There is no need to install this module explicitly, as it comes with the standard library of Python. This
module provides different functions for interaction with the Operating System. In this tutorial, we are
going to use the OS module for fetching the playlist of songs from the specified directory and make
it available to the music player application.
MusicPlayer Class
Here we have the constructor and the other functions defined in the MusicPlayer class.
1. _init_ Constructor
With the help of this constructor, we will set the title for the window and geometry for the window.
We will initiate pygame and pygame mixer and then declare track variable and status variable.
• We will then Create the Track Frames for Song label & status label and then after Insert the
Song Track Label and Status Label.
53
• After that, we will create the Button Frame and insert play, pause, unpause, and stop
buttons into it.
• Then we will create the playlist frame and add the scrollbar to it and we will add songs into
playlist.
def __init__(self,root):
self.root = root
# Title of the window
self.root.title("MusicPlayer")
# Window Geometry
self.root.geometry("1000x200+200+200")
# Initiating Pygame
pygame.init()
# Initiating Pygame Mixer
pygame.mixer.init()
# Declaring track Variable
self.track = StringVar()
# Declaring Status Variable
self.status = StringVar()
# Creating the Track Frames for Song label & status label
trackframe = LabelFrame(self.root,text="Song Track",font=("times new
roman",15,"bold"),bg="Navyblue",fg="white",bd=5,relief=GROOVE)
trackframe.place(x=0,y=0,width=600,height=100)
# Inserting Song Track Label
songtrack = Label(trackframe,textvariable=self.track,width=20,font=("times new
roman",24,"bold"),bg="Orange",fg="gold").grid(row=0,column=0,padx=10,pady=5)
# Inserting Status Label
trackstatus = Label(trackframe,textvariable=self.status,font=("times new
roman",24,"bold"),bg="orange",fg="gold").grid(row=0,column=1,padx=10,pady=5)
54
# Creating Button Frame
buttonframe = LabelFrame(self.root,text="Control Panel",font=("times new
roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
buttonframe.place(x=0,y=100,width=600,height=100)
# Inserting Play Button
playbtn =
Button(buttonframe,text="PLAYSONG",command=self.playsong,width=10,height=1,font=("ti
mes new
roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=0,padx=10,pady=5)
# Inserting Pause Button
playbtn =
Button(buttonframe,text="PAUSE",command=self.pausesong,width=8,height=1,font=("times
new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=1,padx=10,pady=5)
# Inserting Unpause Button
playbtn =
Button(buttonframe,text="UNPAUSE",command=self.unpausesong,width=10,height=1,font=(
"times new
roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=2,padx=10,pady=5)
# Inserting Stop Button
playbtn =
Button(buttonframe,text="STOPSONG",command=self.stopsong,width=10,height=1,font=("ti
mes new
roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=3,padx=10,pady=5)
# Creating Playlist Frame
songsframe = LabelFrame(self.root,text="Song Playlist",font=("times new
roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE)
songsframe.place(x=600,y=0,width=400,height=200)
# Inserting scrollbar
scrol_y = Scrollbar(songsframe,orient=VERTICAL)
# Inserting Playlist listbox
55
self.playlist =
Listbox(songsframe,yscrollcommand=scrol_y.set,selectbackground="gold",selectmode=SING
LE,font=("times new roman",12,"bold"),bg="silver",fg="navyblue",bd=5,relief=GROOVE)
# Applying Scrollbar to listbox
scrol_y.pack(side=RIGHT,fill=Y)
scrol_y.config(command=self.playlist.yview)
self.playlist.pack(fill=BOTH)
# Changing Directory for fetching Songs
os.chdir("PATH/OF/DIRECTORY")
# Fetching Songs
songtracks = os.listdir()
# Inserting Songs into Playlist
for track in songtracks:
self.playlist.insert(END,track)
2. The playsong() Function
3. The stopsong() Function
4. The pausesong() Function
5. The unpausesong() Function
6. Root Window Looping
56
57
CONCLUSION
Python is currently the most popular programming language and millions of newbies and programmers
proficient in other languages are taking the time to learn it. Being a general purpose program, Python is
used almost everywhere today -- from front-end game development and back-end web server systems to
automotive autonomous systems and home appliances and everything in between. Having Python coding
experience under your belt certainly advances your marketability and value in the modern world.
58
REFERENCES
• https://trainings.internshala.com
• google.com
• https://www.learnpython.org
summer t.pdf

More Related Content

PDF
Mastering the Interview: 50 Common Interview Questions Demystified
PDF
Introduction-To-Python- a guide to master
PPTX
Chapter - 1.pptx
PDF
Python Programming Part 1.pdf
PDF
Python Programming Part 1.pdf
PDF
Introduction To Python For Beginners
PPTX
Introduction to Python.pptx
PDF
Introduction to Python
Mastering the Interview: 50 Common Interview Questions Demystified
Introduction-To-Python- a guide to master
Chapter - 1.pptx
Python Programming Part 1.pdf
Python Programming Part 1.pdf
Introduction To Python For Beginners
Introduction to Python.pptx
Introduction to Python

Similar to summer t.pdf (20)

PPTX
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
PDF
COMPUTER 8 Grade 8 - Intro to Python.pdf
PPTX
Chapter 2: Basics of programming pyton programming
PDF
introduction of python in data science
PDF
Python programming for beginners
PDF
python-handbook.pdf
PDF
PPTX
What is Python Programming for Beginners
PPTX
python programming unit 1 wala ppt .pptx
PPTX
Introduction to python
PPTX
cupdf.com_python-seminar-ppt.pptx.........
PPTX
Introduction to Python Programming Basics
PDF
IRJET- Python: Simple though an Important Programming Language
PPTX
Python basics
PPTX
Python Seminar PPT
PPTX
Python
PPTX
Python Class 1
PPT
1-ppt-python.ppt
PDF
python-160403194316.pdf
PPTX
Introduction to Python – Learn Python Programming.pptx
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
COMPUTER 8 Grade 8 - Intro to Python.pdf
Chapter 2: Basics of programming pyton programming
introduction of python in data science
Python programming for beginners
python-handbook.pdf
What is Python Programming for Beginners
python programming unit 1 wala ppt .pptx
Introduction to python
cupdf.com_python-seminar-ppt.pptx.........
Introduction to Python Programming Basics
IRJET- Python: Simple though an Important Programming Language
Python basics
Python Seminar PPT
Python
Python Class 1
1-ppt-python.ppt
python-160403194316.pdf
Introduction to Python – Learn Python Programming.pptx
Ad

Recently uploaded (20)

PPTX
Module 8- Technological and Communication Skills.pptx
PPTX
Chemical Technological Processes, Feasibility Study and Chemical Process Indu...
PPTX
PRASUNET_20240614003_231416_0000[1].pptx
PPTX
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
PPTX
CyberSecurity Mobile and Wireless Devices
PDF
20250617 - IR - Global Guide for HR - 51 pages.pdf
PPTX
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
PDF
Prof. Dr. KAYIHURA A. SILAS MUNYANEZA, PhD..pdf
PPTX
Principal presentation for NAAC (1).pptx
PPTX
Measurement Uncertainty and Measurement System analysis
PPTX
A Brief Introduction to IoT- Smart Objects: The "Things" in IoT
PDF
Applications of Equal_Area_Criterion.pdf
PDF
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
PPTX
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
PDF
Design of Material Handling Equipment Lecture Note
PPTX
Information Storage and Retrieval Techniques Unit III
PPTX
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
PPTX
Feature types and data preprocessing steps
PDF
distributed database system" (DDBS) is often used to refer to both the distri...
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
Module 8- Technological and Communication Skills.pptx
Chemical Technological Processes, Feasibility Study and Chemical Process Indu...
PRASUNET_20240614003_231416_0000[1].pptx
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
CyberSecurity Mobile and Wireless Devices
20250617 - IR - Global Guide for HR - 51 pages.pdf
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
Prof. Dr. KAYIHURA A. SILAS MUNYANEZA, PhD..pdf
Principal presentation for NAAC (1).pptx
Measurement Uncertainty and Measurement System analysis
A Brief Introduction to IoT- Smart Objects: The "Things" in IoT
Applications of Equal_Area_Criterion.pdf
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
Design of Material Handling Equipment Lecture Note
Information Storage and Retrieval Techniques Unit III
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
Feature types and data preprocessing steps
distributed database system" (DDBS) is often used to refer to both the distri...
Exploratory_Data_Analysis_Fundamentals.pdf
Ad

summer t.pdf

  • 1. SUMMER TRAINING REPORT PROGRAMMING WITH PYTHON Carried out with Submitted by Rupal Gandhi 41196302817 In partial fulfillment for the award of the degree Of BACHELOR OF TECHNOLOGY In ELECTRONICS AND COMMUNICATION ENGINEERING MAHARAJA SURAJMAL INSTITUTE OF TECHNOLOGY, NEW DELHI C-4, Janak Puri, New Delhi-58 Affiliated to Guru Gobind Singh Indraprastha University, Delhi
  • 3. ABSTRACT This report presents basic information about python programming. It includes info on the origin of python language / platform and its development, different data types and their syntax and their implementation with different functions and commands. In this we have some sample programs to teach and learn basic programming on python platform. Similarities and advantages of python in comparison with C, C++ and java are given in this report. i
  • 4. ACKNOWLEDGMENT To learn various technical and non-technical courses on the online platform. It helped me to complete my summer training with ease and flexibility to learn. It is indeed a great pleasure for me to present this Summer Training report on Python programming language given by Internshala Trainings. As a part of the curriculum of the B.Tech course (Electronics and Communication Engineering) in MSIT (Maharaja Surjmal Institute of Technology), Janakpuri, New Delhi. I take this golden opportunity to thank.Mr Sarvesh Aggarwal, founder and CEO of Internshala and the course provider. I express my sincere thanks to Mr. Sarvesh Aggarwal and content setup team for my course. There is no denying the fact that Internshala Trainings is a huge platform. RUPAL GANDHI (41196302817) ii
  • 6. TABLE OF CONTENTS Title Page no. Chapter 1: Introduction to Python. 1-8 What is Python? 1 Some facts related to Python programming 2 Detailed History 3 Why Python? 4 Installing Python 6 The Python shell 8 Install a text editor 8 Chapter 2: Hello World and the Basics of Python 9-13 Interactive Programming Mode 9 Script Programming Mode 9 Running the HelloWorld.py script file 9 Python Identifiers 10 Reserved Words 11 Lines and indentation 12 Comments in Python 12 Quotation in Python 13 Blank Lines 13 Chapter 3: Variables and Basic Operators in Python 14-23 Types of Variables in Python 14-16 • Declaring a variable 14 • Assigning a single value to multiple variables 15 • Assigning multiple variables multiple 15 Basic Operators 16-22 Operators Precedence in Python 23 Chapter 4: Working with Strings and Numbers 24-30 Strings in Python 24 iii
  • 7. Creating a string 24 String escape sequence 25 String Methods 26 String formatting 26 Numbers in Python 27 Chapter 5: Lists and Tuples and Dictionary 31-37 Python Lists and Tuples 32 Python Dictionaries 35 Chapter 6: Input, Output, and Import 38-41 Capturing keyboard input using input() 39 Arguments of the print function 40 Python Import 40 Chapter 7: Decision Making and Looping 42-47 Decision making in Python 43 Loops in Python 45 Chapter 8: Functions and function arguments 48-49 Defining a function in Python 49 Calling a function 49 Function arguments 49 Chapter 9: File Operations 51-52 Opening a file 51 Project iv
  • 8. LIST OF FIGURES AND TABLES Fig / Table Page no. Fig.1-Python logo 1 Fig.2- The python.org/downloads/ download page 7 Table 1: Reserved keywords in Python 11 Table 2: Arithmetic operators in Python 18 Table 3: Assignment operators in Python 19 Table 4: Relational (comparison) operators in Python 20 Table 5: Logical operators in Python 20 Table 6: Membership operators in Python 21 Table 7: Identity operators in Python 21 Table 8: Bitwise operators in Python 22 Table 9: Operators precedence in Python 23 Table 10: String literal escape characters in Python. 25-26 Table 11: String methods in Python 26 Table 12: String formatting symbols 27 Table 13: Mathematical Functions 30 Table 14: List and tuple functions 33 Table 15: List methods in Python 33 Table16: Dictionary methods in Python. 36 Table 17: Dictionary functions in Python. 36 v
  • 9. Chapter 1: Introduction to Python Fig.1-Python logo What is Python? Python is an interpreted, high level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes coded readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large- scale projects. 1
  • 10. Some facts related to Python programming: Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including procedural, object-oriented, and functional programing. Python is often described as a “batteries included” language due to its comprehensive standard library. Python was named after the Monty Python Flying Circus comedy group that was popular in the UK between 1969 and 1974. Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0 released in 2000, introduced features like list comprehensions and a garbage collection system capable of collecting reference cycles. Python 3.0 released in 2008, was a major revision of the language that is not completely backward- compatible, and much Python 2 code does not run unmodified on Python 3. The Python 2 language i.e. Python 2.7.x, was officially discontinued on 1 January 2020 after which security patches and other improvements will not be for it. With Python 2‟s end-of-life, only Python 3.5.x and later are supported. 2
  • 11. Detailed History Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands as a successor to the ABC language, capable of exception handling and interfacing with the Amoeba operating system. Its implementation began in December 1989. Van Rossum shouldered sole responsibility for the project, as the lead developer, until 12 July 2018, when he announced his "permanent vacation" from his responsibilities as Python's Benevolent Dictator for Life, a title the Python community bestowed upon him to reflect his long-term commitment as the project's chief decision-maker. He now shares his leadership as a member of a five- person steering council. In January 2019, active Python core developers elected Brett Cannon, Nick Coghlan, Barry Warsaw, Carol Willing and Van Rossum to a five-member "Steering Council" to lead the project. Python 2.0 was released on 16 October 2000 with many major new features, including a cycle- detecting garbage collector and support for Unicode. Python 3.0 was released on 3 December 2008. It was a major revision of the language that is not completely backward-compatible. Many of its major features were back ported to Python 2.6.x and 2.7.x version series. Releases of Python 3 include the 2 to 3 utility, which automates (at least partially) the translation of Python 2 code to Python 3. Python 2.7's end-of-life date was initially set at 2015 then postponed to 2020 out of concern that a large body of existing code could not easily be forward-ported to Python 3 3
  • 12. Why Python? If you did your research well before choosing to buy this eBook, you probably discovered that Python is by far the most studied and the most widely used high level programming language today. This is not just because it emphasizes on code readability and simple syntax, or because it requires fewer lines of code to create a program compared to other languages; here are the top seven reasons why you should see your decision to take on Python programming studies to the end: 1. Python opens up endless opportunities for programmers Python developers are making a killing freelancing and taking up permanent jobs because the language is very popular among companies and organizations. Once you get comfortable with coding sing Python, you will be in a good position to consider job opportunities and even gigs that pay you to apply the concepts you learn in this book. 2. Python is a preferred language for web development The number of websites on the World Wide Web is approaching the 1 billion mark and one facet of this evolution is the growing scope of Python in web development. Python brings a lot of flexibility and an array of ready-to-use framework (such as django, Zope2, Pylons, Grok, and web.py) that are revolutionizing how the front and back end of websites are built. Learning to create websites in Python is the best way to position you on the right side of history. 3. Learning computational thinking with Python is easy Python is a high-level programming language that reads like regular English. Because of this, many English-speaking learners find it very easy to understand its syntax and how to use the various components of the language with minimal complexity. If you are a beginner, you will be surprised how easy it is to tell the computer what to do in Python and to think in ways that helps you conceptualize computer code. 4
  • 13. 4. Python has a rich and vibrant online community As you enter the world of programming, you will discover soon enough how important the developer community is to the language and to its learners. The Python community is the 5th largest on Stack Overflow community and the fourth most used language on Github. When you venture to the cyberspace to interact with other learners and with professionals, you will be taken aback by the huge number of people ready to help you learn by answering your questions and checking your code. 5. Python has one of the most mature package libraries Most programming, as you will discover soon, is repetitive. When you start writing code on a commercial scale, you will appreciate the fact that Python is backed by repositories such as PyPI with hundreds of thousands of free modules and scripts that you can grab and use in your code. These modules and scripts bring pre-packaged functionality to your Python environment to solve a myriad of problems that you would otherwise have to deal with one-by-one. With Python, there is no need to re-invent the wheel. 6. Python is cross-platform and open source Python has been around for over 20 years and throughout that period, it has been developed as a cross- platform and open source software that runs on Linux, Windows, and MacOS. Besides, the language is backed by over 2 decades of kink-straightening and bug-squashing which has turned it into a power house that makes your code run like you intended it on whichever platform. 7. Learning Python is the ideal stepping stone to other languages There aren‟t many languages today that offer the simplicity and versatility of Python, but different people choose their languages of specialty for their own reasons. Even if you intend to specialize in some other high-level programming language e.g. C#, C++, or Java, Python is a great language to learn first before diversifying into another language. 5
  • 14. Installing Python In order to begin writing Python scripts and execute them on your computer, you must first set up the right software on your computer. Nothing is complicated at this stage, just as long as you follow the right steps. If you already know how your computer works, how to navigate around the computer storage structure, download software and files, and install programs, this should be a straightforward process. If you already have Python 3 installed on your computer, you can skip this section and proceed at the next section, The Python shell. Download the right software you can download the official Python programming tools from python.org. On your computer browser, go to http://www.python.org/download/and get the latest version of Python (it should be version 3). Before you can begin the installation, take some time to read the resources on https://wiki.python.org/moin/BeginnersGuide and make sure that you know the operating system (and version) of your computer and whether it is a 32-bit or a 64-bit. This is important to ensure that you download the right software. The python.org/downloads/ download page. At the time of writing this book, the newest version of Python is Python 3.6.1. If you are unsure which version to download, click on the name of your operating system to access more options. Windows installation Installation is pretty straightforward on a Windows 10 or 7 computers. Simply download the right version of Python and open the installation wizard when the download is complete. When the installation is complete, make sure that you check the “Add Python 3.6 to PATH” option in the last step of setup.If the installation went well, you can launch Python from the Windows Start menu. The Python Integrated Development Environment (IDLE) shortcut is placed here: Start ➤ Programs ➤ Python2 ➤ IDLE 6
  • 16. The Python shell Python offers a graphical user interface programming environment (Python IDLE) whose shortcut is placed on the desktop, start menu, or the app dock. This environment includes a text editor where you can write your code. When you properly set up the Python Interpreter, you should be able to run any python files with the extension .py in any location from the command line. This is the approach we will use in this eBook. We believe it is best to learn using the terminal (command line) and a text editor of your choosing because it helps you master concepts and even exercise them with minimal distractions. Install a text editor Python code is entered in a plain text editor and saved in a file with the extension .py. There are quite a number of text editors popular with programmers that you can download and use for free. Word processor such as MS Word or WPS Writer does not work in creating scripts because they introduce special characters in the code that interfere with its execution. 8
  • 17. Chapter 2: Hello World and the Basics of Python Python shares many similarities with other object-oriented programming languages especially Perl, C, C++, and Java. Interactive Programming Mode On top of the list of similarities that Python shares with other top programming languages is the Interactive Programming Mode. This simply means that you can invoke the Python interpreter without passing a script file as a parameter. One can execute commands on the Python interpreter without saving the syntax in a script file. The Python interpreter can carry out arithmetic operations and other commands entered directly into the terminal. Note, however, that in this mode, nothing will be saved permanently. Script Programming Mode The script programming mode is used to execute program instructions and commands. What this means is that we will write the code in a script file (in this case a .py file) then save it and run it from the interpreter. Creating the HelloWorld.py script file. Start your text editor and enter the following code exactly as it appears. Ex1: Hello World print ("Hello World!") print ('I am now a Python programmer!') This is a simple Python script with two lines. You can save this script as “HelloWorld.py” in your preferred location. Running the HelloWorld.py script file Now run the HelloWorld.py script from the command line (terminal) by following these steps: When the python script file is saved, you can run it by invoking the Python interpreter in the location that the file is stored. For instance, if you saved it in the folder „ExFiles‟ within the installation directory of Python or the desktop, and you invoke the 9
  • 18. Python 3 interpreter using the keyword python, your command to run the HelloWorld.py script on the terminal (command line) Python Identifiers When writing a program in Python, you will get used to entering common English words you are used to in everyday language, but with sometimes subtle noticeable differences and rules. When specifying a variable, a class, a module, a function or some other object (all of which we will learn later), you need to assign it an identifying name or simply an identifier. Identifiers in Python must begin with an alphabetic letter (A-Z, a-z) or an underscore (_), followed by other letters and digits (0-9) or underscores. You cannot use punctuation characters and other symbols e.g. @, #, $, % and others within the identifier. Also, because Python is case sensitive, uppercase and lowercase letters are different. For instance, Hello is not the same as hello. Here are very vital conventions used to name identifiers in Python that you should know: A Class name must start with an uppercase letter. Every other identifier may start with a lowercase letter. An identifier that starts with a single leading underscore indicates that the identifier is private e.g. _private. An identifier that starts with two underscores is a strong private identifier. If an identifier ends with two trailing underscores, then it is a language-defined special name 10
  • 19. Reserved Words Python has a set of English and non-English words reserved for the interpreter that you cannot use as variable, constant, or any other identifier names. Here is a table of these words: and As asse rt brea k Clas s conti nue Def Del Elif else exce pt Exe c Fina lly For Fro m Glo bal if Imp ort In Is Lam bda Not Or pass print Rais e Whil e Retu rn Try Wit h Yiel d Table 1: Reserved keywords in Python 11
  • 20. Lines and indentation In other programming languages, curly braces ({}) or square brackets ([]) are used to group blocks of related code for function or class definition. In Python, blocks of code are denoted by a line indentation. This indentation rule is rigidly enforced and you can use a tab or a number of spaces, just as long as there is uniformity and consistency in their use. Consider these two blocks of code:If True: print ("True") print ("Proceed") else: print ("False")The statements print (“True”) and print (“Proceed”) are indented with the same number of spaces. This means they form a block. Comments in Python Comments in a Python script are notes left by the programmer for later or for other programmers to understand the code. Comments in Python have the # sign at the beginning. Anything beyond the # sign to the end of the line will be ignored by the interpreter.print ("Hello World!") # Displays “Hello World!” on the screen.# This line will also be ignored by the interpreter.print ('I am now a Python programmer.') # This is another comment.A comment can be typed on a new line or on the same line after an expression or a statement. You cannot write a comment that spans multiple lines on Python. 12
  • 21. Quotation in Python You can use a single ('), a double ("), or triple (''' or """) quotation marks to denote string literals in Python. The only rule is that you must start and end with the same type of quotation on a string. Triple quotations are used when the string of text spans over multiple lines. Print ('Hello World!') # Double quotation marks. Print ("I am now a Python programmer.") # his line will also be ignored by the interpreter. Print ("""I am now a Python programmer. This means I should be able to create a simple Python Script and run it with no difficulty.''') Blank Lines A blank line is a line that contains only whitespace, commonly inserted into code for aesthetic purposes and to keep the code organized. The Python interpreter completely ignores a blank line in the script. There must be a blank line after a multi-line string block to terminate the statement. 13
  • 22. Chapter 3: Variables and Basic Operators in Python Types of Variables in Python In object-oriented programming, a variable is a space in computer memory that is reserved for storing values of a specified type. When you declare a variable in your Python script, you are essentially asking the interpreter to allocate computer memory for the type of data expected and you assign that memory location a name. This name is what we call a variable name and it may be assigned any of the following five data types supported by Python: 1. Numbers 2. Strings 3. Lists 4. Tuples 5. Dictionary The interpreter decides which data will be stored in the reserved memory based on the data type declaration. It is therefore important to specify the type of data the variable will store so that the interpreter can allocate sufficient memory space. Declaring a variable you declare a variable in Python by assigning a variable name a value. Unlike various other high level programming languages, with Python, you do not need to explicitly declare a memory space reservation, it happens automatically when a value is assigned to the variable using the equal sign (=) called the assignment operator in programming. 14
  • 23. Ex2: Enter the following code in your editor and run it from the command line: name = "Peter" age = 22 score = 97.21 print (name, "is", age, "years old.") print (name, "scored", score, "percent.") The print statement is to display the values of the variable as proof of the assignment. In the statement name = “Peter”, the operand „name‟ on the left side of the equal sign is the variable name while that on the right, in this case “Peter”, is the value of the variable. Assigning a single value to multiple variables One of the things that make Python such an efficient and simple languages is that you can assign several variables a single value in one statement. Ex3: x = y = z = 10 print (x) print (y) print (z) When you run the code in Ex3, you will realize when the values of variables x, y, and z are displayed on the screen, are all the same (10). The integer objects x, y, and z are created in the same memory location when the value 10 is assigned to them. This is how you associate one value with multiple variables. 15
  • 24. Assigning multiple variables multiple values Just the way you can assign multiple variables one value using one statement in Python, you can also assign multiple objects to multiple variables with ease. Ex4:name, age, score = "Peter", 22, 97.21 print (age, "year old", name, "scored", score, "percent.") 16
  • 25. Basic Operators An operator is a construct that is used to manipulate the value of an operand. Most of the operators you will encounter while learning Python will look familiar to you from math class, and most serve the same purpose as it did when you were introduced to them in school. In the expression 5 + 6, 5 and 6 are the operands and the + (plus) is the operator The Python language supports seven types of operators: • Arithmetic operators • Assignment operators • Relational or comparison operators • Logical Operators • Membership operators • Identity operators • Bitwise operators 17
  • 26. Arithmetic operators As the name hints, arithmetic operators are the same ones you learned in Math, albeit with a few changes. They are: 18 operaOperation Name Function + Addition Adds the values of both operands - Subtraction Subtracts the value of the right operand from the value of the left operand. * Multiplication Multiplies the values of both operands / Division Divides the value of the left operand by the / value of the right operand % Modulus Like division above, except that it returns the remainder value after division // Floor Division Like division above, except that it returns the quotient value without the decimal point digits ** Exponent Calculates the exponential calculation (power) on the operands Table 2: Arithmetic operators in Python
  • 27. Assignment operators Assignment operators in Python do just what the name suggests: assign values. An assignment operator will assign the value of the right operand to the left operand. symbol Name Function = Equal Assigns the value of the right operand to the left operand. += Add AND Adds the value of both operand and assigns the result to the left operand. -= Subtract AND Subtracts the value of the right operand from that of the left and assigns the result to the left operand *= Multiply AND Multiplies the value of both operands and assigns the result to the left operand. /= Divide AND Divides the value of the left operand with that of the right and assigns the result to the left operand. %= Modulus AND It takes modulus using the two operands and assigns the result to the left operand **= Exponent AND Finds the power (exponential) of the left operand by the right and assigns the result to the left operand. //= Floor Division Performs a floor division on the operands and assigns the AND result to the left operand Table 3: Assignment operators in Python 19
  • 28. 3. Relational (comparison) operator A comparison operator simply compares the value of the left operand with that of the right operand and determines how they relate. operaOperator Name Function == Equal to Condition becomes True if the value of the left operand is equal to the value of the right operand != Not equal to Condition becomes True if the value of the left operand is not equal to the value of the right operand. > Greater than Condition becomes True if the value of the left operand is greater than the value of the right operand < Less than Condition becomes True if the value of the left operand is less than the value of the right operand. >= Equal to or greater than Condition becomes True if the value of the left operand is equal to or greater than the value of the right operand. <= Equal to or less than Condition becomes True if the value of the left operand is equal to or less than the value of the right operand Table 4: Relational (comparison) operators in Python. Logical operators Also called Boolean operators, logical operators are statements that evaluate to either of the two Boolean conditions: True or False. The not keyword introduced as a reserved keyword earlier reverses a Boolean type, True to False and vice versa Operator Function and Returns True if both operands are True or Returns True if either of the operands are true Not Returns True if operand False and False if it is True. Table 5: Logical operators in Python 20
  • 29. Membership operators The two membership operators in Python check for the operand‟s presence in a sequence of values such as strings (alphanumeric characters), lists, or tuples. Operator Function In Returns True if the operand is found in the specified sequence and False if it is not found. not in Returns True if the operand is not found in the specified sequence and False if it is found. Table 6: Membership operators in Python Identity Operators An identity operator compares the memory locations of two objects. There are two identical operators: Operator Function Is Returns True if both operands point to the same object and False if they do not. is not Returns False if both operands point to the same object and False if they do not. Table 7: Identity operators in Python 21
  • 30. Bitwise operators Bitwise operators are used bit-by-bit operators that execute operations on operands in binary form. Symbol Oper ator Function & AN D Copies a bit if found in both operands | OR Copies a bit if found in either of the operands. ~ NO T Complements an operand by flipping ones for zeros and zeros for ones ^ XO R Copies a bit if set in only one operand >> Shift right The value of the left operand is moved right by the bits in the left operand. << Shift left The value of the left operand is moved left by the number of bits in the right operand Table 8: Bitwise operators in Python 22
  • 31. Operators Precedence in Python The Python interpreter follows a very strict order of execution when presented with multiple operations. The table below summarizes all the operations in order of precedence from the highest to the lowest Order Operation Function 1 () Operations enclosed in brackets are executed first. 2 ** Exponentiation (raise to the power) 3 ~ + - Complement, unary plus (+@) and minus (-@) 4 * % / Multiply, divide, modulus and floor division 5 + - Addition and subtraction 6 >> << Bitwise shift right and left 7 & Bitwise AND 8 | ^ Bitwise AND 9 <=<>>= Comparison operators 10 <> == != Relational operators 11 =%==/=- Assignment operators =+=*= **= 12 is is not Identity operators 13 in not in Membership operators 14 not or and Logical operators Table 9: Operators precedence in Python 23
  • 32. Chapter 4: Working with Strings and Numbers In Chapter 2, we touched lightly on the five basic data types that you will be learning to work with in the course.By the end of this chapter, you will be able to work with the two most popular data types: Strings in Python The first data type we encountered in the first exercise of this book. It is a sequence of characters including symbols and alphanumeric characters. In chapter 2, you learned that you can use a single ('), a double ("), or triple (''' or """) quotation marks to denote a string. If you have been practicing what you have learned so far, I am sure you have created countless string variables in your scripts. However, so far we have only touched on how to display them using the method print. In this section, we will look at a number of other great things you can do with strings. Creating a string You create a string by enclosing characters in quotation marks and assigning it a variable name. In the first exercise, we created a string object and displayed its contents on the screen. In Ex2, we created one string object called name with value “Peter”. You can also create a string object by formatting a user‟s input using the method str() (we will cover this later). In Ex11 below, for instance, the user will be prompted to enter a string of text which is assigned the variable name. Accessing the values of a string In Python, you can access the individual characters of a string using slicing, indexing, and a range of other operations. If you try to access a character that is out of index range, you will get an IndexError. The indexes of the characters start at 0 for the first character and you can only use positive integers. If you try to use any other number type such as a decimal (float) you will encounter a Type Error. 24
  • 33. String concatenation and iteration You can join two or more strings to make them one using the plus operator (+) or separating named string variables with a comma You can repeat multiple copies of one string to create new strings using the asterisk operator * String escape sequence You can now work with almost any type of text, after all, you just need to enclose them in quotation marks and split, slice, iterate etc. But what do you do when you want to work with a string that has quotation marks. For instance, how would you print a text that reads: “I am sorry,” he said, “the „Transformers‟ toys are out of stock”.Notice that this sentence has both double and single quotation marks that create a string. If you slap quotation marks on this string and try to print it, you will encounter a Syntax error. Try it. In such a case, we can either use triple quotation marks or escape sequences to get around this problem. An escape sequence begins with a backslash (). You will place the backslash in front of all double quotes inside a string if the string is created with double quotation marks. You will do the same for single quotation marks if the string is created with single quotation marks. There are quite a few of other escape sequences that you will encounter as you practice working with strings. Here is a tabulated list of the most popular escape sequences you will encounter and what they do. 25 Character Sequence Description Backslash Prints one backlash. ” Double Prints a double quote. quote ‟ Single Prints a single quote. quote a Bell Sounds the system bell.
  • 34. b Backs pace Moves the cursor back one space t Tab Moves the cursor forward one tab. n Newli ne Moves the cursor to the beginning of the next line Table 10: String literal escape characters in Python. String Methods There are quite a number of methods you can use to manipulate strings in Python. Some of the most popular are included in the table below: Metho d Description upper( ) Returns the uppercase characters of a string. lower( ) Returns the lowercase version of a string swapc ase() Like toggle case in word processing, it returns a new string with the case of each character in a string switched capital ize() Capitalizes the first letter of string. title() Returns a string with the first character of each word capitalized and the rest lowercase. trip() Returns a string with all white spaces including spaces, newlines, and tabs at the beginning and the end removed. split() Splits all words into a list join() Joins all words into a string. Table 11: String methods in Python 26
  • 35. String formatting In Python, you can format a string by placing the string formatting operator (%) to the left of the conversion specifier, and the values to the right. You can use this formatting operator on a string containing different data types including tuples, lists, and dictionaries. 27
  • 36. Ex name = "Peter" score = 75 print ("My name is %s and I scored %d percent!" %(name, score)) In this example, we use the placeholders %s and %d to format the strings using placeholders %s for string and %d for decimal integer. The table below presents the format symbols you will use on different data types. Format Conversion symbol %c Character %s string (converted using str() before formatting) %i or %d signed decimal integer %u unsigned decimal integer %o octal integer %x hexadecimal integer (lowercase characters) %X hexadecimal integer (UPPERcase characters) %e exponential notation (lowercase 'e') %E exponential notation (UPPERcase 'E') %f floating point real number %g the shorter of %f and %e %G the shorter of %f and %E Table 12: String formatting symbols
  • 37. Numbers in Python After strings, numbers are the next most popular value types in Python. Python supports three types of numbers: integers, floating point numbers, and complex numbers defined as int, float, and complex respectively. Just like strings, number data types are immutable. An integer is a whole number without a decimal point while a floating point number has a decimal. For instance, 2 is an integer while 2.0 is a floating point number. In Python, integers can be of any length and floats are accurate up to 15 places. Complex numbers are in the form x + yj where x is the real part of the number and y is the imaginary part. Complex numbers is beyond the scope of this book so we will cover only integers and floats. We deal with decimal (base 10) numbers in our everyday lives. However, as you become a proficient programmer, you will need to know how to program systems using only binary (base 2), octal (base 8), and hexadecimal (base16) num Using mathematical operators on numbers With Python, you can carry out almost any calculation with numbers without adding any extra code. For instance, on IDLE or the Terminal, you can enter mathematical operations directly and the interpreter will return the result Ex my_math = 10 * -5 print (my_math) print ("10 + 12 * 3 = ", 10 + 12 * 3) print ("15 + 8 = ", 15 + 8) print ("15 + 8.0 = ", 15 + 8.0) print ("217 %5 = ", 217 %5) A number variable is created by assigning a number a name using the equal sign (=). In the above example, we created a variable called my_math with the value 10*-5. Number coercion The process of converting from one type of number to another is called coercion. You already discovered that operations such as addition, subtraction, 29
  • 38. division, multiplication, and others implicitly coerce an integer to a float if one of the operands is a float. You can also use the built-in functions int(), float(), and complex() to explicitly coerce between number types and from strings. Ex number1 = 12 number2 = 2.5 string1 = "10" print (float(number1)) #convert number1 to float and print print (int(number2)) #Convert number2 to integer and print print (int(string1) * number2) YoB = int(input("Enter your year of birth as YYYY: ")) age = 2017 – YoB print ("You are %d years old!" %age) In Ex, the variable number1 is an integer, number2 is a float, and string1 is a string. The 5th line of the script converts number1 to the type float, the next converts number2 to an integer, and the 7th line converts string1 into an integer before multiplying by number2. Note that when converting a number from a float to an integer, it gets truncated at the decimal point, not truncated. In the same example, notice that we created the variable YoB by asking the user to “Enter your year of birth as YYYY: ” then converting it to an integer before working with it. Mathematical Functions There are many inbuilt Python functions that perform mathematical operations on numbers. To use mathematical functions in the standard module, you will have to import the math module using import math. Some of the most common you should know about are tabulated in Table 13: 30
  • 39. Function Description fabs(x) Returns the absolute value of x (positive distance between 0 and x) ceil(x) Returns the ceiling value of x (the smallest integer that is not less than x) floor(x) Returns the floor value of x (largest integer that is not greater than x) cmp(x, y) Compares x and y and returns 1 (if x > y), 0 if x == y, or -1 if x < y exp(x) Returns the exponential of x (ex) Pow(x,y) Returns the value of x**y min(x,y) Returns the smallest of the numbers x and y max(x,y) Returns the largest of the numbers x and y sqrt(x) Returns the square root of x when x > 0 pi Mathematical constant pi e Mathematical constant e Table 13: Mathematical Functions 31
  • 40. Chapter 5: Lists and Tuples and Dictionary Lists and tuples are popular compound data types that generally fall into the sequences category alongside strings, byte sequences, byte arrays, and range objects (you will learn about these at intermediate and advanced stages). Strings may look a lot different from lists and tuples as you will notice, but they are similar in that: • Their elements are placed in a defined sequence. • The elements can be accessed via indices • They can be manipulated via slicing using [] Python, unlike other object-oriented programming languages, uses the same syntax and function names to manipulate list and tuple sequential data types. These operations include indexing, slicing, iteration, concatenation, and checking for membership. We will cover each of these in greater detail in this section. 32
  • 41. Python Lists and Tuples A list in Python is a mutable type that is made up of a collection of ordered objects. The objects contained in a list do not have to be of the same type and may include other lists (nested sublists). A tuple, on the other hand, unlike a list, is an immutable type. This means that the objects (items) in a tuple cannot be changed once created. Just like a list, the objects in a tuple can be of different types. Creating a list and tuple A list is created by placing all the objects (or items) inside a square bracket [] and separated by commas. A tuple is created by separating its values with a comma only but it is a good practice to enclose them in parentheses (brackets). You can also create a list by splitting the elements of a string. You can also create a list by splitting the elements of a string Accessing values in lists and tuples you access the values of lists and tuples (separated by commas) the same way we did the characters of a string: using indices and slicing with square brackets Updating list objects because lists in Python are a mutable type, you can update a single or multiple elements using the assignment operator (=). You can also add new items on the list using the append() method Tuples are immutable and cannot be updated. However, you can take the values of a tuple and create a new tuple by adding new items or combining with an existing tuple. Deleting list objects there are two ways to delete items from a list in Python. If you know the exact items to delete, you can use the del statement but if you don‟t know you can use the remove() method. Basic list and tuple operations Much like strings, lists and tuples respond to the concatenation (+) and iteration (*) operations. 33
  • 42. Python comes with a range of in-built functions that you can use to manipulate lists and tuples. Some of them are: Function Description cmp() Compares the objects of two lists or tuples. len() Returns the total length of a sequence max() Returns the item with the highest value in a sequence min() Returns the item with the lowest value in a sequence list(seq) Converts from a tuple type to a list. tuple(seq) Converts from a list type to a tuple. Table 14: List and tuple functions Python list methods: Here is a table of list methods in Python and what they do. Method Definition append() Adds an item to the end of the list remove() Removes an item from the list extend() Adds all elements of a list to another list insert() Inserts an item at the defined index copy() Returns a shallow copy of a list pop() Removes an item at the given index and returns it index() Returns the index of the first matched item clear() Removes all items on a list count() Returns the number of items passed as an argument reverse() Reverses the order of items in a list sort() Sorts items in a list in ascending order Table 15: List methods in Python 34
  • 43. Advantages of tuples over lists: We have established that lists and tuples are similar in many ways, and they can be used interchangeably in many situations. Considering that lists are mutable while tuples are not, most beginners often wonder under what situations a tuple is more applicable compared to a list. There are four: 1. When working with heterogeneous (different) types of data, it is better to use a tuple. A list is more practical when sequencing data of the same type. 2. Where the sequence will be iterated, it is more advantageous to use a tuple because it is immutable and will be iterated faster by the interpreter. 3. A tuple can be used as a dictionary key because its data is immutable. A list cannot be used as a dictionary key. 4. When you have data that does not change, the best way to make sure that it does not change is to implement it as a tuple. 35
  • 44. Python Dictionaries It would be impractical to write a functional computer program in Python without using the sequential data types we have covered so far (strings, lists, and tuples) and dictionaries. Like lists, dictionaries are a mutable data type whose objects can easily be deleted, updated, and added at runtime and they can also contain different types of data (including lists). The difference between the two is that dictionaries contain items not in any order, unlike lists whose items are ordered. This means that the items on a dictionary are accessed using keys and not their positions. We can therefore say that a dictionary in python is an associative array or hash in which each value is mapped to (associated with) a key. Creating a dictionary A dictionary in Python is created by pairing values with keys using a colon in the format (key:value). The key:value pairs of items are separated by commas and are enclosed in curly braces ({}). A dictionary can also be created or converted from another data type using the built in function dict(). Accessing dictionary elements As mentioned earlier, while indexing is used to access the values of sequential data types, keys are used to access the values of a dictionary. You can use just the key inside a square bracket but it is recommended that you make it a habit to use the get() method. Using get() has the advantage of returning a None value when a key is missing and not a KeyError you would encounter using the keys in square brackets. Updating the dictionary Because the dictionary is a mutable type, you can add new items, delete existing ones, or update keys and values using the assignment operator (=). Dictionary methods Here is a table of the methods available with the dictionary type in Python alongside their definitions. Be sure to try out each of them to see that it does what is described. 36
  • 45. Method Description dict.clear() Removes all items form the dictionary. dict.copy() Returns a shallow copy of the dictionary. dict.items() Returns a new key:value view of the items in the dictionary. dict.keys() Returns a new view of the dictionary's keys. dict.pop(key[,d]) Removes the item with key and return its value or d if key is not found dict.popitem() Removes and returns an arbitary key:value item). dict.update() Updates the dictionary with the key:value pairs, overwriting existing keys dict.values() Returns a new view of the dictionary's values Table16: Dictionary methods in Python. Dictionary functions Python comes with a number of built-in dictionary functions that you can practice with to gain a deeper understanding what they do. They are: Function Description all() Returns True if all dictionary keys are true or if the dictionary is empty. any() Returns True if any key of the dictionary is true and False if the dictionary is empty. len() Returns the length of the dictionary (the number of items). cmp() Compares the items of two dictionaries. sorted() Returns a new sorted list of keys in the dictionary. type(var) Returns dictionary type if passed variable is of type dictionary. str() Produces a printable string of the dictionary items Table 17: Dictionary functions in Python. 37
  • 46. Properties of dictionary keys in Python Dictionary values can be arbitrary objects - standard or user-defined - there are no restrictions. However, there are two vital considerations to bear in mind about dictionary keys: 1. You cannot have two or more similar keys. Keys must be unique. When there are more than one similar keys, the last to be assigned is the only valid one. 2. Dictionary keys must be immutable. You can use numbers, strings, or tuples as keys but you cannot use something like [„key‟]. 38
  • 47. Chapter 6: Input, Output, and Import Python comes with numerous built-in functions readily available at the Python prompt to enable you write programs that accept user input and can output processed information. 39
  • 48. Capturing keyboard input using input() The input() function reads data from the keyboard as a string, no matter whether it is enclosed in quotes (“” or „‟). You can convert the captured text into a specified data type using a casting function (see Example18 script) or using the eval function. When the input() function is called, the interpreter will stop the program flow until the user provides an input and ends it by pressing the return key. The function offers an optional [prompt] parameter of text to print on the screen input([prompt]) The prompt text will be displayed to the left of the line where the user will need to enter keyboard characters. It is a good habit to end the prompt text with a colon and a space (: ) to properly format the input area for the end user There is more you can do with input() besides capturing a single string of text. For instance, you can capture a sequence of data and save it as a list. 40
  • 49. Printing to the screen using the print() function we have used the print() statement to display text on the computer screen. In principle, for any computer program to be useful, it must be able to communicate with the user by displaying requested information on the screen. In Python 3, we use the print() function to convert expressions separated by commas into a string and display the result to the standard console output. Arguments of the print function The print function takes the following arguments: print(value1, value2.., sep='', end='') You can print an arbitrary number of values separated by commas as you can see in almost all the examples so far. The separator (sep) argument defines what separates the printed values and the end argument defines what characters or symbols are placed at the end of the string to print. Other arguments you will discover in the advanced stages of learning to write code in Python are file and flush. Python Import So far, the program examples we have been creating have been very small, only a few lines long. As you create longer scripts and bigger programs, you will find it necessary to break it into modules. A module is a python file containing statements and definitions. Every Python module has a filename and ends with the .py extension, just like the scripts you have been creating so far. There are countless modules distributed with the standard Python installation package or created by individuals and downloadable from the internet. To import a module in Python, you use the keyword import. 41
  • 50. We use the value of pi to calculate the area and circumference of a circle whose radius the user is prompted to enter and converted to a float number. When we import a module, all the definitions it contains are available in the program’s scope. As you practice using import, you will discover that you can also import specific attributes or functions using keywords. For instance, in our above example, we could have just imported the value of pi using the statement: import math pi You can also write the import statement like this: from math import pi. 42
  • 51. Chapter 7: Decision Making and Looping When writing a program, you will have to include decision making structures in anticipation of conditions that will occur during the execution of the program. In this chapter, you will learn how to use the if statement to write a program that makes decisions and how to create a program that iterate particular block of code until or when a condition is met 43
  • 52. Decision making in Python Decision making structures evaluate one or multiple expressions that can return True or False outcomes then use the response to determine which action to take or block of code to execute when the outcome is True or False The following types of decision making statements are available in Python: 1. If 2. if...else 3. if...elif...else 4. Nested if The if statement The if statement tests a condition such as if two variables are equal, then executes a block of code if the result is True. The most basic syntax of this statement is: if : statement(s) Take note of the trailing colon (:) after the test condition and the indentation of the next line of statement(s). The statement(s) in this case is an indented block that may be made up of one or more statements. The indentation is very important in Python because this is how the interpreter determines which lines of code belong to what block. Make it a habit to indent your lines of code to one level using a Tab or four spaces. The if statement tests the Boolean expression which will return either a True or False. If the condition is True, the statement(s) are executed and if it is False, the interpreter will ignore the indented statements and continue with the program execution at the first line after the indented block of statement(s). The if...else statement The if statement has one downside: that there is only one block of code to execute when the test condition evaluates to True. 44
  • 53. Here is the Python syntax for this decision making structure: if : statement(s) else: statement(s) If the test condition returns True, the first block of statements is executed, and if the test condition returns False, the block of statements under the else: statement are executed. The if...elif statement t The if...elif statement is a complex construct of the if...else conditional statement, elif being a shorthand for else if. With the if...elif statement, there are more than one conditions to test and at the end of the tests is an optional else: statement. Beneath else:, just like with the previous if...else statement, is a block of code to execute if all the previous conditions return False. The syntax for the if...elif decision making structure looks like this: if : statement(s) elif: statement(s) Nested If statements When you begin creating even more complex programs in Python, you may find it necessary to place any of the three if decision making structures inside another if structure to form a structure of nested if statements. Because nesting if statements can form a complex, even confusing structure, you will need to pay close attention to indentation to differentiate the levels of each if statement. The syntax of this type of conditional statement would take a structure like this: if : statement(s) if : statement(s) elif statement(s) else: statement(s) elif : statement(s) else: statement(s) 45
  • 54. Loops in Python Loops or loop statements are used to iterate one or more statements multiple times. Python offers three mechanisms for repeatedly executing one or more blocks of code either for a defined number of times or continuously until a defined condition is met. The three types of loops we will cover in this section are: the for loop, the while loop, and the nested loop. The for loop The for loop is the most popular loop structure in Python used to iterate over a sequence such as a list, string, tuple, or range (this is discussed further at the end of the chapter). The for loop takes the following general form: for var_name in sequence: statement In the syntax above, var_name is the variable that assumes the value of the item inside the sequence in every round of iteration. The loop will continue until the last item in the sequence is reached. The while loop The while loop is used to iterate over a block of code as long as a test condition returns True. The while loop is used when you do not know the number of times to iterate in advance. The syntax of the while loop takes this form: while : statements With the while loop, the test condition is checked first and the body executed only if the test condition evaluates to True. This type of loop checks the test condition after each cycle of iteration until the test condition evaluates to False. Nested loop Just the way we put an if statement inside another to create a nested if structure, we can also put a loop a while or for loop inside another loop. The rules and structure for a nested loop in Python is pretty much the same as the rules of nested if. An important note about nesting loops is that you can put any type of loop inside any other type of loop. This means a for loop can fit inside another for loop or while loop and vice versa. The syntax of a basic nested loop would look like any of these: 46
  • 55. for var in sequence: for var in sequence statements statement for var in sequence: while : statements while : for var in sequence: statements while : While : statements Loop control statements In the previous section, we learned that loops iterate over a block of code until a certain condition is met, or until the test condition returns False. However, sometimes, you may wish your program to terminate an ongoing iteration or an entire loop without necessarily checking the test condition. In such a case, you use a loop control statement. Loop control statements are used to alter the normal flow of a looped block of code. Python supports three control statements: break, continue, and pass. The break statement The break statement terminates the loop it is contained in and transfers the flow of execution to the statement immediately following the body of the loop. If the break statement is contained inside a nested loop, its use will cause the innermost loop to terminate. The syntax for the break statement is simply break. The continue statement Unlike break, the continue statement does not terminate the loop and instead breaks the current loop and skips the remaining loop statements. It then moves control back to the beginning of the loop to retest the condition and resume iteration. The syntax for this loop control is continue. The pass statement In Python, the pass statement is a null statement such that nothing happens when it is executed (a state called NOP or no operation). It is used as a placeholder where a statement is required syntactically but there is no code or command to execute. Pass is used as a placeholder for a future function or loop that has not been implemented yet. Note, however, that unlike a comment that is completely ignored, the pass statement is not ignored by the interpreter. 47
  • 56. Using else: with loops in Python The else statement that we used in decision making structure if can also be optionally used with both the for and while loops. Just like with the if statement, loops can have the else: block that is executed when test conditions return a False. The syntax for the for and while loop with else: would look like these: for var_name in sequence: statement else: statement while<condition> : statement else: statement The range command In the examples we used in this chapter, we ask the interpreter to loop over a specified range of integers or characters. The range command is used with the for loop to iterate the loop a fixed number of times. There are three ways to use the range command: range(i): This generates a sequence of integers that begin at 0 and end at i-1 (not i), increasing by 1 with each iteration. range(i, j): This command generates a sequence of integers starting at i and ending at i-j, increasing by 1 with each iteration. range(i,j,k): This range command generates a sequence of integers that start at i and end at j-1, increasing by k with each iteration. 48
  • 57. Chapter 8: Functions and function arguments When you create a block of code that carries out a specific calculation or an action, a useful way to refer to it is a function. In Python, you will be able to call one instance of code many times and reuse it to avoid having to write similar code over and over in one or more programs you create. A function takes some input, referred to as input parameters or arguments, and do something with it. It may or may not return a result (value) depending on what you wrote it for. Consider it a way to break down a complex program into modular or smaller chunks for better organization and manageability. Predefined functions such as sqrt() and cos() are good examples of in-built functions that come with Python. You can also define your own functions 49
  • 58. Defining a function in Python A function is defined using the keyword def and assigning it a name. Its syntax takes the following format: def function_name(arguments): """docstring""" statement(s) The keyword def marks the beginning of the function header followed by the function name, a unique identifier that must follow the standard rules of writing identifiers in Python. The arguments section in parentheses is where the optional values or parameters are passed to the function . Note that the end of the function header is marked by a colon (:). The optional documentation string (docstring) describes what the function does. The statements that make up the body of the function are entered below the docstring and must be indented at the same level, typically one tab or four spaces. The return statement at the very end of the function exits the function back to the last position from where it was called. Note that return may contain an expression or expressions that get evaluated and a value returned. Calling a function Once you define a function, you can call it from the Python prompt, program, or another function by simply typing its name with appropriate parameters Function arguments If the function is run without the argument it expects, the interpreter will return an error. The same will happen if you provide two arguments when the function needs only one.Python offers multiple options for passing arguments of functions including 1. Positional arguments 2. Optional or defaulted arguments 3. Keyword arguments 4. Arbitrary number of arguments 5. . Arbitrary number of keyword arguments 50
  • 59. Chapter 9: File Operations You have learned a lot so far, but all the examples we have been using either have static data (the data types that we typed into the script for demonstration) or can take temporary user input that is lost when we exit the shell. Practical programming involves working with files to read and store permanent data for the program scripts. This is what you will be introduced to in this chapter. A computer file can be defined as a named storage location on a volatile memory device, such as the hard disk, where data is recorded to be accessed and/or modified later. File operations or file handling in Python is a three-step process that includes: 1. Open a file object. 2. Using the file object to read and write data. 3. Closing the file object. 51
  • 60. Opening a file A file must be opened before it can be read or written into. Python comes with the inbuilt open() function that returns the file object or handle that is used to read and write the file. The syntax for opening a file is: file object = open(file_name, [access_mode], [buffering], [encoding]) File object: Using the open() function creates a file object that is used to call other associated methods. file_name: This is a string argument that contains the name of the file you want to open. access_mode: Access mode is an optional parameter that determines how the file will be accessed or manipulated. [buffering]: If a value of 1 is set, the interpreter will buffer lines while accessing the file. If the value is greater than 1, buffering will depend on the buffer size. When the value is set to 0 or a negative number, the default action which is no buffering will run. [encoding]: This option is included in this list but it only applies to text files. Different operating systems use different encoding standards for text files. For instance, Linux uses “utf-8” while Windows uses “cp1252”. It is a good programming practice to specify the type of encoding when manipulating text files. 52
  • 61. PROJECT MUSIC PLAYER APPLICATION USING TKINDER MUSIC PLAYER Libraries used for Music Player Application: 1. Tkinter We had already told you in the title of this page that we are going to use the Tkinter library, which is a standard library for GUI creation. The Tkinter library is most popular and very easy to use and it comes with many widgets (these widgets helps in the creation of nice-looking GUI Applications). Also, Tkinter is a very light-weight module and it is helpful in creating cross-platform applications(so the same code can easily work on Windows, macOS, and Linux) 2. Pygame module Pygame is a Python module that works with computer graphics and sound libraries and designed with the power of playing with different multimedia formats like audio, video, etc. While creating our Music Player application, we will be using Pygame's mixer.music module for providing different functionality to our music player application that is usually related to the manipulation of the song tracks. 3. OS module There is no need to install this module explicitly, as it comes with the standard library of Python. This module provides different functions for interaction with the Operating System. In this tutorial, we are going to use the OS module for fetching the playlist of songs from the specified directory and make it available to the music player application. MusicPlayer Class Here we have the constructor and the other functions defined in the MusicPlayer class. 1. _init_ Constructor With the help of this constructor, we will set the title for the window and geometry for the window. We will initiate pygame and pygame mixer and then declare track variable and status variable. • We will then Create the Track Frames for Song label & status label and then after Insert the Song Track Label and Status Label. 53
  • 62. • After that, we will create the Button Frame and insert play, pause, unpause, and stop buttons into it. • Then we will create the playlist frame and add the scrollbar to it and we will add songs into playlist. def __init__(self,root): self.root = root # Title of the window self.root.title("MusicPlayer") # Window Geometry self.root.geometry("1000x200+200+200") # Initiating Pygame pygame.init() # Initiating Pygame Mixer pygame.mixer.init() # Declaring track Variable self.track = StringVar() # Declaring Status Variable self.status = StringVar() # Creating the Track Frames for Song label & status label trackframe = LabelFrame(self.root,text="Song Track",font=("times new roman",15,"bold"),bg="Navyblue",fg="white",bd=5,relief=GROOVE) trackframe.place(x=0,y=0,width=600,height=100) # Inserting Song Track Label songtrack = Label(trackframe,textvariable=self.track,width=20,font=("times new roman",24,"bold"),bg="Orange",fg="gold").grid(row=0,column=0,padx=10,pady=5) # Inserting Status Label trackstatus = Label(trackframe,textvariable=self.status,font=("times new roman",24,"bold"),bg="orange",fg="gold").grid(row=0,column=1,padx=10,pady=5) 54
  • 63. # Creating Button Frame buttonframe = LabelFrame(self.root,text="Control Panel",font=("times new roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE) buttonframe.place(x=0,y=100,width=600,height=100) # Inserting Play Button playbtn = Button(buttonframe,text="PLAYSONG",command=self.playsong,width=10,height=1,font=("ti mes new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=0,padx=10,pady=5) # Inserting Pause Button playbtn = Button(buttonframe,text="PAUSE",command=self.pausesong,width=8,height=1,font=("times new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=1,padx=10,pady=5) # Inserting Unpause Button playbtn = Button(buttonframe,text="UNPAUSE",command=self.unpausesong,width=10,height=1,font=( "times new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=2,padx=10,pady=5) # Inserting Stop Button playbtn = Button(buttonframe,text="STOPSONG",command=self.stopsong,width=10,height=1,font=("ti mes new roman",16,"bold"),fg="navyblue",bg="pink").grid(row=0,column=3,padx=10,pady=5) # Creating Playlist Frame songsframe = LabelFrame(self.root,text="Song Playlist",font=("times new roman",15,"bold"),bg="grey",fg="white",bd=5,relief=GROOVE) songsframe.place(x=600,y=0,width=400,height=200) # Inserting scrollbar scrol_y = Scrollbar(songsframe,orient=VERTICAL) # Inserting Playlist listbox 55
  • 64. self.playlist = Listbox(songsframe,yscrollcommand=scrol_y.set,selectbackground="gold",selectmode=SING LE,font=("times new roman",12,"bold"),bg="silver",fg="navyblue",bd=5,relief=GROOVE) # Applying Scrollbar to listbox scrol_y.pack(side=RIGHT,fill=Y) scrol_y.config(command=self.playlist.yview) self.playlist.pack(fill=BOTH) # Changing Directory for fetching Songs os.chdir("PATH/OF/DIRECTORY") # Fetching Songs songtracks = os.listdir() # Inserting Songs into Playlist for track in songtracks: self.playlist.insert(END,track) 2. The playsong() Function 3. The stopsong() Function 4. The pausesong() Function 5. The unpausesong() Function 6. Root Window Looping 56
  • 65. 57
  • 66. CONCLUSION Python is currently the most popular programming language and millions of newbies and programmers proficient in other languages are taking the time to learn it. Being a general purpose program, Python is used almost everywhere today -- from front-end game development and back-end web server systems to automotive autonomous systems and home appliances and everything in between. Having Python coding experience under your belt certainly advances your marketability and value in the modern world. 58