Python Programming Presentation

From Training Material
Jump to: navigation, search

Reading from the text console

User input can be read from the keyboard with or without a message text. The value returned is always a string:

a = raw_input()
a = raw_input('Please enter a number')

Writing to the text console

The Python print statement is very versatile and accepts almost any combination of strings, numbers, function calls, and arithmetic operations separated by commas.

print 'Hello World'
print 3 + 4
print 3.4
print ”””Text that stretches over
multiple lines.”””
print 'number', 77
print int(a) * 7

String formatting

Variables and strings can be combined, using formatting characters. This works also within a print statement. In both cases, the number of values and formatting characters must be equal.

s = 'Result: %i'%(number)
print 'Hello %s!'%('Roger')
print '(%6.3f/%6.3f)'%(a,b)

The formatting characters include:

  •  %i – an integer.
  •  %4i – an integer formatted to length 4.
  •  %6.2f – a float number with length 6 and 2 after the comma.
  •  %10s – a right-oriented string with length 10.

Escape characters

Strings may contain also the symbols: \t (tabulator), \n (newline), \r (carriage return), and \\ (backslash).

Determining the length of sequences

The len() functions returns an integer with the length b of an argument. It works with strings, lists, tuples, and dictionaries.

l = [0,1,2,3]
print len(l) # → 4

Creating lists of integer numbers

The range function allows to create lists of numbers on-the-fly. There are two optional parameters for the start value and the step size.

l = range(4) # [0,1,2,3]
l = range(1,5) # [1,2,3,4]
l = range(2,9,2) # [2,4,6,8]
l = range(5,0,-1) # [5,4,3,2,1]

Summing up numbers

The sum of a list of integer or float numbers can be calculated by the sum() function.

l = [1,2,3,4]
print sum(l)

Enumerating elements of lists

The enumerate() function associates an integer number starting from zero to each element in a list. This is helpful in loops where an index variable is required.

fruits = ['apple','banana','orange']
for i, fruit in enumerate(fruits):
print i, fruit

Merging two lists

The zip() function associates the elements of two lists to a single list of tuple. Excess elements are ignored.

fruits = ['apple','banana','orange']
prices = [0.55, 0.75, 0.80, 1.23]

for fruit,price in zip(fruits,prices):
print fruit, price