PyLecture1 -Python Basics-

14

Transcript of PyLecture1 -Python Basics-

Page 1: PyLecture1 -Python Basics-
Page 2: PyLecture1 -Python Basics-

Installation

Create easy networks and show them

Page 3: PyLecture1 -Python Basics-

The interactive shell vs scripts

› Running the interactive shell

just type ‘python’

› Running a script

type ‘python <script-name>’ (e.g. python

script.py)

Page 4: PyLecture1 -Python Basics-

Numbers >>> 2 + 2

4

>>> 50 - 5*6

20

>>> (50 - 5.0*6) / 4

5.0

>>> 8 / 5.0

1.6

>>> 5 % 3

2

>>> 2 ** 8

256

› int – the integer values(2, 7, 20…)

› float – the ones with a fractional part(1.0, 3.14…)

› int / int -> int (5 / 3 = 1, not 1.66…)

› int / float -> float, float / int -> float

Page 5: PyLecture1 -Python Basics-

Strings

› Can be enclosed in single quotes (i.e. ‘…’) or

double quotes (i.e. “…”)

>>> “Hello Python!”

‘Hello Python!’

>>> print “Hello”, “Python”, 2.7

Hello Python 2.7

Page 6: PyLecture1 -Python Basics-

Lists – compound data type >>> [1,2,3,5][0]

1 >>> [1,2,3,5][2] 3 >>> [1,2,3,5][-1] 5

>>> [1,2,3,5][2:] [3, 5] >>> [1,2,3,5][:2] [1, 2] >>> len([1,2,3,5])

4 >>> range(4) [0,1,2,3] (Creates a 4-value list starts with 0)

Page 7: PyLecture1 -Python Basics-

The equal sign(=) is used to assign a

value to a variable

>>> width = 5

>>> height = 10

>>> print ‘Triangle area:’, (width * height / 2.0)

Triangle area: 25.0

Page 8: PyLecture1 -Python Basics-

>>> raw_input(‘Please enter something: ’)

Please enter something: <your response>

‘<your response>’ – string type!

>>> x = int(raw_input(‘Enter an integer: ‘))

Enter an integer: -1

>>> x

-1

Page 9: PyLecture1 -Python Basics-

Two methods › the interactive shell › scripts

Basic data types › Numbers

› Strings

› Lists

range() function

Variable Inputs from your keyboard

Page 10: PyLecture1 -Python Basics-

if, elif, else statements >>> x = 42

>>> if x < 0:

… print ‘Negative’

…elif x == 0:

… print ‘Zero’

…else:

… print ‘Positive’

Positive

Page 11: PyLecture1 -Python Basics-

You can skip elif and/or else. >>> if x < 0: … print ‘Negative’

… else:

… print ‘Not negative’

… Not negative

>>> if x > 0:

… print ‘Positive’

Positive

Page 12: PyLecture1 -Python Basics-

for statements >>> words = [‘Mac’, ‘Linux’, ‘Windows’]

>>> for w in words:

… print w

Mac

Linux

Windows

>>>

>>> for i in range(len(words)):

… print words[i]

Page 13: PyLecture1 -Python Basics-

Generates a list with for statement(s)

>>> [4 * x for x in range(5)]

[0, 4, 8, 12, 16]

>>> [4 * x for x in range(5) if x % 2 == 0]

[0, 8, 16]

>>> [4*x*y for x in range(1,3) for y in range(1,3)]

[4, 8, 8, 16]

Page 14: PyLecture1 -Python Basics-

Control flow statements

› if statements

› for statements

List comprehension