导语:
本文主要介绍了关于详解python迭代循环和用户输入的相关知识,包括python循环函数迭代,以及python遍历循环这些编程知识,希望对大家有参考作用。
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)
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Python基础:numpy中有哪些常用函数10/10
- ♥ Python实例属性的优先级分析10/01
- ♥ 如何在python中使用pow函数08/21
- ♥ python中reportgen库的使用和介绍01/03
- ♥ python如何计算夏普比率?09/02
- ♥ pycharm如何配置python环境08/16
内容反馈