Subsections

 
3. An Informal Introduction to Python

In the following examples, input and output are distinguished by the presence or absence of prompts (">>" and "... "): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, "#", and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character.

Some examples:

# this is the first comment
SPAM = 1 # and this is the second comment #... and now a third!
STRING = "# This is not a comment."

 
3.1 Using Python as a Calculator

Let's try some simple Python commands. Start the interpreter and wait for the primary prompt, ">>". (It shouldn't take long.)

 
3.1.1 Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example:

>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3

Like in C, the equal sign ("=") is used to assign a value to a variable. The value of an assignment is not written:

>>> width = 20
>>> height = 5*9
>>> width * height
900

A value can be assigned to several variables simultaneously:

>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

>>> 4 * 2.5 / 3.3
3.0303030303030303
>>> 7.0 / 2
3.5

Complex numbers are also supported; imaginary numbers are written with a suffix of "j" or "J". Complex numbers with a nonzero real component are written as "(real+imagj)", or can be created with the "complex(real, imag)" function.

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

Complex numbers are always represented as two floating point numbers, the real and imaginary part. To extract these parts from a complex number z, use z.real and z.imag.

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

The conversion functions to floating point and integer (float(), int() and long()) don't work for complex numbers -- there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part.

>>> a=1.5+0.5j
>>> float(a)
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use e.g. abs(z)
>>> a.real
1.5
>>> abs(a)
1.5811388300841898

In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

>>> tax = 17.5 / 100
>>> price = 3.50
>>> price * tax
0.61249999999999993
>>> price + _
4.1124999999999998
>>> round(_, 2)
4.1100000000000003

This variable should be treated as read-only by the user. Don't explicitly assign a value to it -- you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

 
3.1.2 Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

String literals can span multiple lines in several ways. Newlines can be escaped with backslashes, e.g.:

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
 Note that whitespace at the beginning of the line is\
 significant.\n"
print hello

which would print the following:

This is a rather long string containing
several lines of text just as you would do in C.
 Note that whitespace at the beginning of the line is significant.

Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.

print """
Usage: thingy [OPTIONS] 
 -h Display this usage message
 -H hostname Hostname to connect to
"""

produces the following output:

Usage: thingy [OPTIONS] 
 -h Display this usage message
 -H hostname Hostname to connect to

The interpreter prints the result of string operations in the same way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it's enclosed in single quotes. (The print statement, described later, can be used to write strings without quotes or escapes.)

Strings can be concatenated (glued together) with the + operator, and repeated with *:

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'

Two string literals next to each other are automatically concatenated; the first line above could also have been written "word = 'Help' 'A'"; this only works with two literals, not with arbitrary string expressions:

>>> import string
>>> 'str' 'ing' # <- This is ok
'string'
>>> string.strip('str') + 'ing' # <- This is ok
'string'
>>> string.strip('str') 'ing' # <- This is invalid
 File "<stdin>", line 1
 string.strip('str') 'ing' ^
SyntaxError: invalid syntax

Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.

>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:

>>> word[0] = 'x'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment

However, creating a new string with the combined content is easy and efficient:

>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2] # The first two characters
'He'
>>> word[2:] # All but the first two characters
'lpA'

Here's a useful invariant of slice operations: s[:i] + s[i:] equals s.

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

Indices may be negative numbers, to start counting from the right. For example:

>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # All but the last two characters
'Hel'

But note that -0 is really the same as 0, so it does not count from the right!

>>> word[-0] # (since -0 equals 0)
'H'

Out-of-range negative slice indices are truncated, but don't try this for single-element (non-slice) indices:

>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
 File "<stdin>", line 1
IndexError: string index out of range

The best way to remember how slices work is to think of the indices as pointing betweenCharacters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of nCharacters has index n, for example:

 +---+---+---+---+---+ 
 | H | e | l | p | A |
 +---+---+---+---+---+ 
 0 1 2 3 4 5 
-5 -4 -3 -2 -1

The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. The slice from i to jConsists of all characters between the edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds, e.g., the length of word[1:3] is 2.

The built-in function len() returns the length of a string:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

 
3.1.3 Unicode Strings

