Docsity

the python quick syntax reference, Notas de estudo de Engenharia Elétrica

Toggle sidebar
bg1
Shelve in
Programming Languages/General
User level:
Beginning–Advanced
BOOKS FOR PROFESSIONALS BY PROFESSIONALS®
The Python Quick Syntax
Reference
The Python Quick Syntax Reference is the “go to” book that contains an
easy to read and use guide to Python programming and development. This
condensed code and syntax reference presents the Python language in a
well-organized format designed to be used time and again.
You won’t find jargon, bloated samples, case studies, or history of Hello
World and computer theory in this handy reference. This Python syntax
reference is packed with useful information and is a must-have for any
Python developer.
What You’ll Learn:
• Variables, strings, lists, dictionaries and conditional statements are
and how to use them
• Some of the standard libraries and what they can do to help you
• How to write your own functions
• How to write your first Python program based on terminal Input
and Output
• How to use the Python Interactive Shell
• How to use classes in your Python programs
Walters
9 781430 264781
52499
ISBN 978-1-4302-6478-1
www.apress.com
RELATED
SOURCE CODE ONLINE
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe the python quick syntax reference e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

For your convenience Apress has placed some of the front

matter material after the index. Please use the Bookmarks

and Contents at a Glance links to access them.

xxvii

Introduction

One of the best things that Python offers is an extensive standard library that offers a wide range of included features that range from network functionality, database handling, and XML processing all the way to zip file processing. There are hundreds of additional libraries that extend the abilities of Python. The current versions of Python that are available at this writing are 2.7 and 3.2.5. The reason for this is that version 3.x is NOT completely backward compatible to the earlier versions, and with the wealth of existing code and libraries that are currently being used on a daily basis, both versions are available. You can find these versions at www.python.org for the Windows, Linux/Unix, and Mac OS X operating systems. If you are running Linux, you can check your normal distribution, which will have a version of Python available. It might already be installed on your system. You can do a web search for versions that are available for other operating systems. Although there are many free and for-pay IDEs (Integrated Development Editors) available for Python, all code may be written in a standard text editor and run from the command line in a standard terminal or command box. My personal preference is a free IDE named Geany, which is available for both Linux and Windows. The goal of this book is to provide (as the name suggests) a quick guide to the Python language syntax. Sometimes, a programmer is called on to know multiple languages and the differences from one programming language to another can be just different enough to cause issues. This guide is designed to be kept not on the bookshelf but on the desk, to provide a way to quickly get answers. You’ll find chapters on data structures, keywords, strings, variables, and more. There is even a chapter on some of the more useful standard libraries that come with almost every distribution of Python.

Conventions used in this book

Almost all code presented here will be simple examples showing how to use a particular command or function and can be run in the interpreter shell. The code will look like the following, with the output or response from the shell in bold.

print('This is a test') This is a test

If you see a line of code that starts with “>>>”, that shows the prompt from the interpreter shell. Do not insert that into your code, just the part after it. If you see a line of code that starts with “.. .”, that shows that the shell recognizes this is a line that should be indented. Again, do not insert the dots in your code. Just remember that you have to indent that portion of the code.

Chapter 1

Hello Python

Let’s review a simple Python program that will explain the use of the Python Interactive Shell along with a few tips.

Python’s Interactive Shell

Once you have Python installed on your system, you can use the Interactive Shell to try simple lines of code, debug some problematic code, and even use it as a simple calculator. In a terminal (Linux) or Command Prompt (Windows), simply type:

python

If you are running on Linux, you will see something like this:

Python 2.7.3 (default, Apr 10 2013, 05:09:49) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>>

Or if you are running on Windows, you would see something like this:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win Type "help", "copyright", "credits" or "license" for more information. >>>

As you can see, there is not a lot of difference in the two.

CHAPTER 1 ■ HEllo PyTHon

Save this as ‘hello.py’ whereever you like. I'd suggest you create a subfolder of your home directory to store all your test code, like this:

C: |-Development |-Tests

Now in a command or terminal window, change to the folder you saved the above file in and type:

python hello.py

You should see something like this:

greg@earth:~$ python hello.py Hello. I am a Python program. What is your name? Greg (The program pauses here for you to enter your name) Hello there Greg!

or under Windows:

C:> python hello.py Hello. I am a Python program. What is your name? Greg (The program pauses here for you to enter your name) Hello there Greg!

Decoding the Code

Let’s look at each line of the code.

print 'Hello. I am a Python program.'

