1. Trang chủ
  2. » Công Nghệ Thông Tin

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

121 137 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 121
Dung lượng 780,89 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 ValuesHello World Prog

Trang 2

THE CODE ACADEMY

PRESENTS

Python Programming

An In-Depth Guide Into The Essentials Of

Python Programming

Trang 3

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 ValuesHello World Program

Basic Syntax Rules 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

Trang 4

Operator Precedence in Python

4 Python Data Types I: Numbers and Strings

Numbers

Creating number objects

Deleting number objects

Number Type Conversion

String formatting with %

String formatting with format()

Other common string methods

5 Python Data Types II: Lists, Tuples, and DictionaryLists

Creating a list in Python

Accessing values in a list

Updating a list

Deleting an element in a list

Basic list operations

Tuples

Trang 5

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 dictionaryProperties of dictionary keys

6: Decision Making 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

Trang 7

1 Chapter 1: Introduction

You have used a computer You even own one or more, and it helps youaccomplish all kinds of interesting and useful things The many applicationsthat computers run to help you solve daily life problems to make your lifeeasier are designed and written by programmers to accept input and respond tocommands in different ways—but you already know this

The underlying operations that make computer applications and computersystems in general useful are determined by the design in which the programsare written In this eBook, you will learn how to write computer programs sothat a user can issue instructions to the computer and make it react a way thatsolves their problems This eBook will teach you the basics on how to writecomputer programs using a programming language called Python

Trang 8

What is Python?

Python is one of the numerous computer programming languages that aregaining popularity every day It is a general high-level language that is easy tolearn and even easier to use Its style and philosophy emphasizes on codereadability and simplicity The syntax makes it easy for programmers to writecomputer instructions in fewer lines of code compared to the number it wouldtake to write similar instructions in other languages such as Java, C++, or C#

Python’s core philosophy is summarized in the first seven principles thatgoverned the development of the language as written in The Zen of Python:They read:

1 Beautiful is better than ugly

2 Explicit is better than implicit

3 Simple is better than complex

4 Complex is better than complicated

5 Flat is better than nested

6 Sparse is better than dense

7 Readability counts

At the risk of exposing my biasness towards the language, I will make a boldclaim that Python is fast and steadily becoming the most popular programminglanguage amongst beginner programmers You probably chose to study thislanguage because you were influenced by a programmer already using it, orlearning it You are in luck because you get to study a simple-to-learn yetpowerful programming language that is also economical with a high levelinformation 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 bystudying the chapters in this eBook will help you create elegant and dynamicsyntax that is already interpreted Your code will be perfect and ready forscripting, and turning simple lines of text into speedy and useful applications

Trang 9

that can run on a variety of platforms – both small and large scale Whether youare completely new to computer programming or have some experience withanother language, you will be pleasantly surprised how easy it is to createpowerful programs with Python.

Trang 10

What should you expect of this book?

This book is written for a complete beginner to the world of programming or aseasoned programmer curious to learn a new language It goes deep to showwhat 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, whatbasic functions you need to know, and what classes and objects are used in thecourse of creating programs It also teaches the basics about operators andvariables, and how to call functions among others

Do not be intimidated by all these jargon—they are the most basic things youneed 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 youneed to get started, but you would probably end up lost and confused becauseyou need ordered and simplified introduction to master the art of coding inPython

This book uses instruction technique to guide you through a sequence of 64controlled 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 andmemorization, which enables you to apply what you learn in more difficultproblems at the end of each section of the book

By the end of this book, you will be equipped with the skills to learn evenmore complex programming topics in Python and other object orientedprogramming languages As long as you invest your focus in every chapter ofthe book, dedicate some time in understanding and practicing what you learn,and apply the skills you acquire outside what you learn within the book, youwill be a proficient Python programmer in no time

Trang 11

What you need to get started

The requirements to use this book to learn programming using Python are prettystraightforward:

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 acompatible operating system with Python binaries installed Some

operating systems including Mac OS and Linux come with Python installed, but you may need to download and install from python.org ifyour 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 Python3.x or simply Python 2 and Python 3 There are subtle differences

pre-between these two versions that may nevertheless affect how your

program runs, hence how you write your scripts Ensure that you havePython 3 installed in your system before you proceed Go to

https://wiki.python.org/moin/BeginnersGuide/Download to learn moreabout this

2 You must know basic computer operations and how to read and

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 betweentwo pieces of text For instance, you must be able to tell the differencebetween a colon (:) and a semicolon (;) because it can be the differencebetween a functional and buggy code Unless you learn to pay close

Trang 12

attention to detail, you will miss key elements that make your programwhat 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 theguitar But getting it wrong once should not mean the end of the road foryou; 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 yougood at writing computer programs

Trang 13

Setting up Python environment

