1. 程式人生 > 其它 >Python基礎入門:D2-Task01 從變數到異常處理--阿里雲天池

Python基礎入門:D2-Task01 從變數到異常處理--阿里雲天池

技術標籤:pythonpython

學習地址

https://mp.weixin.qq.com/s/hX5pqGQHqRN_lh9RF74l8g

變數和賦值

在使用變數之前,需要對其先賦值。
變數名可以包括字母、數字、下劃線、但變數名不能以數字開頭。
Python 變數名是大小寫敏感的,foo != Foo

例子

teacher = "老馬的程式人生"
print(teacher)  # 老馬的程式人生
first = 2
second = 3
third = first + second
print(third)  # 5
myTeacher = "老馬的程式人生"
yourTeacher = "小馬的程式人生" ourTeacher = myTeacher + ',' + yourTeacher print(ourTeacher) # 老馬的程式人生,小馬的程式人生

資料型別與轉換

在這裡插入圖片描述

# 例子】通過 print() 可看出 a 的值,以及類 (class) 是int。
a = 1031
print(a, type(a))
# 1031 <class 'int'>

Python 裡面萬物皆物件(object),整型也不例外,只要是物件,就有相應的屬性 (attributes) 和方法(methods)。

b = dir(
int) print(b) # ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', # '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', # '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', # '__getattribute__', '__getnewargs__', '__gt__', '__hash__', # '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
# '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', # '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', # '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', # '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', # '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', # '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', # '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', # 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', # 'numerator', 'real', 'to_bytes']

對它們有個大概印象就可以了,具體怎麼用,需要哪些引數 (argument),還需要查文件。看個bit_length()的例子。

# 【例子】找到一個整數的二進位制表示,再返回其長度。
a = 1031
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11

print() 函式

將物件以字串表示的方式格式化輸出到流檔案物件file裡。其中所有非關鍵字引數都按str()方式進行轉換為字串輸出;
關鍵字引數sep是實現分隔符,比如多個引數輸出時想要輸出中間的分隔字元;
關鍵字引數end是輸出結束時的字元,預設是換行符\n;
關鍵字引數file是定義流輸出的檔案,可以是標準的系統輸出sys.stdout,也可以重定義為別的檔案;
關鍵字引數flush是立即把內容輸出到流檔案,不作快取。

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
# 【例子】沒有引數時,每次輸出後都會換行。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)

# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana