Tải bản đầy đủ (.pdf) (121 trang)

Python programming an in depth guide into the essentials of python programming

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (780.89 KB, 121 trang )


THE CODE ACADEMY

PRESENTS

Python Programming

An In-Depth Guide Into The Essentials Of
Python Programming


Table of Contents
1: Introduction
What is Python?
What should you expect of this book?
What you need to get started
Setting up Python environment
The Python shell
Use a text editor
Executing Python scripts
2. Python Basic Syntax Rules, Variables and Values
Hello World Program
Basic Syntax Rules in Python
Python Identifiers
Reserved Words
Lines and Indentation
Multi-Line Statements
String Quotation Characters
Comments in Python
Multiple Statements on a Single Line
Variables and Values


Variables and Assignment
3. Basic Operators in Python
Types of Operator
Arithmetic Operators
Comparison Operators


Assignment Operators
Logical Operators
Membership operators
Identity operators
Bitwise operators
Operator Precedence in Python
4. Python Data Types I: Numbers and Strings
Numbers
Creating number objects
Deleting number objects
Number Type Conversion
Mathematical Functions
Strings
Accessing Values in a String
Updating Strings
Concatenating two or more strings
Escape characters
String formatting with %
String formatting with format()
Other common string methods
5. Python Data Types II: Lists, Tuples, and Dictionary
Lists
Creating a list in Python

Accessing values in a list
Updating a list
Deleting an element in a list
Basic list operations
Tuples


Accessing values in a tuple
Updating a tuple
Deleting tuple elements
Basic tuple operations
Dictionaries
Creating a dictionary
Accessing elements of a dictionary
Adding, deleting, and modifying elements in a dictionary
Properties of dictionary keys
6: Decision Making in Python
The if statement
The if… else statement
if...elif...else statement
Nested if statement
7: Loops in Python
The for Loop
Syntax of for Loop
The range() function
for… else loop
while loop
Syntax of while loop
While… else loop
Loop Control Statements

The break statement
The continue statement
The pass statement
8. Input, Output, Files and Import
Output Using the print() function


Output formatting
Input
Python File Input and Output
Opening a file
Writing to a File
Reading From a File
Closing a file
Python File Methods
Importing Modules
9. Functions and Arguments
Syntax of a Function
Creating and calling a function
Docstring
The return statement
Function Arguments
Default arguments
Required arguments
Keyword arguments
Variable-length arguments
10. Objects and Class
Defining a Class
Creating an Object
Constructors

Deleting Attributes and Objects
Conclusion
What next?


1. Chapter 1: Introduction
You have used a computer. You even own one or more, and it helps you
accomplish all kinds of interesting and useful things. The many applications
that computers run to help you solve daily life problems to make your life
easier are designed and written by programmers to accept input and respond to
commands in different ways—but you already know this.
The underlying operations that make computer applications and computer
systems in general useful are determined by the design in which the programs
are written. In this eBook, you will learn how to write computer programs so
that a user can issue instructions to the computer and make it react a way that
solves their problems. This eBook will teach you the basics on how to write
computer programs using a programming language called Python.


What is Python?
Python is one of the numerous computer programming languages that are
gaining popularity every day. It is a general high-level language that is easy to
learn and even easier to use. Its style and philosophy emphasizes on code
readability and simplicity. The syntax makes it easy for programmers to write
computer instructions in fewer lines of code compared to the number it would
take to write similar instructions in other languages such as Java, C++, or C#.
Python’s core philosophy is summarized in the first seven principles that
governed the development of the language as written in The Zen of Python:
They read:
1.

2.
3.
4.
5.
6.
7.

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

At the risk of exposing my biasness towards the language, I will make a bold
claim that Python is fast and steadily becoming the most popular programming
language amongst beginner programmers. You probably chose to study this
language because you were influenced by a programmer already using it, or
learning it. You are in luck because you get to study a simple-to-learn yet
powerful programming language that is also economical with a high level
information structure.
Studying Python is possibly the most effective approach you could have chosen
to learn object-oriented programming. The code you will learn to create by
studying the chapters in this eBook will help you create elegant and dynamic
syntax that is already interpreted. Your code will be perfect and ready for
scripting, and turning simple lines of text into speedy and useful applications