The print command will output into the terminal or command prompt box whatever follows. In this case, we are telling Python to display “Hello. I am a Python program.” Notice that what we want displayed is in single quotes in our code. You can use either single or double quotes to enclose the string. However, when you want to show single quotes within a display string, you should use double quotes to enclose the entire string. If you want to display double quotes within a display string, you should use single quotes to enclose the string. We'll discuss this later in Chapter 4.

name = raw_input("What is your name? ")

CHAPTER 1 ■ HEllo PyTHon

Here we are doing two things. First, we are using the raw_input command to tell Python to display a prompt to the user (the “What is your name? “ part) and then wait for the user to input something, even if it is a simple “enter” key to enter a blank input. It is important for you to include the space after the question mark and before the ending quote. This gives a cleaner look for the program, in that the ultimate user has an idea that there is something they need to do. The second thing we are doing is assigning the user’s response to a variable called ‘name’. We will talk more about variables in Chapter 2. For now, think of a variable as a simple box that holds something. In this case, it would hold the name of the user:

print 'Hello there ' + name + '!'

Again, we are telling Python to display a line in the terminal window, but this time we are creating the line out of three strings of text. This is called concatenation. The plus symbol ('+') is used to join the parts of the line together. So we have “Hello there” and the user name and a “!”.

Comments

