PyLecture1 -Python Basics-
-
Upload
yoshiki-satotani -
Category
Documents
-
view
36 -
download
1
Transcript of PyLecture1 -Python Basics-
Installation
Create easy networks and show them
The interactive shell vs scripts
› Running the interactive shell
just type ‘python’
› Running a script
type ‘python <script-name>’ (e.g. python
script.py)
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
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
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)
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
>>> 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
Two methods › the interactive shell › scripts
Basic data types › Numbers
› Strings
› Lists
range() function
Variable Inputs from your keyboard
if, elif, else statements >>> x = 42
>>> if x < 0:
… print ‘Negative’
…elif x == 0:
… print ‘Zero’
…else:
… print ‘Positive’
…
Positive
You can skip elif and/or else. >>> if x < 0: … print ‘Negative’
… else:
… print ‘Not negative’
… Not negative
>>> if x > 0:
… print ‘Positive’
…
Positive
for statements >>> words = [‘Mac’, ‘Linux’, ‘Windows’]
>>> for w in words:
… print w
…
Mac
Linux
Windows
>>>
>>> for i in range(len(words)):
… print words[i]
…
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]
Control flow statements
› if statements
› for statements
List comprehension