that can run on a variety of platforms – both small and large scale. Whether you

are completely new to computer programming or have some experience with
another language, you will be pleasantly surprised how easy it is to create
powerful programs with Python.


What should you expect of this book?
This book is written for a complete beginner to the world of programming or a
seasoned programmer curious to learn a new language. It goes deep to show
what makes Python such a dynamic programming language, starting from how
to set it up on your computer, what the different data types it uses are, what
basic functions you need to know, and what classes and objects are used in the
course of creating programs. It also teaches the basics about operators and
variables, and how to call functions among others.
Do not be intimidated by all these jargon—they are the most basic things you
need to learn when you are introduced to any programming language. What
makes this book special, however, is HOW you learn them, and not WHAT
you learn. You could use Google only and still get as much information as you
need to get started, but you would probably end up lost and confused because
you need ordered and simplified introduction to master the art of coding in
Python.
This book uses instruction technique to guide you through a sequence of 64
controlled exercises that will build your skills through practice. First you do,
see HOW it works, then learn the WHAT and WHY. This is a great way to
gradually but progressively establish your coding skills by practice and
memorization, which enables you to apply what you learn in more difficult
problems at the end of each section of the book.
By the end of this book, you will be equipped with the skills to learn even
more complex programming topics in Python and other object oriented
programming languages. As long as you invest your focus in every chapter of
the book, dedicate some time in understanding and practicing what you learn,

and apply the skills you acquire outside what you learn within the book, you
will be a proficient Python programmer in no time.


What you need to get started
The requirements to use this book to learn programming using Python are pretty
straightforward:
1. You must have a computer running a Windows, Mac OS, or Linux.
To be able to write computer programs in Python, you need to have a
compatible operating system with Python binaries installed. Some
operating systems including Mac OS and Linux come with Python preinstalled, but you may need to download and install from python.org if
your system has the older v. 2 installed or if you are a Windows user.
There are two versions of Python currently in use: Python 2.x and Python
3.x or simply Python 2 and Python 3. There are subtle differences
between these two versions that may nevertheless affect how your
program runs, hence how you write your scripts. Ensure that you have
Python 3 installed in your system before you proceed. Go to
to learn more
about this.
2. You must know basic computer operations and how to read and
write.
Stupidly obvious as it may seem, you need to have basic computer skills
that include typing and manipulating files and folders to become a
programmer. If you have not used a computer before, this book is not for
you. You cannot learn to create computer software if you have not used
computer software before. Considering how far you have come, this
book assumes that you can read, write, and follow simple instructions.
3. You must pay attention to detail and be persistent
What typically sets good computer programmers apart from bad
programmers is how they can visually spot minute differences between

two pieces of text. For instance, you must be able to tell the difference
between a colon (:) and a semicolon (;) because it can be the difference
between a functional and buggy code. Unless you learn to pay close


attention to detail, you will miss key elements that make your program
what you want it to be.
While studying to become a programmer, you will make many mistakes,
just the way musicians make many mistakes when learning to play the
guitar. But getting it wrong once should not mean the end of the road for
you; you must persist and go over your code over and over to understand
it or to find problems in them. Repetitive practice is what will make you
good at writing computer programs.


Setting up Python environment
On your computer, open a terminal window and type the word “python” to find
out if the local environment is already set up and which version is installed. If
you do not have the latest version of Python installed, you can download the
source code, binaries and documentation for Python 3.5 from python.org.
You will need to know whether you are running a 32-bit or a 64-bit operating
system beforehand to download the right version of Python for your computer.
Should you encounter any difficulty while downloading or installing the
program (package for unix-based systems), you can check out the simplified
beginner’s resources on this link: />.
By default, Python creates an installation directory on the root of your
computer hard drive with a name that corresponds to the version number of the
Python development environment you downloaded. For instance, Python 3.6.2
release candidate 1 installs to C:\Python36-21\ on a Windows computer. You
can change where Python installs by clicking on “Customize installation”

button during setup.
Be sure to check the ‘Add Python 3.5 to PATH’ option during the last step of
setup.
When Python installs successfully to your computer, you will be able to write
scripts in Python as instructed in this book and run them with no problem. We
recommend that you extract the practice Exercise files bundled with the book
to the ‘Exercises’ directory within the Python installation folder to make it
easy to execute them during the course of learning. The path to the Exercises
directory will look something like this:
C:\Python36-21\Exercises\
This is also the location you should save your practice files for easier access


