Python基礎(chǔ)之輸入,輸出與高階賦值詳解
1. 輸入、輸出與注釋
1.1 獲取用戶輸入
程序常常需要與用戶進行交互,以獲得用戶提交的數(shù)據(jù)。Python 提供了input 函數(shù),它接受用戶輸入數(shù)據(jù)并且返回一個字符串的引用。
input 函數(shù)接受一個字符串作為參數(shù),該字符串用于作為提示用戶輸入的文本,因此也被稱為提示字符串:
>>> number = input('Enter the number of students: ') Enter the number of students: 52 >>> number '52'
在交互式解釋器中執(zhí)行第一行 number = input('Enter the number of students: '),它打印字符串 "Enter the number of students: ",提示用戶輸入相應(yīng)的信息。此處輸入 52 并按回車,獲取用戶在提示字符串后的輸入后,存儲在 number變量中。需要注意的是 input 函數(shù)返回的值是字符串類型,如果需要將這個字符串轉(zhuǎn)換成其他類型,必須提供相應(yīng)的類型轉(zhuǎn)換,以進行所需操作:
>>> score = input('Enter the total score: ') Enter the total score: 4396 >>> number = input('Enter the number of students: ') Enter the number of students: 52 >>> average_score = int(score) / int(number) >>> average_score 84.53846153846153
1.2 格式化輸出
1.2.1 基本方法
我們在以上示例中,已經(jīng)不止一次看到了 print 函數(shù),其提供了非常簡便打印 Python 輸出的方法。它接受零個或者多個參數(shù),默認(rèn)使用單個空格作為分隔符來顯示結(jié)果,可以通過可選參數(shù) sep 修改分隔符。此外,默認(rèn)情況下每一次打印都以換行符結(jié)尾,可以通過設(shè)置參數(shù) end 來改變:
>>> print('Data', 'Structure', 'and', 'Algorithms') Data Structure and Algorithms >>> print('Data', 'Structure', 'and', 'Algorithms', sep='-') Data-Structure-and-Algorithms >>> print('Data', 'Structure', 'and', 'Algorithms', sep='-', end='!!!') Data-Structure-and-Algorithms!!!>>>
格式化字符串是一個模板,其中包含保持不變的單詞或空格,以及用于之后插入的變量的占位符。 使用格式化字符串,可以根據(jù)運行時變量的值而發(fā)生改變:
print("The price of %s is %d yuan." % (fruit, price))
% 是字符串運算符,被稱作格式化運算符。 表達式的左邊部分是模板(也叫格式化字符串),右邊部分則是一系列用于格式化字符串的值,右邊的值的個數(shù)與格式化字符串中 % 的個數(shù)一致。這些值將依次從左到右地被換入格式化字符串。
格式化字符串可以包含一個或者多個轉(zhuǎn)換聲明。轉(zhuǎn)換字符告訴格式化運算符,什么類型的值會被插入到字符串中的相應(yīng)位置。在上面的例子中,%s 聲明了一個字符串,%d 聲明了一個整數(shù)。
可以在 % 和格式化字符之間加入一個格式化修改符,用于實現(xiàn)更加復(fù)雜的輸出格式:
>>> print("The price of %s is %d yuan." % ('apple', fruits['apple'])) The price of apple is 5 yuan. >>> print("The price of %s is %10d yuan." % ('apple', fruits['apple'])) The price of apple is 5 yuan. >>> print("The price of %s is %+10d yuan." % ('apple', fruits['apple'])) The price of apple is+5 yuan. >>> print("The price of %s is %-10d yuan." % ('apple', fruits['apple'])) The price of apple is 5 yuan. >>> print("The price of %s is %10.3f yuan." % ('apple', fruits['apple'])) The price of apple is5.000 yuan. >>> print("The price of apple is %(apple)f yuan." % fruits) The price of apple is 5.000000 yuan.
1.2.2 format 格式化函數(shù)
上述方式雖然依舊可以使用,但是目前推薦到的另一種解決方案是模板字符串 format,其旨在簡化基本的格式設(shè)置機制,它融合并強化了前一方法的優(yōu)點。使用 format 格式化函數(shù)時,每個替換字段使用花括號括起,其中可以包含變量名,替換字段也可以沒有名稱或?qū)⑺饕米髅Q::
>>> "The price of {} is {} yuan.".format('apple', 5.0) 'The price of apple is 5.0 yuan.' >>> "The price of {fruit} is {price} yuan.".format(fruit='apple', price=price) 'The price of apple is 5.0 yuan.' >>> "The price of {1} is {0} yuan.".format(5.0, 'apple') 'The price of apple is 5.0 yuan.'
從上述示例可以看出,索引和變量名的排列順序無關(guān)緊要。除此之外,還通過結(jié)合冒號 :,從而利用格式說明符(與 % 運算符類似):
>>> value = 2.718281828459045 >>> '{} is approximately {:.2f}'.format('e', value) 'e is approximately 2.72' >>> '{} is approximately {:+.2f}'.format('e', value) 'e is approximately +2.72' >>> '{} is approximately {:0>10.2f}'.format('e', value) 'e is approximately 0000002.72' >>> '{} is approximately {:0<10.2f}'.format('e', value) 'e is approximately 2.72000000' >>> '{} is approximately {:^10.2f}'.format('e', value) 'e is approximately 2.72' >>> '{:,}'.format(100000) '100,000' >>> '{} is approximately {:.2%}'.format('e', value) 'e is approximately 271.83%' >>> '{} is approximately {:.4e}'.format('e', value) 'e is approximately 2.7183e+00' >>> '{} is approximately {:0=+10.2f}'.format('e', value) 'e is approximately +000002.72'
從上述示例中,很容易總結(jié)出,使用 : 號可以指定寬度、精度以及千位分隔符等,^、<、> 分別用于居中、左對齊、右對齊,并且其后可以指定寬度, 并可以使用指定單個字符進行填充,默認(rèn)情況下用空格填充,也可以使用說明符 =,指定將填充字符放在符號和數(shù)字之間。
同樣我們可以使用 b、d、o、x 進行數(shù)據(jù)類型轉(zhuǎn)換,分別是二進制、十進制、八進制、十六進制,c 用于將數(shù)據(jù)轉(zhuǎn)換為 Unicode 碼:
>>> "The number is {num:b}".format(num=1024) 'The number is 10000000000' >>> "The number is {num:d}".format(num=1024) 'The number is 1024' >>> "The number is {num:o}".format(num=1024) 'The number is 2000' >>> "The number is {num:x}".format(num=1024) 'The number is 400' >>> "The number is {num:c}".format(num=1024) 'The number is ?'
1.3 注釋
是時候介紹下注釋了,注釋是提高程序可讀性的一個絕佳方法,也是大家容易忽視的點。Python 不解釋緊跟在 # 符號后面的文本:
radius = 5.0 # 圓的半徑 side = 2.0 # 正方形邊長 # 正方形面積與圓形面積的差 area_c = 3.14 * radius ** 2 area_s = side ** 2 diff = area_s - area_c
如果要使用多行注釋,可以將注釋語句放在一對三雙引號 (""") 或一對三單引號 (''') 之間:
radius = 5.0 side = 2.0 area_c = 3.14 * radius ** 2 area_s = side ** 2 diff = area_s - area_c
2. 高階賦值語句
我們已經(jīng)學(xué)習(xí)了如何給變量賦值,或者給數(shù)據(jù)結(jié)構(gòu)的數(shù)據(jù)元素賦值,但還有其他類型的賦值語句,可以用于簡化代碼,增加代碼的可讀性。
2.1 賦值運算符
除了最基礎(chǔ)的 = 賦值運算符外,也可以將右邊表達式中的標(biāo)準(zhǔn)運算符移到賦值運算符 = 的前,構(gòu)成新的運算符,如 +=、-=、*=、/=、%=等:
>>> number = 1 >>> number += 4 >>> print(number) 5 >>> number //= 2 >>> print(number) 2 >>> number **= 2 >>> print(number) 4 >>> string_1 = 'Hello!' >>> string_1 *= 2 >>> print(string_1) 'Hello!Hello!'
可以這種賦值方式不僅可以用于數(shù)值數(shù)據(jù),也可以用于其他數(shù)據(jù)類型(只要數(shù)據(jù)類型支持所使用的雙目運算符)。
2.2 并行賦值
除了一個一個進行賦值外,可以同時(并行)為多個變量賦值:
>>> a, b, c, d = 0, 1, 2, 3 >>> print(a, b, c, d) 0 1 2 3
通過這種方式,可以簡單的交換多個變量的值:
>>> b, c = c, b >>> print(a, b, c, d) 0 2 1 3
2.3 序列解包
序列解包是將一個可迭代對象解包,并將得到的值存儲到一系列變量中,但要解包的序列包含的元素個數(shù)必須與等號左邊列出的變量個數(shù)相同,否則將引發(fā)異常:
>>> fruit, price = ['apple', 5.0] >>> print(fruit) apple >>> print(price) 5.0 >>> fruit, price, date = ('apple', 5.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: not enough values to unpack (expected 3, got 2) >>> fruit, price = ('apple', 5.0, '2021-11-11') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 2)
為了避免異常觸發(fā),可以使用星號運算符 * 來收集多余的值,這樣便不需要確保值和變量的個數(shù)相同,賦值語句的右邊可以是任何類型的序列,但帶星號的變量最終得到的總是一個列表:
>>> fruits = ['apple', 'orange', 'lemon'] >>> fruit_a, *rest = fruits >>> print(rest) ['orange', 'lemon'] >>> fruits_a, *rest, fruits_b = fruits >>> print(rest) ['orange'] >>> fruits_a, fruits_b, fruits_c, *rest = fruits >>> print(rest) []
2.4 鏈?zhǔn)劫x值
鏈?zhǔn)劫x值可以將多個變量關(guān)聯(lián)到同一個值:
var_1 = var_2 = value
等價于:
var_1 = value var_2 = var_1
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。