教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

Python中for循環(huán)的用法|Pythonfor循環(huán)語句

更新時間:2021年05月19日16時35分 來源:傳智教育 瀏覽次數(shù):

for循環(huán)的作用

Python for循環(huán)可以遍歷任何序列的項目,如一個列表或者一個字符串。

for循環(huán)的基本語法:

for 變量 in 字符串|列表|元組|字典|集合:
    循環(huán)語句


for循環(huán)案例1:

使用for循環(huán)遍歷打印"python"每個字母

for i in "python":
    print(i)


運(yùn)行結(jié)果:

打印Python字符串



for循環(huán)案例2:
使用for循環(huán)求數(shù)字1~100所有整數(shù)之合

result = 0
for i in range(101):
    result += i
print(result)


運(yùn)行結(jié)果:

求1到100的整數(shù)之和


for循環(huán)案例3:
通過for循環(huán)實現(xiàn)階乘

number = int(input('輸入大于0的整數(shù):'))    # 求1*2*……n(用戶輸入)階乘
result = 1
for i in range(1, number+1):                # 使用for循環(huán)實現(xiàn)階乘
    result *= i
print("階乘結(jié)果為:%d" % result)


運(yùn)行結(jié)果:

for循環(huán)實現(xiàn)階乘



猜你喜歡:

python中的for循環(huán)怎么用?

break語句在Python中有什么用途?

Python的if語句多層嵌套怎么使用?

什么是整型?Python整型詳細(xì)介紹

傳智教育Python大數(shù)據(jù)培訓(xùn)課程

0 分享到:
和我們在線交談!