from the terminal.


The Python shell
When you install Python, you will have the option to run python scripts saved
as .py files right from your computer’s terminal or you can use the simpler
Python IDLE integrated development environment. When you install Python, a
link to IDLE link will be placed on the desktop or your programs menu. We use
the command-line interpreter for exercises in this book because it is more
practical and helps you learn and master concepts faster with less distractions.
You can initialize the Python Shell via the IDLE link placed on the desktop, on
the dock if you use a Mac, or on the Start menu if you are a windows user.


Use a text editor
You need a text editor to write your code on and save it as a .py. Word
processors such as MS Word will not work because they introduce formatting

characters in the text that will interfere with the code. There are many
lightweight text editors you can download and install that come with advanced
tools to check and even color your code to minimize the chances of making
mistakes.
Some of the most popular text editors you should check out are Notepad++,
Vim, Atom, Sublime Text, and Text Wrangler for Mac users.


Executing Python scripts
Python scripts have an extension of .py. When saving your code, be sure to
specify this in the filename. It is preferable that you save your exercise scripts
with a simple but descriptive name with no spaces. The exercise files
accompanying this book are named Exercise1.py, Exercise2.py and so on.
Proper naming of your script files eliminates chances of errors and confusion
when calling them from the terminal.
To run the saved .py scripts, you will need to know a few things about
navigating the terminal (the command line interface). The instructions are much
alike for navigating the terminal is similar for most operating systems. You
should know how to change directories (you must always be on the working
directory in which the python scripts are saved to call them), and you should
know how to call and quit the Python interpreter.
To call the Python interpreter, simply type Python.
If typing Python calls the interpreter for the older version 2 Python interpreter,
you may want to try Python3, especially if you are a Linux or Mac user.
For instance, to run a script saved as HelloWorld.py on a windows terminal,
you will enter this on your terminal then press enter:
C:\Python36-21\Exercises\Python HelloWorld.py

Now that we have that out of the way, let us begin.



Chapter 2. Python Basic Syntax Rules,
Variables and Values
Hello World Program
In keeping with the age-old tradition of introducing newbies to the world of
programming with a simple Hello World, your first program will be a simple
program that displays the “Hello World”.
First off, start your command line terminal and initiate the Python interpreter by
typing “python” and pressing enter. You should see a prompt with three arrows
meaning that the Python interpreter has been invoked.

Enter the following text and press enter (return):
>>> print ("Hello World!")
This is a way to invoke the interpreter without having to pass a script file.
However, this approach does not save your program because the code is
interpreted and executed from the temporary memory.
To create a program we can save, we will have to save the line of code we
typed in a .py script file using a text editor.


Exercise1: Hello World!
Start your text editor and type the code as it appears, replacing the (enter your
name here) with your name. Choose a name to save your script as, such as
HelloWorld.py. The line of code on your editor should look like this:
print ("Hello World!") #This will display Hello World! text on the screen
print ('Hello World again!')
print ("My name is (enter your name here)")
If you set the Python PATH variable correctly during setup, you should be able
to run the saved .py script from the terminal by typing this command:
$ python HelloWorld.py

If you typed the code exactly as it appears, and you are running Python from the
directory in which the python script is saved, you should see the following
result on your terminal when you execute the HelloWorld.py script:
print ("Hello World!") #This will display Hello World! text on the screen
print ('Hello World again!')
print ("My name is (enter your name here)")
Congratulations! You just wrote your first program in Python! By your own
effort, you have earned the right to be referred to as a programmer.


Basic Syntax Rules in Python
Before we can delve further into learning to write code in Python, there are a
few universal Python syntax rules you must grasp first. In this section, we will
cover the most basic rules you need to get started with your very first real
Python program. We will learn more rules and best practices later on in the
book.

Python Identifiers
An identifier is a name used to identify an object such as a variable, module,
class, or function. In the Python language, an identifier must begin with an
alphabetic letter in uppercase (A to Z), lower case (a to z) or an underscore
(_) followed more letters, underscores, or numeric digits. Python does not
allow the use of punctuation characters such as %, /, $, or @ within the
identifier name.
It is also important to note that Python is a case sensitive language. This means
that an identifier age is not the same as Age.