On your computer, open a terminal window and type the word “python” to findout if the local environment is already set up and which version is installed Ifyou do not have the latest version of Python installed, you can download thesource 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 operatingsystem beforehand to download the right version of Python for your computer.Should you encounter any difficulty while downloading or installing theprogram (package for unix-based systems), you can check out the simplifiedbeginner’s resources on this link: https://wiki.python.org/moin/BeginnersGuide

By default, Python creates an installation directory on the root of yourcomputer hard drive with a name that corresponds to the version number of thePython development environment you downloaded For instance, Python 3.6.2release candidate 1 installs to C:\Python36-21\ on a Windows computer Youcan 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 writescripts in Python as instructed in this book and run them with no problem Werecommend 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 Exercisesdirectory will look something like this:

C:\Python36-21\Exercises\

This is also the location you should save your practice files for easier access

Trang 14

from the terminal.

Trang 15

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, alink to IDLE link will be placed on the desktop or your programs menu We usethe command-line interpreter for exercises in this book because it is morepractical 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, onthe dock if you use a Mac, or on the Start menu if you are a windows user

Trang 16

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 formattingcharacters in the text that will interfere with the code There are manylightweight text editors you can download and install that come with advancedtools to check and even color your code to minimize the chances of makingmistakes

Some of the most popular text editors you should check out are Notepad++,Vim, Atom, Sublime Text, and Text Wrangler for Mac users

Trang 17

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 scriptswith 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 confusionwhen 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 muchalike for navigating the terminal is similar for most operating systems Youshould know how to change directories (you must always be on the workingdirectory in which the python scripts are saved to call them), and you shouldknow 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

Trang 18

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 ofprogramming with a simple Hello World, your first program will be a simpleprogram that displays the “Hello World”

First off, start your command line terminal and initiate the Python interpreter bytyping “python” and pressing enter You should see a prompt with three arrowsmeaning that the Python interpreter has been invoked

Enter the following text and press enter (return):

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

Trang 19

Exercise1: Hello World!

