Rapid Python Programming

chapter 2

Strings - Operators - Conditions You already wrote your first string print 'I am learning python'. Next, open up the command prompt or terminal and input the following string into the interpreter print 'It's my python'. You should receive an error. It's because of the extra single quote. Now try it with an escape key called the back slash (): print 'It\'s my python'. If you need a back slash such as in 'the good \ the bad \ the ugly' just add an extra escape key (\).

>>> print 'the good \\ the bad \\ the ugly'.
the good \ the bad \ the ugly

Your scripts might look a little better if you swap between single and double quotes as needed.

>>> print "It's your python"
It's your python

Before we move into triple quotes keep in mind that you can also create a string like 'this'.

>>> 'this'
'this'

We can create the string but we really don’t have to do anything with it. The interpreter will tell you what it is. Next enter the following into the interpreter. (Make sure to enter 3 single quotes before and after). Warning a double quote and single quote together will give a different error.

>>> '''line 1
... line 2'''
'line 1\nline 2'

Notice the (\n) for new line. Try it with print in front of it and it will put the string in two separate lines.

>>> print '''line 1
... line 2'''
line 1
line 2

If you enter “\n” the following string will be displayed on a new line..

>>> print 'I\ngo'
I
go

The results will be the same with >>>”””. Now a raw string with some slight changes. Try it at the interpreter.

>>> r'string'
'string'
>>> r'string\string2'
'string\\string2'
>>> r"string\string2"
'string\\string2'
>>> print r"string\string2"
string\string2
>>> r"""string\string2"""
'string\\string2'
>>> print r"""string\string2"""
string\string2

The last example is to show that you can test your expressions as your scripts progress towards complexity in the future. The string examples above will become more evident as you progress. In section 3.2.3 there is an example of printing a string, integer, or float in a print statement on the same line.

2.1.2 Variables and Assignment

Assignments must begin with either an (upper or lower case) letter or an underscore (). A number can be used after the first letter or underscore. Here are some examples. Please try each one to get a feel for the effect.

>>> var1=1
>>> print var1
1
>>> a=2
>>> print a
2
>>> b,c=3,4
>>> print b,c
3 4
>>> s= 'string'
>>> print s
string
>>> s
'string'

2.1.3 Operators, Order, Indent

These are the most commonly used operators. The rest are listed in the appendix.

Table 2.1 Common Operators

Operator Name Example

+ Plus 2+2 gives 4
- Minus 4-2 gives 2
* Multiplication 2*6 gives 12
/ Division 6/2 gives 12
% Modulus 8%3 gives 2
< Less than 8<4 gives false
> Greater Than 8>4 gives true
<= Less Than or equal 8<=4 gives false
>= Greater Than or equal 8>=4 gives false
== Equal x=2; x==2 gives true
!= not equal x=2; x!=3 gives true
** power 2**2 gives 4, 2**3 gives 8

Type in the following expressions:

>>> 8+8
16
>>> 8-4
4
>>> 4*2
8
>>> 8/2
4
>>> 2+3*8
26
>>> 2/3
0
>>> 2.0/3.0
0.66666666666666663

Notice that in the equation 2+3*8, multiplication comes before addition. You can change this around by using parenthesis (2+3)*8 gives 40. Also notice 2/3 gives 0. Since it's an integer it returns the appropriate integer. If you know that the expression yields a decimal place, then supply it to begin with, otherwise you will corrupt your output.

2.1.4 Pitfalls

You may have noticed with the above examples that you can run into many pitfalls. Truncation, and conversion are the primary causes of corruption. Always test your work first before deployment.

2.1.5 Integer Conversion

>>> number=1234
>>> int(number)
1234
>>> int(12.34)
12
>>> round(12.34)
12.0
>>>oct(number)
'02322'
>>> hex(number)
'0x4d2'
>>> print 2**256
11579208923731619542357098500868790785326998466564
0564039457584007913129639936
>>> x=1234567890
>>> y=3489493838
>>> x+y
4724061728L
>>> x*x
1524157875019052100L
>>> x*y
4308017044747661820L

As you can see, “python” supports large integers out of the box. However you might see the “L” statement as listed in above examples. This really depends on the operating system.

2.1 Conditions and Indentation

2.1.6 Flow Control if/else

help(“if”)

The if statement is used for conditional execution: Please DO NOT type the following.

if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]

2.1.7 For Loop

