Python Basics

Expressions and Statements

An expression is a combination of values and operations that creates a new value, which we call a return value—i.e., the value returned by the operation(s). A statement does not return a value, but does perform some task. A statement may have a side effect. Evaluation of a Python expression may not produce a side effect. An expression has a value, but a statement does not!

Tokens

Special Python elements (e.g., keywords, operators, punctuators and delimiters, literals)

Every name must begin with a letter or the underscore character (`_`):

  • – A numeral is not allowed as the first character.
  • – Multiple-word (`hello_world`)

After the first letter, the name may contain any combination of letters, numbers, and underscores:

  • – The name cannot be a keyword as listed in Table 1.1.
  • – You cannot have any delimiters, punctuation, or operators (as listed in Tables 1.2 and 1.3) in a name.

Name is case sensitive

A _variable_ is a name you create in your program to represent “something” in your program. It can be one of many types of entities: a value, another program to run, a set of data, a file. Once a variable is created, you can store, retrieve, or modify the data associated with that variable. In Python, integers can grow to be _as large as needed _to store a value. never lead int with a 0. {x = (u + v) + w, y = u + (v+ w) }if abs(x – y)

int(‘1.1’) # float as a str to int, too far! conversion does not change my var
False = any objects with value of zero, empty string; True = any objects with no-zero value; ‘1’

not p
– The not operator flips the value of the Boolean operand. That is, it converts True to False and False to True. 

r p and q

– The and operator requires both p and q to be True for the whole expression to be True. Otherwise, the value of the expression is False. Observe that the four rows in the p and q columns represent all the possible combination values that the Booleans pand q can have. You should take a moment and convince yourself of that observation.