Starting with Python 2.0 a new data type for storing text data is available to the programmer: the Unicode object. It can be used to store and manipulate Unicode data (see http://www.unicode.org) and integrates well with the existing string objects providing auto-conversions where necessary.

Unicode has the advantage of providing one ordinal for every character in every script used in modern and ancient texts. Previously, there were only 256 possible ordinals for script characters and texts were typically bound to a code page which mapped the ordinals to script characters. This lead to very much confusion especially with respect to internationalization (usually written as "i18n" -- "i" + 18 characters + "n") of software. Unicode solves these problems by defining one code page for all scripts.

Creating Unicode strings in Python is just as simple as creating normal strings:

>>> u'Hello World !'
u'Hello World !'

The small "u" in front of the quote indicates that an Unicode string is supposed to be created. If you want to include special characters in the string, you can do so by using the Python Unicode-Escape encoding. The following example shows how:

>>> u'Hello\u0020World !'
u'Hello World !'

The escape sequence \u0020 indicates to insert the Unicode character with the ordinal value 0x0020 (the space character) at the given position.

Other characters are interpreted by using their respective ordinal values directly as Unicode ordinals. If you have literal strings in the standard Latin-1 encoding that is used in many Western countries, you will find it convenient that the lower 256 characters of Unicode are the same as the 256 characters of Latin-1.

For experts, there is also a raw mode just like the one for normal strings. You have to prefix the opening quote with 'ur' to have Python use the Raw-Unicode-Escape encoding. It will only apply the above \uXXXXConversion if there is an uneven number of backslashes in front of the small 'u'.

>>> ur'Hello\u0020World !'
u'Hello World !'
>>> ur'Hello\\u0020World !'
u'Hello\\\\u0020World !'

The raw mode is most useful when you have to enter lots of backslashes e.g. in regular expressions.

Apart from these standard encodings, Python provides a whole set of other ways of creating Unicode strings on the basis of a known encoding.

The built-in function unicode() provides access to all registered Unicode codecs (COders and DECoders). Some of the more well known encodings which these codecs can convert are Latin-1, ASCII, UTF-8, and UTF-16. The latter two are variable-length encodings that store each Unicode character in one or more bytes. The default encoding is normally set to ASCII, which passes through characters in the range 0 to 127 and rejects any other characters with an error. When a Unicode string is printed, written to a file, or converted with str(), conversion takes place using this default encoding.

>>> u"abc"
u'abc'
>>> str(u"abc")
'abc'
>>> u"äöü"
u'\xe4\xf6\xfc'
>>> str(u"äöü")
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
UnicodeError: ASCII encoding error: ordinal not in range(128)

To convert a Unicode string into an 8-bit string using a specific encoding, Unicode objects provide an encode() method that takes one argument, the name of the encoding. Lowercase names for encodings are preferred.

>>> u"äöü".encode('utf-8')
'\xc3\xa4\xc3\xb6\xc3\xbc'

If you have data in a specific encoding and want to produce a corresponding Unicode string from it, you can use the unicode() function with the encoding name as the second argument.

>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
u'\xe4\xf6\xfc'

 
3.1.4 Lists

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:

>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']

Unlike strings, which are immutable, it is possible to change individual elements of a list:

>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

Assignment to slices is also possible, and this can even change the size of the list:

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a # Insert (a copy of) itself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]

The built-in function len() also applies to lists:

>>> len(a)
8

It is possible to nest lists (create lists containing other lists), for example:

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']

Note that in the last example, p[1] and q really refer to the same object! We'll come back to object semantics later.

 
3.2 First Steps Towards Programming

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
... 
1
1
2
3
5
8

This example introduces several new features.

See About this document... for information on suggesting changes.

Kevin Carr

Natural Skin Care European Soaps
Kevin Carr
City of Stanton Sales Tax
Internetusers


You can also get Organic Skin Care products from Bliss Bath Body and you must check out their Natural Body Lotions and bath soaps

Now if you are looking for the best deals on surf clothing from Quiksilver and Roxy then you have to check these amazing deals here:

Hey, check out this Organic Skin Care European Soaps along with Natural Lavender Body Lotion and shea butter

And you must check out this website

 

French Lavender Soaps Organic And Natural Body Care Shea Body Butters

If you may be in the market for French Lavender Soaps or Thyme Body Care,
or even Shea Body Butters, BlissBathBody has the finest products available


You can also get Organic Skin Care products from Bliss Bath Body and you must check out their Natural Body Lotions and bath soaps

Now if you are looking for the best deals on surf clothing from Quiksilver and Roxy then you have to check these amazing deals here:

Hey, check out this Organic Skin Care European Soaps along with Natural Lavender Body Lotion and shea butter

This is the website that has all the latest for surf, skate and snow. You can also see it here:. You'll be glad you saw the surf apparel.

Take a moment to visit 1cecilia448 or see them on twitter at 1cecilia448 or view them on facebook at 1cecilia448.


pest Termite Inspection kfi kfwb knx
I saw the best iphone cases on this website best Apple iPhone cases so get on before they are gone.

I bought the ipod touch 4g cases at this page .


I saw the best iphone cases on this website best Apple iPhone cases so get on before they are gone.

I bought the ipod touch 4g cases at this page .



This is the website that has all the latest for surf, skate and snow. You can also see it here:. You'll be glad you saw the surf apparel.

Take a moment to visit 1cecilia448 or see them on twitter at 1cecilia448 or view them on facebook at 1cecilia448.

Orange County Mobile Home Pest Control



The case offers 2300 mAh of power, which is a lot, and it fits into a svelte package. Also like the hawaiian sandal , the Meridian leaves the headphone jack very deeply recessed—but while the Mophie cases ship with a small headphone adapter, the Meridian doesn’t. Like the Freedom 2000, the Power Bank requires that you charge it with your own Lightning cable. So, when you want to use the 1cecilia28 , you need to connect it to your iPhone with your overly long cable, which looks awkward. I don't get it.

The two single-piece hard-shell cases look nice, and the setup with the hawaian Sandals snapped onto it looks sharp, too. But with this case option, you’re really toting around a stand-alone charging unit that happens to fit on the back of your iPhone. Like the Mojo Refuel, it consists of a main battery portion that plugs into your charging case iphone 5 , and a thin frame that snaps down around the front. The backing plastic on the case feels a little cheap in my hand, but I like the look regardless.

The two-layer armor kit involves a solid piece that snaps onto your 1cecilia131 , with a hard rubbery layer that wraps around it, offering impact protection coupled with the case’s battery-boosting ability. The case uses rubbery flaps that protect the headphone jack, the Ring/Silent switch, and the Micro-USB charging port, along with overlays that protect the buttons.
The Grip Power is one of the few hawaiian made sandals I tested that intentionally protrudes beyond the screen—a design that affords a bit of extra protection if you drop the phone and it lands screen-side down. The Micro-USB port on the Grip Power is tucked away on the side, which works fine. You’ll find button overlays for the volume and Sleep/Wake controls, and a tight cutout for the Ring/Silent switch. Because it covers the headphone jack, as the Mophies do, the Grip Power ships with a small headphone extension cord. It uses a 2300-mAh battery, and has a two-piece cap-and-base design that functions a lot like the Mophies do. The DX ships with a small headphone extension cord, too. The not your daughter's jeans outlet makes where the cap and base fit together—it’s too visible. Still, the DX packs a lot of battery power, and it’s easy to put on and take off, so it isn’t a bad option.

I’ve looked at many battery cases or the iPhone5 external battery All of them plug into your iPhone’s Lightning connector, and all of them work basically the same way: You charge the cases up by plugging them into a wall adapter or USB port, and you activate them when you want to start charging up your iPhone’s built-in battery. The best hawaiian made sandals should be easy to toggle on and off, simple to charge, and capable of providing a good indication of how much battery life remains in the case. Oh, and of course, they should provide a lot of extra juice.

On a more subjective scale, I prefer button overlays to cutouts. With the latter design, cases leave holes around the volume buttons, the Sleep/Wake button, and usually the Ring/Silent switch. I find the Sandals from hawaii iPhone’s buttons harder to press through such tiny gaps; I prefer a “surface-level” hardware button that doesn’t require squeezing the tip of my finger into a small space.

Forget about dropped calls and being unable to read your emails because of a dying battery. The nimble battery pack powerful lithium polymer battery cells allow for a thinner and lighter design and Original Samsung Lithium Ion cells, which means our batteries are high quality, unlike many other companies, using generic lithium ion cells. Patented slide-lock mechanism and unique unibody construction allow you to easily install and remove your Quirk-Silva Recall without scratches — unlike typical slider style cases that can damage your phone and fall apart after prolonged use.

Apple claims that the iPhone 6 has slighty better battery life than the ... does its battery last long enough to obviate the need for a 1cecilia60 but it is best to have one anyway.

Termites eat wood, and can consequently cause great structural damage to your home if left unchecked. A typical homeowner's insurance policy does not cover destruction caused by termites, even though they cause over 1 billion dollars in damage to homes throughout the United States each year. Our inspection and treatment program can help you understand the threat of termites, and take the necessary steps to protect your home.

garden grove pest control

westminster pest control

buena park pest control

huntington beach pest control

Orange County Mobile Home Pest Control



Kevin Carr |

HB Sport Surf Clothing

|

Huntington Beach Surf Sport Shop

|


Use jojoba as a skin moisturizer to relieve dry skin. Kevin Carr |


Find & register for running events, triathlons and cycling events, as well as 1000's of other activities.

Orange County Mobile Home Pest Control

Company termite rat pest control los angeles KFI AM 640

pest control stanton

pest control orange county

southern california exterminators los angeles

southern california exterminators stanton

pest control orange county

pest control stanton

Your source for race results for thousands of running events

Fox Head shorts for sale here comfort boot order one now.Today, Fox Racing remains a family owned and operated business, with all four of Geoff and Josie Fox's children working full-time at the company. Ever-growing, Fox Racing is moving bravely into the future with the help and enthusiasm of its 300. Fox Head shirts is at Look at iPhone Cases and this website iPhone Cases and this one too iPhone Case on the website. Buy plumber kfi humu on the web store mark daniels anaheim and AB5 Law. and order a few.

Fox Head t-shirt is on sales at hawaiian shoes on the Internet. While Fox Racing offers its complete line of motocross pants, jerseys, gloves, boots, and helmets through independent motorcycle accessory dealers worldwide, the company also offers a full line of sportswear, including shorts, T-shirts, fleece, hats, jeans, sweaters, sweatshirts and jackets to the public through finer motocross, bike, and sportswear retailers worldwide. Fox Head hydro shorts at this website rideshops and buy a few. During the last three decades, Fox Racing has become an international leader in the sportswear apparel industry with its famous Fox Head logo seen worldwide. In doing so, Fox Racing has held steadfast to Geoff Fox's original goal of making the best motocross products money can buy.