python sec2

Post on 27-Mar-2016

244 Views

Category:

Documents

4 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

INTRODUCTION TO INTRODUCTION TO PYTHONPYTHONSEC 2SEC 2

1

Eng. Fatma M. Talaat

2

3.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 ("...") with the same result. ( \ ) can be used to escape quotes

3

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes.

The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes.

The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters

4

In Print :(\ ) : Space(\n) : New Line

5

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote.

6

>>> 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." >>> print(hello)

7

Concatenation

>>> word = “Help” + “A”>>> word’HelpA’

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

8

3.3. ListsList 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] = a[2] + 23>>> a[’spam’, ’eggs’, 123, 1234]

9

The built-in function len() also applies to lists:>>> a = [’a’, ’b’, ’c’, ’d’]>>> len(a)4It is possible to nest lists (create lists containing other lists), for example:>>> q = [2, 3]>>> p = [1, q, 4]>>> len(p)3>>> p[1][0]2>>> p[1].append(’xtra’) >>> p[1, [2, 3, ’xtra’], 4]

10

print 'Hello, world!‘print 3, -1, 3.14159, -2.8print int(3.1), int(3.7), int(-3.1), int(-3.7)print float(3), float(-7)

operators + plus addition - minus subtraction * times multiplication / divided by division ** power exponentiation

print 1 + 2, 3 - 4, 5 * 6, 2 ** 5print 1 + 2 ** 3, 4 - 5 / 6, 7 * 8 + 9 * 10

11

Examplemy_name = "Fatma"Print(my_name)

my_age = 24Print(my_age)

my_age += 1Print(my_age)

12

Temperature examples

# convert from Fahrenheit to Celsuis# c = 5 / 9 * (f - 32) # use explanatory names

temp_Fahrenheit = 212temp_Celsius = 5 / 9 * (temp_Fahrenheit - 32)Print(temp_Celsius)

# convert from Celsius to Fahrenheit# f = 9 / 5 * c + 32

temp_Celsius = 100temp_Fahrenheit = 9 / 5 * temp_Celsius + 32Print(temp_Fahrenheit)

THANKS FOR YOUR ATTENTION!

top related