python基礎(三)--數據類型

打印數據類型:type

>>> a=1
>>> print(type(a))
<class 'int'>
  • int():將一個數值或字符串轉換成整數,可以指定進制。
  • float():將一個字符串轉換成浮點數。
  • str():將指定的對象轉換成字符串形式,可以指定編碼。
  • chr():將整數轉換成該編碼對應的字符串(一個字符)。
  • ord():將字符串(一個字符)轉換成對應的編碼(整數)。

整除

  • 自然除法/:能整除則整除,不能整除以浮點數的方式返回結果
  • 地板除法//:對不能整除的向下取整
  • 取整函數int:對於整數直接返回原值,對於浮點數返回其整數部分
  • 四捨五入取偶函數round():對於整數直接返回原值,對於浮點數,進行四捨五入,並且向偶數取整。另外both round(0.5) and round(-0.5) are 0, and round(1.5) is 2
  • 向下取整floor():見名知意,當結果在這些區間時(-1,1)取0;(1,2)取1;(n,n+1)取n;(-n,-n-1)n>0取-n-1
  • 向上取整ceil():用法與floor相反,並且都需要導入math模塊
>>> 1/2  #0.5
>>> 1/3  #0.3333333333333333
>>> 1//2 #0
>>> 1//3 #0
>>> 7//2 #3
>>> -7//2 #-4
>>> -(7//2) #-3
>>> int(1.9999) #1
>>> int(1.0)  #1
>>> round(1.5) #2
>>> round(-1.5) #-2
>>> round(0.5)  #0
>>> round(0.500001) #1
import math
math.floor(1.9999)  #1
math.floor(1.0)     #1
math.floor(-3.4)    #-4
math.ceil(2.1)      #3
math.ceil(-2.999)   #2

常用的數值處理函數

min() :對象可以是可迭代對象或者是一列對象
max() :
pow(x,y):冪運算,x**y(x的y次方)
math.sqrt(x):開方運算x**0.5
bin():將十進制整型數值轉換位二進制,返回字符串,類似於'0b1010'
oct():將十進制整型數值轉換爲八進制,返回字符串,類似於'0o12'
hex():將十進制整型數值轉換爲十六進制,返回字符串,類似於'0xa'
math.pi:引用π的值
math.e:引用e的值
另外還有對數函數和三角函數等

類型轉換

a=int(input('a= '))
b=int(input('b= '))
print('%d + %d = %d' % (a,b,a+b))

賦值運算與複合賦值運算

a = 10
b = 3
a += b # 相當於:a = a + b
a *= a + 2 # 相當於:a = a * (a + 2)
print(a) # 想想這裏會輸出什麼

比較運算符與邏輯運算

flag0 = 1 == 1
flag1 = 3 > 2
flag2 = 2 < 1
flag3 = flag1 and flag2
flag4 = flag1 or flag2
flag5 = not (1 != 2)
print('flag0 =', flag0) # flag0 = True
print('flag1 =', flag1) # flag1 = True
print('flag2 =', flag2) # flag2 = False
print('flag3 =', flag3) # flag3 = False
print('flag4 =', flag4) # flag4 = True
print('flag5 =', flag5) # flag5 = False
print(flag1 is True) # True   由於flag1是真,因此括號中的爲真,所以輸出True
print(flag2 is not False) # False

將華氏溫度轉換爲攝氏溫度

F=float(input('請輸入華氏溫度:'))  #默認input獲取到的輸入是string類型,因此這裏需要進行顯式轉換
f=(F - 32) / 1.8
print('攝氏溫度爲:%.3f' % (f))  #%.3f默認保留三位小數

計算圓的面積和周長

import math
r=float(input('請輸入圓的半徑:')) #顯式轉換
S=math.pi*r**2
L=2*math.pi*r
print('圓的面積爲:%.3f' % S) 
print('圓的周長爲:%.3f' % L)

計算年份

year=float(input('請輸入年份:'))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print('%d is a special Year' %  year)
else:
    print('%d is not a special Year' % year)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章