当前位置: 首页 > Python编程 > Python编程实战技能 > Python编程基础入门 > 详解python迭代循环和用户输入

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

发布时间:2020年09月27日 08:27:20 来源: 点击量:591

【摘要】FOR(iteration) 循环for 循环是 Python 中最常用的迭代机制。Python 中几乎所有的结构都能被 for 迭代。包括列表,元组,字典等。另

FOR(iteration) 循环

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

什么是 while 循环

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

通用语法

# Set an initial condition.
game_active = True

# Set up the while loop.
while game_active:
    # Run the game.
    # At some point, the game ends and game_active will be set to False.
    #   When that happens, the loop will stop executing.
    
# Do anything else you want done after the loop runs.

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

while 循环中包含条件判断。

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

判断为 false 则退出循环。

示例

# The player's power starts out at 5.
power = 5

# The player is allowed to keep playing as long as their power is over 0.
while power > 0:
    print("You are still playing, because your power is %d." % power)
    # Your game code would go here, which includes challenges that make it
    #   possible to lose power.
    # We can represent that by just taking away from the power.
    power = power - 1
    
print("nOh no, your power dropped to 0! Game Over.")

用户输入

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

通用用法

# Get some input from the user.
variable = input('Please enter a value: ')
# Do something with the value that was entered.

示例

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

# Start with a list containing several names.
names = ['guido', 'tim', 'jesse']

# Ask the user for a name.
new_name = input("Please tell me someone I should know: ")

# Add the new name to our list.
names.append(new_name)

# Show that the name has been added to the list.
print(names)

分享到: 编辑:wangmin

就业培训申请领取
您的姓名
您的电话
意向课程
点击领取

环球青藤

官方QQ

扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群

绑定手机号

应《中华人民共和国网络安全法》加强实名认证机制要求,同时为更加全面的体验产品服务,烦请您绑定手机号.

预约成功

本直播为付费学员的直播课节

请您购买课程后再预约

环球青藤移动课堂APP 直播、听课。职达未来!

安卓版

下载

iPhone版

下载
环球青藤官方微信服务平台

刷题看课 APP下载

免费直播 一键购课

代报名等人工服务

课程咨询 学员服务 公众号

扫描关注微信公众号

APP

扫描下载APP

返回顶部