1. Basic use of Python
National Institute of Technology, Anan College, JAPAN
Yoshiki Satotani
2. Start python interactive shell
• (Windows)
• In your explorer, to start
python shell, menu, right
click while pressing shift
key and then, press w
key. And, type python.
• (Mac or Linux)
• Just open your shell and
type python.
5. Basic data types (Strings)
• Type the following commands
• “Hello Python!”
• ‘Hello Python!’
• print ‘Hello’, ‘Python’, 2.7
• In python 3.x, print(‘Hello’, ‘Python’, 3.4)
• ‘Hello’ + ‘Python’ + str(2.7)
• Don’t do this, ‘Hello’ + ‘Python’ + 2.7
• ‘ ‘.join([‘Hello’, ‘Python’, str(2.7)])
6. Basic data types (Lists)
• Type the following commands
• a = [1, 2, 3, 5]
• a[0]
• a[2]
• a[-1]
• a[2:]
• a[:2]
• len(a)
• range(5)
• range(1, 5)
• range(0, 5, 2)
• # in python 3.x, [i for i in range(…)]
7. Basic data types (Dictionary)
• Type the following commands
• tel = {‘John’:8000, ‘Jane’:8001, ‘Joe’:8002}
• tel[‘Jane’]
• tel[‘Joan’] = 8003
• del tel[‘Jane’]
• tel.keys()
• tel.values()
• tel.items()
• names = [‘John’, ‘Jane’, ‘Joe’]
• tel = [8000, 8001, 8002]
• tel = dict(zip(names, tel))
8. Keyboard input
• Type the following commands
• raw_input(‘Input something: ’)
• x = int(raw_input(‘Input an integer: ‘))
• x
9. Function
• Type the following commands
• def Pfunc(n):
• s = 0 # 2 spaces
• for i in range(1, n+1): # 2 spaces
• s = s + I # 4 spaces
• return s # 2 spaces
• print Pfunc(10)
12. If, elif, else
• Type the following commands
• x = 42
• if x < 0:
• print ‘Negative’ # Insert 2 spaces in the head
• elif x == 0:
• print ‘Zero’
• else:
• print ‘Positive’
13. For statements
• Type the following command
• words = [‘National’, ‘United’, ‘University’, ‘Taiwan’]
• for w in words:
• print w
• for i in range(10):
• print i
14. List comprehension
• Type the following commands
• [4 * x for x in range(5)]
• [4 * x for x in range(5) if x % 2 == 0]
• [4 * x * y for x in range(3) for y in range(3)]
16. Graph of a function
• Type the following commands
• import numpy as np
• import matplotlib.pyplot as plt
• x = np.arange(-3, 3, 1.0/100)
• y = x ** 2
• plt.plot(x, y)
• plt.xlabel(r’$x$’)
• plt.ylabel(r’$y=x^{2}$’)
• plt.title(r’Graph of $y=x^{2}$’)
• plt.grid(True)
• plt.show()
17. Histograms
• Type the following commands
• import matplotlib.pyplot as plt
• import random
• x = [random.gauss(0, 1) for i in range(1000)]
• plt.hist(x, bins=25)
• plt.xlabel(‘Rand Norm Num’)
• plt.ylabel(‘Freq’)
• plt.title(‘Norm Dist(n=%d)’ % len(x))
• plt.show()
18. Pie Charts
• Type the following commands
• import matplotlib.pyplot as plt
• labels = [‘DoCoMo’, ‘au’, ‘Softbank’, ‘Emobile’, ‘Wilcom’]
• sizes = [47,27,20,2,3]
• colors = [‘red‘, ‘green’, ‘white’, ‘yellow’, ‘cyan’]
• plt.pie(sizes, labels=labels, colors=colors)
• plt.axis(‘equal’)
• plt.show()