1 Python Chapter 3 Reading strings and printing. © Samuel Marateck

Preview:

Citation preview

1

PythonChapter 3

Reading strings and printing.

© Samuel Marateck

2

To write and run a program:1. On the shell’s file menu click New Window2. Type your program.3. Use a # to begin a comment.4. Use the Edit window to edit your program.5. Save your program to the proper directory To save, choose save on the file menu.6. To run your program, click run module on the run menu,

3

When you save your program, type the program’s name a period and then py. ForInstance prog1.py . The program you writeis called the source program. When yourun your program, the compiler produceswhat is called the object program. If you look at the directory, in our case you will seeprog1.pyc; you will not be able to read this.

4

The entity that runs the object program is

called the Python virtual machine.

5

The input() statement

Input to a program is read using theinput() statement and is read as a string,for instance,

name = input(‘Type your input’)

The variable name is a string variable.The string ‘Type your input’ is printed inthe shell when the program is run.

6

Our program is:

#our first program

name = input(‘Type your input ’)

Print(‘Our input is ‘, name)

7

When your run the program, the following

appears in the shell:

>>>

Type your input

You then type anything after the word input.

Type your input NYU rocks

Here we typed NYU rocks.

8

The computer responds:

Our input is NYU rocks

The entire session is shown on the next

slide.

9

>>>

Type your input NYU rocks

our input is NYU rocks

>>>

10

To be able to type the input on another line,

place \n at the end of the string:

name = input(‘Type your input \n’)

11

After you save the program and run it,and type asd as input, the following appears on the shell:

>>> Type your input asdour input is asd>>>

12

The characters \n does not appear in the

shell.; \n is called an escape sequence and

n is called a control character and forces a

a skip to the next line (carriage return).

13

To see the functions that can be used with

a string, type dir(‘’) in the shell. The result is:

14

• >>> dir('')• ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',

'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

• >>>

15

To see the effect of one of these functions,type a string, then a period, then the functionending with (). So>>>’asd’.upper()‘ASD’

upper() converts every letter in the string to uppercase. It leaves all other characters alone.The following are examples of some ofthese functions.

16

lower()Changes uppercase to

Lowercase and leaves all other variables

alone.

Example:

>>>’THE’

‘the’

17

isalpha() Returns True if the string

consists of only letters else False.

Example:

>>> ‘the’.isalpha()

TRUE

>>>’the12’. isalpha()

False

18

capitalize(). Capitalizes a string.

Example:

>>>’asd’. capitalize()

‘Asd’

19

strip() Removes the leading and trailing blanks.

Example:

>>>‘ asd ‘.strip()

‘asd’

20

To convert numeric input to an integer, use

the int() function.

value = input(‘type your integer’)

number = int(value)

print(number + 3)

21

Normally, two print statements print theiroutput on two separate lines, Thusprint(‘abc’)print(‘def’)

Produces>>>abcdef>>>

22

To have the output on one line, end the first

print with end= ‘’

print(’abc’, end = ‘’)

print(‘def’)

produces

>>>abcdef

23

We’ll investigate the following program:

length = 87

width = 5

area = length*width

print(‘area =‘, area)

24

If we wrote prin(‘def’) the computer would

respond with

• Traceback (most recent call last):

• File "<pyshell#0>", line 1, in <module>

• prin('def')

• NameError: name 'prin' is not defined

25

This is another example of a syntax error .

It is also called a compilation error since it

occurs during compilation time.

Such an error must be corrected before the

program will run.

26

The following table describes how the variables are defined.

undef means undefined.

27

statement length width area

length = 87 87 undef undef

width = 5 87 5 undef

area=length*width 87 5 435

print 87 5 435

28

Now let’s analyze:

length = 87width = 5area = length*widthprint(‘area =‘, area)width = 3print(‘area =‘, area)

29

We see that the width has been redefined.

What happens in the computer’s memory

is that the bits in the location width are

reconfigured.

30

statement length width area

length = 87 87 undef undef

width = 5 87 5 undef

area=length*width 87 5 435

print 87 5 435

width = 3 87 3 435

print 87 3 435

31

We see that since the area does not appearon the left side of an assignment statement,it is not redefined and the original valueof the area will be printed. This is called alogical error because it is an error inlogic and will produce the wrong results.You must detect a logical error yourself.

32

In the corrected program we recalculate

the area as is shown in the next slide.

33

length = 87

width = 5

area = length*width

print(‘area =‘, area)

width = 3

area = length*width

print(‘area =‘, area)

Recommended