Start your text editor and type the code as it appears, replacing the (enter yourname 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 screenprint ('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 thedirectory 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 screenprint ('Hello World again!')

print ("My name is (enter your name here)")

Congratulations! You just wrote your first program in Python! By your owneffort, you have earned the right to be referred to as a programmer

Trang 20

Basic Syntax Rules in Python

Before we can delve further into learning to write code in Python, there are afew universal Python syntax rules you must grasp first In this section, we willcover the most basic rules you need to get started with your very first realPython program We will learn more rules and best practices later on in thebook

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 analphabetic letter in uppercase (A to Z), lower case (a to z) or an underscore(_) followed more letters, underscores, or numeric digits Python does notallow the use of punctuation characters such as %, /, $, or @ within theidentifier 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 andcannot be used as constants, variables, or variable identifies Here is a table ofthese words:

Trang 21

Table 1: Reserved words in Python.

Lines and Indentation

Unlike most other object-oriented programming languages, Python does notmake use of curly braces to group lines of code into blocks to define functions,classes and flow control structures Instead, line indentations are used todenote blocks of code The rule of indentation is rigidly enforced

The number of spaces in the indentation may vary, but all statements within oneblock must have matching indentation spaces, typically four spaces or one tabper indent level

Multi-Line Statements

Typically, statements in Python end with a new line However, the linecontinuation character (\) can be used to denote that the line does not end andinstead continues in the next Consider this example:

"Thursday"," Friday", "Saturday"]

String Quotation Characters

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

Trang 22

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

#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 newblock of code Such a line would look like this:

name = "John"; age = 21;

Trang 24

Variables and Values

Variables and Assignment

You were taught in basic algebra that a variable represents a number The sameapplies in Python, except that a variable can also represent other valuesbesides numbers, which can be integers or floats (we will look at thesebriefly) In Exercise2, as an illustration, we took a variable “name” andassigned it a value “John” In Exercise3, we take another variable x and assign

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

Exercise4: Multiple variable assignment

x = 10

print (x)

x = “Apples”

Trang 25

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:

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 tovariables name, age, and occupation respectively

Do not worry if the script prints “John21programmer” with no spaces—you

Trang 26

get the point The print statement in this exercise is for demonstration purposes.

We will cover how to format your outputs later in the book

Trang 27

Chapter 3 Basic Operators in Python

In programming, an operator is the construct which is used to manipulate thevalues of operands

On your terminal, invoke the Python interpreter by typing Python then thefollowing and press enter:

Trang 29

print ("When you divide x by z you get", d)

print ("The floor division value of x divided by y is", h)

Here is a table summarizing the above (and more) arithmetic operators used inPython:

- Subtraction Subtracts the value on the right side

from that on the left

* Multiplication Multiplies values on either sides./ Division Divides the value on the left side by

that on the right

% Modulus Divides the value on the left by that

on the right and returns the remainder

calculation of the value on the right

by the value on the left

// Floor Division Divides the value on the left by that

on the right and returns the quotient

Trang 30

value of the result (without thedecimal values).

Trang 31

print ("4 x is not greater than y")

print ("6 x is neither greater than nor equal to y")

Exercise8, demonstrates how to use relational operators The table below

summarizes what all the relational operators in Python do:

the left and right operands are equal

the left and right operands are notequal

> Condition returns true if the value of

the left operand is greater than thevalue of the right operand

< Condition returns true if the value of

the left operand is less than the value

of the right operand

>= Condition returns true if the value of

Trang 32

the left operand is greater than orequal to the value of the rightoperand.

<= Condition returns true if the value of

the left operand is less than or equal

to the value of right operand

Assignment Operators

As the name suggests, assignment operators are used to assign values to

variables Exercise9 demonstrates how these operators are used.

Exercise9: Assignment Operators

Trang 33

right operand to that on the left side.+= Add AND Adds the value of the right operand to

the value of the left operand thenassign the result to left operand

-= Subtract AND Subtracts the value of the right

operand from the value left operandthen assigns the result to the leftoperand

*= Multiply AND Multiplies the value of the right

operand with the value of the leftoperand then assigns the result to leftoperand

/= Divide AND Divides the value of the left operand

by the value right operand thenassigns the result to left operand

%= Modulus AND Takes the modulus using the values of

Trang 34

the two operands then assigns theresult to left operand.

calculation of the operators thenassigns the result to the left operand.//= Floor Division It performs floor division on the

operators then assigns the result to theleft operand

Other assignment operators you will come across at an advanced stage oflearning Python are &=, |=, ^=, >>=, and <<=

Logical Operators

There are three logical operators in Python: and, or, and not

Exercise10: Logical operators

x = True

y = False

print (“When x is True and y is False:”)

print ("x and y is", x and y)

print("x or y is", x or y)

print("not x is", not x)

print("not y is", not y)

Trang 35

Here is a summary of what the logical operators in Python do:

False if the operand is True

Membership operators

There are two membership operators in Python: in and not in They are used

to test whether a variable or value is present in a sequence such as string,dictionary, list, set, or tuple We will learn about these types later on

Exercise11: Membership operators

Trang 36

Exercise12: Identity operators

identical because they are lists and lists are mutable (this means they can be

Trang 37

changed) The interpreter allocates the lists separate memory even when theyare equal.

Here is a table defining what the identity operators do

>> Bitwise right shift

<< Bitwise left shift

Trang 38

Operator Precedence in Python

To evaluate expressions with more than a single operator, Python uses a rule ofprecedence that guides the order in which the operations are executed Forinstance, multiplication has a higher precedence than addition, and additionhigher than subtraction

This rigid order can be changed using parentheses () as it has the highestprecedence The table below lists the precedence of all operators from thehighest to the lowest

Operator Description

3 ~ + - Complement, unary plus +@ and minus -@

4 * / % // Multiply, divide, modulo and floor division

6 >> << Right and left bitwise shift

8 ^ | Bitwise exclusive `OR' and regular `OR'

12 Is, is not Identity operators

13 In, not in Membership operators

14 not, or, and Logical operators

Trang 39

Chapter 4 Python Data Types I: Numbers and Strings

In Python, just as in any other object oriented programming language, everyvalue has a (data) type Everything in Python is an object and data types areconsidered classes while variables are the instances or objects of theseclasses

The function type() is used to determine which class a particular value or variable belongs to and the isinstance() function is used to check whether an

object belongs to a specific class In this section, we are going to look at themost important data types and how to use them in basic programming

Trang 40

Integers, floating point, and complex, defined as int, float, and complex

respectively, are the three classification of numbers in Python A Number as adata type stores numeric values and is immutable, meaning that when the value

of the variable is changed, a new object is allocated

Creating number objects

Number objects (variables) are created when they are assigned values In thefollowing exercise, we will create three objects x, y, and z, when we assignthem values

Exercise13: Number Datatype

print ("is", z, "a complex number?", isinstance(1+2j,complex))

Unlike in most other OOP languages where the length of an integer is limited,

in Python, an integer can be of any length and is only limited by the availablememory in which it is stored

A float, on the other hand, is accurate up to 15 decimal places The differencebetween an integer and a float is a decimal point For instance, in Exercise13,

7 is an integer while 7.0 is a floating point number

Complex numbers in Python are written in the format x + yj where x is the real

part of the number and y is the imaginary part While it is good to know about

Ngày đăng: 05/03/2019, 08:47

TỪ KHÓA LIÊN QUAN