help(“for”)

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object. The syntax is below:

for_stmt ::= "for" target_list "in" expression_list ": " suite
["else" ":" suite]

2.1.8 While Loop

The while statement is used for repeated execution as long as an expression is true. Again, the syntax is below.

while_stmt ::= "while" expression ":" suite
["else" ":" suite]

2.1.9 Examples

Now we can learn a little about flow and conditions. You can utilize the interactive interpreter, but keep in mind that if you exit out early and connect back later, you will need to reinitialize x=3 again to test out the conditions. The preferred way would be to enter this into a file called “conditions.py”. Using your favorite editor, run it using the following command: “python ./conditions.py”.

Pay ATTENTION to indentation!

x=3
if x < 4:
print "x is less then 4 x is ",x
if (x < 4 or x > 2):
print "x is less then 4 and greater than 2, x=", x
if x == 1:
	print "Item 1 - true value", x
elif x == 2:
	print "Item 2 - true value", x
elif x == 3:
	print "Item 3 - true value", x
else:
	print "Default option if none listed", x
for i in [1,2,3,4,5,6,7,8,9,10]:
	print "Iteration #", i
for i in range(5):
	print i # note this prints up to 4
while (x< 10):
	print "The while iteration is.", x
	x=x+1

Indentation can be either a space or a tab. Whichever you choose will set the level for the rest of the script. After you run “conditions.py” feel free to edit it and change the values. You can remove the indentation and read the errors. With what you have learned you can compute just about any algorithm. Of course input functions, and methods would round out your knowledge and can be found in the next chapter.

2.1.10 Conditions and Indentation

You can utilize the interactive interpreter or continue to use your favorite editor. Enter the following data into a file called “conditions.py”. Pay ATTENTION to indentation!

x=3
if x < 4:
print "x is less then 4 x is ",x # notice the space (is ",x)
if (x < 4 or x > 2):
	print "x is less then 4 and greater then 2, x=", x # notice (x=", x)
if x == 1:
	print "Item 1 - true value", x
elif x == 2:
	print "Item 2 - true value", x
elif x == 3:
	print "Item 3 - true value", x
else:
	print "Default option if none listed", x

The results are:

x is less then 4 x is 3
x is less then 4 and greater than 2, x= 3
Item 3 - true value 3

Standard iteration:

for i in [1,2,3,4,5]:
	print "Iteration #", i

results:

Iteration # 1
Iteration # 2
Iteration # 3
Iteration # 4
Iteration # 5

Iterate a range:

for i in range(5):
	print i # note this prints up to 4

results:

0
1
2
3
4

Notice that it went from 0 to 4. You can change where it starts by setting an additional parameter ↓range(1,5) so it will start with 1 and end with 4.

while (x< 10):
	print "The while iteration is.", x
	x=x+1

The results are: x initialize as 3

while iteration is. 3
while iteration is. 4
while iteration is. 5
while iteration is. 6
while iteration is. 7
while iteration is. 8
while iteration is. 9

Notice that indention is very important and can be either a space or tab. Whichever you choose first sets the key or level for the rest of the script. Please change some of the values in the “conditions.py” to get different results.

2.1.11 Summary

In this chapter you will have learned how strings work, and how to supply a number or string to a variable and operators. With what you have learned so far you can compute just about any algorithm. However things would be easier if functions (methods) are used. This will be discussed in later chapters.

2.1.12 Exercises

Figure 2.1 Formula Temperature

formula for Celsius to Fahrenheit c*(9)/(5+32=x
python code for this would be as simple as (c*9/5+32)
  1. Go through the examples above using the interactive interpreter.
  2. Write a program to calculate 20 degrees Celsius and convert to Fahrenheit.
  3. Continue with previous exercise using variable ’c’ calculate Celsius to Fahrenheit on one line and Fahrenheit to Celsius on another line.
  4. Go through the examples above using the interactive interpreter.
  5. Create a program to print out your name that has been assigned to a variable.
  6. Multiply your name by 5 and create a new line each time the name is printed out.
  7. Continue with the previous exercise and assign the variable of 5 to x and multiply.
  8. Go through the examples above using the interactive interpreter.
  9. Print out a list of temperatures Celsius to Fahrenheit only using c=20, c=25, c=30, c=40.
  10. If the temperature exceeds 90 F print (its hot) if temperate is lower then 70 F print (its cool) otherwise print (its just fine).

To post a comment you need to login first.