註解

In [27]:
# 井字號的後面會被忽略
### 多打幾個井字好也可以

第一個Hello, World程式

In [1]:
print("Hello, World!")
Hello, World!

宣告變數

In [2]:
a = 514
b = 9.2
c = "Hello, World!"
print(a)
print(b)
print(c)
514
9.2
Hello, World!

變數有型態

In [3]:
type(a) #整數 integer
Out[3]:
int
In [4]:
type(b) #小數 (程式中稱作浮點數 float)
Out[4]:
float
In [5]:
type(c) #字串 string
Out[5]:
str

數值變數

In [6]:
a = 5
b = 3

變數運算

In [7]:
print(a + b)
print(a - b)
print(a * b)
print(a / b)   #數學除法
print(a // b)  #無條件捨去除法
print(a ** b)  # a 的 b 次方
8
2
15
1.6666666666666667
1
125

數學函數運算

In [8]:
a = -3
b = 5
print( abs(a) ) # a的絕對值
print( min(a, b) )
print( max(a, b) )
3
-3
5

注意不同型態的運算

In [9]:
a = "123"
b = 123
print( a + b )
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-8dfce689cb17> in <module>()
      1 a = "123"
      2 b = 123
----> 3 print( a + b )

TypeError: Can't convert 'int' object to str implicitly

用 int() str() 轉型

In [10]:
print( int(a) + b)
print( a + str(b))
246
123123

輸入 input()

In [11]:
a = input()
print(a)
123
123

輸入的型態是字串

In [12]:
a
Out[12]:
'123'
In [13]:
a = int(a)  #轉型

輸入的字串有分隔時

In [14]:
a = input().split()
111 222 333
In [15]:
a
Out[15]:
['111', '222', '333']
In [16]:
a, b, c = int(a[0]), int(a[1]), int(a[2])
In [17]:
print(a, b, c)
111 222 333

用 '?' 看說明

In [18]:
abs?
In [19]:
a = "rilak"
a?
In [20]:
a = 123
a?

彩蛋

In [1]:
import antigravity
In [22]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!