Skip to main content

2-1 資料型態

PRINT:永遠是跟世界打聲招呼的第一個程式

print語法是在print函式中放進你要印的東西,比如 print(我要印這個)。說聲 Hello World,跟程式的世界打聲招呼吧!

 

第一個跟世界打招呼的程式!

print的內容可以是變數(variable): print(a),數字(init): print(1234),或是字串(string): print(‘abc123’)

變數

  • 容器,可以存放資料
  • 變數名稱有區分大小寫!
  • 命名原則:第一個字元必須是英文字,其餘可用英文、數字及底線符號
  • 不能單獨使用保留字當成變數名稱,包括:
  • and   as   assert   break   class   continue   def   del   elif   else   except   exec   finally   for   from   global
    if  import   in   is   lambda   not   or   pass   print   raise   return   try   while   with yield

基本資料型態

變數在程式中,扮演中儲存資料的角色。將資料儲存下來,就可在需要的時候拿出來用。

在程式中,每個變數會有自己的型別。那型別是什麼呢? 簡單來說,型別決定了這個變數可用來儲存什麼樣格式的資料,並且定義了相對應的操作。

簡單舉例,Python中常見的基本型別有:int (整數)、float (浮點數)、str (字串)。

從上述你大概可以知道,如果要今天存放年齡,整數會是不錯的選擇。

身高 & 體重? 浮點數看來不錯。 名字? 字串是不二之選!

不過在Python中,宣告變數並不用事先給定型別,他會依照你給他的初始值來決定變數的型別

 

 

 

 

 

 





資料型態的轉換

 

常用的轉換函數:

int(x) :    把x轉換為整數
float(x) : 把x轉換為浮點數
str(x) :    把x轉換為字串

 

  1. int(x [,base]) Converts x to an integer. The base specifies the base if x is a string.

  2. float(x) Converts x to a floating-point number.

  3. complex(real [,imag]) Creates a complex number.

  4. str(x) Converts object x to a string representation.

  5. repr(x) Converts object x to an expression string.

  6. eval(str) Evaluates a string and returns an object.

  7. tuple(s) Converts s to a tuple.

  8. list(s) Converts s to a list.

  9. set(s) Converts s to a set.

  10. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.

  11. frozenset(s) Converts s to a frozen set.

  12. chr(x) Converts an integer to a character.

  13. unichr(x) Converts an integer to a Unicode character.

  14. ord(x) Converts a single character to its integer value.

  15. hex(x) Converts an integer to a hexadecimal string.

  16. oct(x) Converts an integer to an octal string.

練習題

a="123"
b=456
計算出 a+b = 579

a="123"
b=456
計算出 a+b = 123456

 

讓使用者輸入資料:「input」

 

語法:

字串變數 = input("提示文字")

例如: name = input("請輸入大名:")

會提示使用者輸入一串文字,並儲存到變數name裡面,型態為「字串」,如果要變成數字,可在input的外面加上 int或float函數。

例如:

a = int(input("請輸入一個正整數"))

 

練習:

讓使用者輸入一個數字,計算該數字的平方為多少。