iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 5
0
自我挑戰組

30天搞懂Python系列 第 5

[第05天]30天搞懂Python-基本型態

前言

本文介紹Python基本型態。

基本型態

Python 的內建型態主要分為以下四種:

  1. 數值型態:int, float, complex
import sys
# 整數(int)
i = 99
print(i, "之型態:", type(i))
print("整數最大值:",sys.maxsize)
print("整數最小值:",-sys.maxsize - 1)
#浮點數(float)
f = 99.99
print(f, "之型態:", type(f))
print("浮點數最大值:",sys.float_info.max)
print("浮點數最小值:",sys.float_info.min)
c = 1+2j
print(c, "是複合數?", isinstance(1+2j,complex))

程式執行測試成果:
https://ithelp.ithome.com.tw/upload/images/20200920/201071439Ujs41gKM5.jpg
2. 字串型態:str, chr
chr():把 ASCII 中的數字轉換成字元。

#把 ASCII 中的數字轉換成字元
numASCII = input("請輸入ASCII數字:")
print ("ASCII數字:", numASCII)
print ("字元:", chr(int(numASCII)))

程式執行測試成果:
https://ithelp.ithome.com.tw/upload/images/20200920/20107143HdjTbHf0ml.jpg
3. 容器型態:list, dict, tuple

#List
List = ['a','b','c','d','e','f','g']
print("List:", List)
print("List[3]:", List[3])
#元組
Tuple = (0,1,2,3,4,5,6,7,8,9)
print("Tuple:", Tuple)
print("Tuple[3]:", Tuple[3])
#把元組中第2個~第4個資料(到第4個但不包含第4個)拿出來
print("Tuple[1:3]", Tuple[1:3]) 
#字典
dict = {'age':35, 'name':'Allen', 'Nation':'Taiwan'}
print("dict['name']:", dict['name'])

程式執行測試成果:
https://ithelp.ithome.com.tw/upload/images/20200920/20107143J1jSU4FyER.jpg
4. 布林型態:bool
真:True, 假:False

溫度轉換程式

溫度轉換公式(華氏/攝式)

轉換公式:
celsius * 1.8 = fahrenheit - 32

程式

celsius = float(input('請輸入溫度(攝氏)°C: '))
fahrenheit = (celsius * 1.8) + 32
print('溫度(華氏): %.2f' % fahrenheit,"°F")

程式執行成果

https://ithelp.ithome.com.tw/upload/images/20200920/20107143PacIAOie44.jpg


上一篇
[第04天]30天搞懂Python-DB連線(MongoDB)
下一篇
[第06天]30天搞懂Python-JSON Parser
系列文
30天搞懂Python30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言