日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Python的输入指令、格式化输出、基本运算符

發布時間:2025/4/5 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python的输入指令、格式化输出、基本运算符 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python的輸入指令、格式化輸出、基本運算符

Python的輸入指令input

name = input('Could I know your name please?')

在Python3版本下,輸入的所有內容都視為字符串,所以此時name的類型是字符串。如果輸入年齡,需要進行轉換

age = int(input('Could I know your age please?'))

在Python2版本下,使用input()輸入的內容不會被自動轉成字符串,所以需要在輸入時指定數據類型。

而Python2下的raw_input()等于Python3下的input()

Python的格式化輸出

我們先定義3個變量

name = '李隆基' height = 175 weight = 80
使用占位符輸出信息
print('My name is %s, height is %d cm, weight is %d kg' % (name, height, weight))
使用format輸出
print('My name is {0}, height is {1} cm, weight is {2} kg'.format(name, height, weight))
使用f-string輸出
print(f'My name is {name}, height is {height} cm, weight is {weight} kg')

仔細觀察下列代碼,看看3句print的差別(雖然他們的輸出結果是一樣的)

name = '李隆基' height = 1.75 weight = 80.5 print('My name is %s, height is %.2f m, weight is %.2f kg' % (name, height, weight)) print('My name is {0}, height is {1:.2f} m, weight is {2:.2f} kg'.format(name, height, weight)) print(f'My name is {name}, height is {height:.2f} m, weight is {weight:.2f} kg')

Python的基本運算類型

算術運算符

關于算術運算符,下面的代碼就能說明一切了

x = 11 y = 7 plus = x + y minute = x - y multiply = x * y divide = x / y divide_exactly = x // y mod = x % y exponent = x ** y print(f'plus is {plus}') print(f'minute is {minute}') print(f'multiply is {multiply}') print(f'divide is {divide}') print(f'divide_exactly is {divide_exactly}') print(f'mod is {mod}\nexponent is {exponent}')

比較運算符

代碼的執行結果說明了一切

x = 10 y = 11 print(x == y) print(x > y) print(x < y) print(x >= y) print(x <= y) print(x != y)

賦值運算符

運算后直接賦值的縮寫法

# x = x + y x += y # x = x - y x -= y # x = x * y x *= y # x = x / y x /= y # x = x // y x //= y # x = x % y x %= y

邏輯運算符

老樣子,通過代碼來學習

# and 與運算,所有條件都為True,結果才是True。相當于一串布爾值分別做乘法 print(True and False) print(False and False) print(True and True) # or 或運算,有一個條件為True,結果即True。相當于一串布爾值分別做加法 print(True or False) print(False or False) print(True or True) # not 把True轉成False,把False 轉成True print(not True) print(not False)

身份運算符

通過兩個值的存儲單元(即內存地址)進行比較

is 如果相同則返回True

is not 如果不同則返回True

== 用來判斷值相等,is 是內存地址

換言之,

== 是True,is 不一定是True

== 是False,is 一定也是False

is 是True,== 一定是True

is 是False,== 不一定是False

邏輯有點饒,關鍵是理解

運算符的優先級

平時多用括號,方便別人,方便自己

鏈式賦值

# 若數字一樣時,可以如此 a = b = c = 10 print(a, b, c) # 若數字不同時,可以如此 x, y, z = (10, 11, 12) print(x, y, z)

交叉賦值

變量直接互換,就是這么任性

num_a = 100 num_b = 200 print(num_a,num_b) num_a,num_b = num_b,num_a print(num_a,num_b)

解壓縮

可以快速取出列表中的值,可以使用占位符_ 和 *_

執行一下下面的代碼,效果很棒

boy_list = ['apple', 'banana', 'pear', 'gripe', 'cherry'] a, b, c, d, e = boy_list print(a, b, c, d, e) a, _, _, b, c = boy_list print(a, b, c) a, *_, b = boy_list print(a, b)

轉載于:https://www.cnblogs.com/heroknot/p/10901633.html

總結

以上是生活随笔為你收集整理的Python的输入指令、格式化输出、基本运算符的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。