Reserved Words
There are a number of words written in lowercase letters that are reserved and
cannot be used as constants, variables, or variable identifies. Here is a table of

these words:
And

assert

break

class

continue

Def

del

elif

else

except

exec

finally

for

from

global


If

import

in

is

lambda

Not

or

pass

print

raise

return

try

while

with

yield



Table 1: Reserved words in Python.

Lines and Indentation
Unlike most other object-oriented programming languages, Python does not
make use of curly braces to group lines of code into blocks to define functions,
classes and flow control structures. Instead, line indentations are used to
denote blocks of code. The rule of indentation is rigidly enforced.
The number of spaces in the indentation may vary, but all statements within one
block must have matching indentation spaces, typically four spaces or one tab
per indent level.

Multi-Line Statements
Typically, statements in Python end with a new line. However, the line
continuation character (\) can be used to denote that the line does not end and
instead continues in the next. Consider this example:
Total_cost = item1_price + \
item2_price + \
item3_price
Multi-line statements contained within brackets (), square brackets [], or curly
braces {} do not need the line continuation character.
workdays = ["Monday", "Tuesday", "Wednesday",
"Thursday", " Friday", "Saturday"]

String Quotation Characters
Single (‘), double (“), and triple (''' or """) quotation marks are used to denote
string literals in Python. A quotation must start and end with the same type of
quote mark. Triple quotation marks denote strings that may span multiple lines.



In Exercise2, you can see how:
Exercise2: String quotation
name = 'John'
occupation = "Python programmer"
comment = """John is a Python programmer. He is
currently based in London."""
print (name)
print (occupation)
print (comment)

Comments in Python
Comments in your program code are lines of text that the interpreter ignores
because they are written for humans to understand what a particular section of
the code does. Comments in Python start with the hash sign (#). Anything that
comes after this sign will be ignored by
#This is a comment. It will be ignored by the interpreter.
print ("Hello World!") #This is another comment
To write comments spanning multiple lines, you must start each line with the #
symbol.

Multiple Statements on a Single Line
You can separate multiple lines written on a single line using a semi-colon.
This rule only applies when neither of the statements on the line start a new
block of code. Such a line would look like this:
name = "John"; age = 21;



Variables and Values

Variables and Assignment
You were taught in basic algebra that a variable represents a number. The same
applies in Python, except that a variable can also represent other values
besides numbers, which can be integers or floats (we will look at these
briefly). In Exercise2, as an illustration, we took a variable “name” and
assigned it a value “John”. In Exercise3, we take another variable x and assign
it a value 10.
Exercise3: Variable assignment
x = 10
print (x)
The statement x = 10 is what is called an assignment statement. Assignment is
associating a value with a variable. In Python, the key to assignment statement
is the use of an assignment operator which is the symbol =, as you know from
math, the equal sign.
To put it in another way, the statement x = 10 binds a variable we named x to
the value 10. In this case, x is a type int because it is bound to a value of
integer type.
You can assign and re-assign a variable as often as wish. The variable type
will change when you reassign it an expression of a different type.
The print statement in Exercise4.py displays the assigned value of variable x.
Re-assigning the variable a different to the variable will evident after printing
it.
Exercise4: Multiple variable assignment
x = 10
print (x)
x = “Apples”


print (x)
When you run exercise5.py, here is what you should see:

10
Apples
Exercise5: Assigning multiple variables same value
You can assign a single value to several variables simultaneously in Python.
Consider this exercise:
x = y = z = 10
print (x)
print (y)
print (z)
When you run the script above, you will notice that the values of variables x, y,
and z are all 10. This is because an integer object with the value 10 is created
and all the variables are assigned to its memory location.
You can also assign multiple variables multiple values in one line of code.
This is best illustrated in Exercise6.
Exercise6: Assigning multiple variables different values
name, age, occupation = "John", 21, "programmer"
print (name + age + occupation)
In Exercise6, three objects “John”, 21, “programmer” are assigned to
variables name, age, and occupation respectively.
Do not worry if the script prints “John21programmer” with no spaces—you


×