or q
– The or operator only requires one of p or q to be True for the whole expression to be True. Therefore, the expression is False only when neither p nor q is True.
(0 and (a int (0 and (5 True and True
True

Order of operations: and before or:(X > 2) or (X > 5) (x=3)

(3>2) or (3>5) 

True or False 

True

True and False or True and False 

(True and False) or (True and False) 

False or False
False

4

(4 and (5 == True)

True and False

False

The basic idea of a set of ifelifelse statement is to find the first True condition in the set of if and elif headers and execute that associated suite. If no such Truecondition is found, the else is executed. The important point is that only one suite will be executed. if, if, if, if, else vs. if, elif, else

while- else: Similar to the ifelse statement, you can have an else clause at the end of a whileloop. The else is strictly optional, but it does have some very nice uses.

while boolean expression:# suite1

else:
# suite2

The else clause is entered after the while loop’s Boolean expression becomes False. See Figure 2.9. This entry occurs even if the expression is initially False and the whileloop never ran (its suite was never executed). As with other header statements, the elsepart of the while loop can have its own associated suite of statements. Think of theelse statement on the while loop as “cleanup” for the action performed as the loop ends normally.

The else clause is a handy way to perform some final task when the loop ends normally. Figure 2.9 shows how the else works.

The for statement was introduced in an earlier section. Just like the while statement, the for statement can support a terminal else suite, as well as the control modifierscontinue and break. Their roles are as previously described, that is:

  1. The else suite is executed after the for loop exits normally.

  2. The break statement provides  an immediate exit of the for loop, skipping the else clause.
  3. The continue statement immediately halts the present iteration of the loop, continuing with the rest of the iterations.

It is possible to write a while loop that behaves exactly like a for loop. However, not every while loop can be expressed as a for loop.

Consider this simple for loop using the sequence generated by range(5):for in range(5):

print(i)
We can write an equivalent while loop as:

i=0
while i

print(i) i += 1

Nesting, an loop inside a loop

\n-return \t – tab

hello str = “Hello World”

hellostr[::2]

‘HloWrd’

hello str[::3]

‘HlWl’

hello str[::-1]

‘dlroW olleH’

hello str[::-2]

‘drWolH’

>>> digits = “0123456789”

digits[1::2]

‘13579’

digits[-2::-2]

 ‘86420’

>>> name one = ‘Monty’ >>> name two = name one[:] >>> name two
‘Monty’

Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.

A string is indeed an iterable data type, and you can iterate through the individual elements of a string using a for loop.

String Operation:

A couple of points of interest:

Both the + and * create new string objects and do not affect the strings in the expres- sion. That is, a str + ‘a’ does not change the contents of a str. Neither doesa str * 3.

In concatenation, there is no space introduced between the end of the first and the beginning of the second string, unless you include it explicitly.

The order of the two string objects does matter in concatenation. The first string shows up at the beginning of the new string object; the second string at the end. Changing the order changes the order in which the strings occur in the new string object.

The order of the string and integer in replication does not matter.
The types needed for each operator are very specific. For concatenation, you need two string objects. For replication, you need one string and one integer. No other

combinations of types are allowed for each operator.

Single-Character String Compares

Let’s start easy and work with only single-character strings. You can compare two single- character strings using the equality operator ==, as in ‘a’ == ‘a’. If the two single characters are the same, the expression returns True. Note that the expression ‘a’ == ‘A’returns False as those are indeed two different strings.

What about the greater than (>) or less than ( ‘a’, which is obviously False. What is the result of ‘a’ > ‘A’? If you type it into the shell, you will get the result True. Why? We introduced the functions ord and chrin Section 4.1.3. These two functions help us relate a character and its integer representation in the Unicode UTF-8 table. All comparisons between two single characters are done on the basis of their UTF-8 integer mapping. When we compare ‘a’ > ‘A’, Python fetches the associated UTF-8 number for both characters and compares those two numbers. Because ord(‘a’) is 97 and ord(‘A’) is 65, the question becomes whether 97 > 65, which yields True. Conveniently, the lowercase letters are all sequentially ordered, so that’a’

Comparing Strings with More than One Character

When strings with more than one character are compared, the process is slightly more complicated, though still based on the concept of a character’s UTF-8 number.

String comparison—in fact, any sequence comparison—works as follows. The basic idea is to, in parallel, examine both string characters at some index and then walk through both strings until a difference in characters is found.

  1. Start at index 0, the beginning of both strings.

  2. Compare the two single characters at the present index of each each string.

    If the two characters are equal, increase the present index of both strings by 1 and go back to the beginning of step 2.

    If the two characters are not equal, return the result of comparing those two characters as the result of the string comparison.

  3. If both strings are equal up to some point but one is shorter than the other, then the longer string is always greater. For example, ‘ab’

    The following session shows some examples:

>>>’abc’# different at index 0, ‘a”c’True
>>>’abc’# different at index 2, ‘c”d’True

>>>’abc’# ‘abc’ equal up to ‘d’ but shorter than ‘abcd’True
>>>”# the empty string’s length is 0, always smallerTrue

The empty string (“) is always less than any other string, because it is the only string of length 0.

It is an interesting challenge to write a string-comparison algorithm using only single- character compares. See the exercises.

The in operator is useful for checking membership in a collection. An example of its use is’a’ in ‘abcd’. The operator takes two arguments: the collection we are testing and the element we are looking for in the collection. As it applies to strings, the operator tests to see if a substring is an element of a string. As it is a membership check, it returns a Boolean value to indicate whether the first argument is a member (can be found in) the second argument. For the previous example, the return value is True. The test string sequence must be found exactly. For example, in ‘ab’ in ‘acbd’, the question being asked is whether the exact sequence ‘ab’ occurs anywhere in the string. For this example, the return value is False. Like most of these operators, in can be used with other collections, in which the interpretation of membership depends on the collection type. Here is a session showing some ways to use the in operator:

>>> vowels = ‘aeiou’ >>> ‘a’ in vowels True
>>> ‘x’ in vowels False

>>> ‘eio’ in vowels

True
>>> ‘aiu’ in vowels False
>>> if ‘e’ in vowels:

print(“it’s a vowel”) it’s a vowel

String collections are immutable

instead :>>> my str = ‘Hello’

>>>mystr=’J’+mystr[1:]# create new string with ‘J’ and a slice
>>> my str # my str is now associated with the new string‘Jello’

Consider the len function. The len function is used to find a string’s length, the number of individual characters in a string. You use a function just like any other command in Python. The function is invoked, or called, when the interpreter reaches the function name in a program. A function name is always followed by a set of parentheses, indicating that the name represents a function. Within the parentheses are zero or more arguments. Arguments are values that are passed to the function so the function can accomplish its task. If the function requires multiple arguments, a comma is placed between each object in the argument list. After the function completes its processing, it may return some value that can be saved by an assignment or other operation.

method is a variation on a function.Every method is called in conjunction with a particular object. The kinds of methods that can be used in conjunction with an object depends on the object’s type. String objects have a set of methods suited for strings, just as integers have integer methods, and floats have float methods. The invocation is done using what is called the dot notation. An example would be the string typeupper method. An example invocation would be ‘A String’.upper(). In this case, the object, the string ‘A String’, is calling the associated method upper. This method takes the associated object and creates a new string where all the letters are converted to uppercase, in this case the string object ‘A STRING’. The interpretation of this invocation, in plain English, would be something like: The object ‘A String’ is calling the methodupper on itself to create a new string, an uppercase version of the calling object. An example session for the method upper is shown here:

>>> my str = ‘Python rules!’ >>> my str.upper()
‘PYTHON RULES!’

Nesting of Methods

You can also use method and function invocations as arguments to another method call. This kind of “method in a method” is called nesting. The rule for nested calls is that all invocations inside parentheses, such as those found in a function invocation, are done first. For example, how could you find the second occurrence of a substring? You do so by nesting one call of find as an argument of a find invocation in the following way. Suppose you wish to find the second ‘t’. The first step is to find the first ‘t’. The second step begins with a search (a second invocation of find) starting from one past the location where the first ‘t’ is found. That is, find the index of the first ‘t’, add 1 to that index, and use that value as the starting point for a search for the second ‘t’. That is,

                    a string.find('t', a string.find('t')+1)

The nested method invocation is called first, yielding 7 + 1 = 8. The outer invocation then begins by searching for ‘t’ starting at position 8. A session illustrating this process follows:

>>> a str = ‘He had the bat.’
>>> a str.find(‘t’) # look for ‘ t ‘ starting at beginning
7
>>> a str.find(‘t’,8) # start at index 8 = 7 + 1
13
>>>astr.find(‘t’,astr.find(‘t’)+1)# start at one after the first ‘t’

13

The general structure of the most commonly used parts of the format command is:2

{:[align] [minimum width] [.precision] [descriptor]}

where the square brackets, [ ], indicate optional arguments. It is important to note the placement of the colon. All the optional information comes after a colon in the braces.

The different types are described in Table 4.3. There are actually 10 possible format commands—we will cover the others later.

>>> print(“{} is {} years old”.format(“Bill”,25))
Bill is 25 years old.
>>> print(“{:>10sis {:} years old”.format(“Bill”,25))

       Bill is 25          years old.
Formatting is useful for aligning values when printing tables, as illustrated in the next

session:

>>> print(‘{0:.>12s{1:0=+10d{2:->5d}‘.format(‘abc’,35,22)) ………abc | +000000035 | —22

>>> print(‘{:6.2f}‘.format(3.4567)) 3.46

>>> print(‘{:6.1f}‘.format(3)) 3.0

>>> print(‘{:6.0f}‘.format(3)) # zero precision3

>>> print(‘{:6f}‘.format(3)) # no precision ( default precision )3.000000
>>> print(‘{:#6.0f}‘.format(3)) # decimal point forced

3.

>>> print(‘{:04d}‘.format(4)) # zero preceeds width0004
>>> print(‘{:,d}‘.format(1234567890))
1,234,567,890