Comments allow us to put notes within our code. When the interpreter encounters a comment, it ignores the rest of the line. It is considered good practice to comment your code well to explain the thought process behind it. If you ever have to come back to your code after a week or so, the comments will help you remember what you were doing. It also allows other people to understand your code. To create a comment line, simply start the comment with the hash symbol (#). The following lines are example of commented lines:

This is a full line comment.

aVariable = 23 # this is an in-line comment.

It is important to remember that anything following the hash symbol is considered a comment. You can also use triple double quotes (""") to enclose multiline comments.

""" This is an example of a multiline comment. Everything between the sets of triple double quotes is considered a comment. """

Comments also allow us to tell the interpreter to ignore lines of code that might be giving us problems or a block of code that is incomplete.

CHAPTER 2 ■ VARiAblEs

Another alternative is to use underscores in place of spaces:

this_is_an_example_of_a_long_variable_name counter_variable returned_value

Either way is “acceptable.” It mainly depends on what you want to use or what your work uses as a standard. As I stated earlier, it is important for you to use variable names that are “self-documenting.”

Assignment

To assign a value to a variable, use the equal (“=”) sign:

AnInteger = 3 AFloatValue = 3. AString = “The time has come for all good men…” TheList = [1,2,3,4,5]

You can also make multiple assignments of a single value on one line. In the following snippet, the variable ‘a’ is assigned to the value 1. Then the variables ‘b’ and ‘c’ are assigned to be equal to the variable ‘a:’

>>> a = 1 >>> b = c = a >>> print('a=%d, b=%d, c=%d') % (a,b,c) a=1, b=1, c=

Data Types

Python has five “standard” data types: numeric, string, list, tuple, and dictionary.

Numeric

Numeric data types are for storing numeric values. In Python 2.x, there are four types of numeric data, Integers (signed), Long (signed), Float (floating point numbers), and complex numbers. Booleans (0 or 1) are subtypes of integer under version 2.x. The actual range of values that can be stored in any different numeric type will vary from system to system. On my Windows machine, the maximum value for an integer is 2,147,483,647. You can find the actual maximum value for an integer on your system by using the following code in a Python Interactive Shell session:

import sys print sys.maxint 2147483647 (My system)

CHAPTER 2 ■ VARiAblEs

Hexadecimal, octal, and binary numbers also fall under the Numeric data type umbrella. Hexadecimal numbers are base 16. They range from 0 to 9 and A to F. Octal numbers are base 8 numbers. They range from 0 to 7. Binary numbers are base 2 numbers and only include 0 and 1. Examples of each follow:

Hexadecimal - 1B = 27 (decimal) Octal - 033 = 27 (decimal) Binary - 00011011 = 27 (decimal)

String

The string data type is a series of characters that is delimited by quotation marks (either single or double). Strings will be discussed seperately in Chapter 4. An example of strings would include:

'This is a string' "3.14159"

Lists, Tuples, and Dictionaries will be discussed in Chapter 6, but for now here is a quick description.

List

Lists are a way to create multiple values that are referenced by a single variable name with a zero-based index, similar to arrays in other programming languages. Lists use square brackets (“[ ]”) to define them. An example would be:

ColorList = ['Red','Orange','Yellow','Green','Blue','Purple']

ColorList[2] would be the value ‘Yellow.’

Tuple

Tuples are a number of values seperated by commas. The data within a tuple may consist of numbers, strings, and even other objects:

t = 3,42,'The time has come for all good men'

Like lists, tuples are referenced by a zero-based index. t[1] would be the value “42”.

CHAPTER 2 ■ VARiAblEs

complex(real [,imaginary])

Creates a complex number.

>>> complex(3.14159) (3.14159+0j) >>> complex(-123.45) (-123.45+0j) >>> complex(32,43) (32+43j)

str(x)

Returns a string based on the numeric value x. If (x) is not a valid number, this function will return an error.

>>> str(3.14159) '3.14159'

tuple(s)

Returns a tuple based on sequence s. The sequence should be something like a string or a list.

>>> tuple([3,5,7]) (3, 5, 7) >>> tuple('abcd') ('a', 'b', 'c', 'd')

list(s)

Returns a list based on sequence s. The sequence should be something like a string or a tuple.

>>> list((1,2,3)) [1, 2, 3] >>> list('abcd') ['a', 'b', 'c', 'd']

CHAPTER 2 ■ VARiAblEs

set(l)

Returns a set based on sequence l. Sequence l must be a list.

>>> set([7,3,11]) set([11, 3, 7])

dict(s) (s must be sequence of (key,value) tuples)

Returns a dictionary from a list of tuples.

>>> dict([('fname','fred'),('value',1)]) {'value': 1, 'fname': 'fred'}

frozenset(s)

Returns a frozenset created from set s.

>>> s = set([7,3,1]) >>> frozenset(s) frozenset([1, 3, 7])

chr(x)

Returns a character created from integer x in the range of 0 to 255.

>>> chr(65) 'A'

unichr(x)

Returns a unicode character created from integer x in the range (on most machines) of 0 to 0x10000.

>>> unichr(1000) u'\u03e8'

ord(c)

Returns the ascii value of character c.

>>> ord('M') 77

Chapter 3

Operators

Python supports several operators. Here, we review some of the key ones.

Arithmetic Operators

We use the arithmetic operators to do simple math on two variables or literals. Be sure to only try to use arithmetic operators on like types. For example, if you try to add a string value to a integer (3 + “ is a number”) you will get an error.

  • Addition

Adds the left value to the right:

>>> lvariable = 5 >>> sum = lvariable + 3 >>> sum 8

− Subtraction

Subtracts the right value from left:

>>> lvariable = 5 >>> difference = lvariable - 3 >>> difference 2

  • Multiplication

Multiplies left value by right:

>>> lvariable = 5 >>> product = lvariable * 3 >>> product 15

CHAPTER 3 ■ OPERATORs

/ Division

Divides left value by right. Integer divided by integer returns an integer. Right-side value can not be zero:

>>> quotient = 5 / 3 # integer/integer >>> quotient 1 >>> quotient = 5.2 / 3.1 # float/float >>> quotient

>>> quotient = 3.14159 / 7 # float/integer >>> quotient

>>> quotient = 7 / 3.14159 # integer/float >>> quotient

>>> quotient = 5 / 0 Traceback (most recent call last): File "", line 1, in ZeroDivisionError: integer division or modulo by zero

% Modulus

Divides left value by right and returns the remainder:

>>> remainder = 5 % 3 >>> remainder 2 >>> remainder = 3 % 5 >>> remainder 3

** Exponent

Left value raised to the power of the right:

>>> exp = 2 ** 3 >>> exp 8 >>> exp = 2.1 ** 3 >>> exp

CHAPTER 3 ■ OPERATORs

!=

Checks to see if left variable is NOT equal to right (3.x and 2.x):

Python 2.x >>> print(a != b) True Python 3.x >>> print(a != b) True

<>

Checks to see if left variable is NOT equal to right (2.x only):

Python 2.x >>> print(a <> b) True Python 3.x (use !=) >>> print(a <> b) File "", line 1 print(a <> b) ^ SyntaxError: invalid syntax

>

Checks to see if left variable is greater than right:

>>> print(a > b) True

<

Checks to see if left variable is less than right:

>>> print(a < b) False

>=

Checks to see if left variable is greater than or equal to right:

>>> print(a >= b) True

CHAPTER 3 ■ OPERATORs

<=

Checks to see if left variable is less than or equal to right:

>>> print(a <= b) False

Assignment Operators

Assignment operators, as we have seen earlier, assigns and/or modifies a value to a variable.

=

Assignment operator. Assigns the value on right to variable on left:

>>> a = 3 >>> a 3

+=

Add and assign or increment operator. Adds value on right to left variable: >>> a = 3 >>> a += 3 >>> a 6

−=

Subtract and assign or decrement operator. Subtracts value on right from left variable:

>>> a = 3 >>> a -= 2 >>> a 1

*=

Multiply and assign. Multiplies right value to left value:

>>> a = 3 >>> a *= 2 >>> a 6