详解python迭代循环和用户输入

Python (208) 2023-06-12 22:35:37

FOR(iteration) 循环

for 循环是 Python 中最常用的迭代机制。Python 中几乎所有的结构都能被 for 迭代。包括列表,元组,字典等。另一种常用的循环是 while 循环,但是 for 循环会是你最常见到的循环。

什么是 while 循环

while 循环会判断一个初始条件,条件成立则执行一次迭代,每次迭代完成后重新判断条件,如果成立则继续迭代,否则退出循环。

通用语法

#Setaninitialcondition.
game_active=True

#Setupthewhileloop.
whilegame_active:
#Runthegame.
#Atsomepoint,thegameendsandgame_activewillbesettoFalse.
#Whenthathappens,theloopwillstopexecuting.

#Doanythingelseyouwantdoneaftertheloopruns.

每次循环前都要初始化一条判断为 true 的条件。

while 循环中包含条件判断。

条件判断为 true 则执行循环内代码,不断迭代,判断。

判断为 false 则退出循环。

示例

#Theplayer'spowerstartsoutat5.
power=5

#Theplayerisallowedtokeepplayingaslongastheirpowerisover0.
whilepower>0:
print("Youarestillplaying,becauseyourpoweris%d."%power)
#Yourgamecodewouldgohere,whichincludeschallengesthatmakeit
#possibletolosepower.
#Wecanrepresentthatbyjusttakingawayfromthepower.
power=power-1

print("\nOhno,yourpowerdroppedto0!GameOver.")

用户输入

在 Python 中你可以利用 input() 函数接受用户输入。函数可以接受一条提示信息,等待用户输入。

通用用法

#Getsomeinputfromtheuser.
variable=input('Pleaseenteravalue:')
#Dosomethingwiththevaluethatwasentered.

示例

如下示例,提示用户输入名字,加入到名字列表中。

#Startwithalistcontainingseveralnames.
names=['guido','tim','jesse']

#Asktheuserforaname.
new_name=input("PleasetellmesomeoneIshouldknow:")

#Addthenewnametoourlist.
names.append(new_name)

#Showthatthenamehasbeenaddedtothelist.
print(names)
THE END

发表回复