Python 30 天 – 第 6 天 – 循环 II 和函数
编写Python代码的乐趣应该是看到简短、简洁、可读的类,这些类在少量清晰的代码中表达了大量的操作,而不是在令读者厌烦至死的大量琐碎代码中。
我在玩一些代码的同时继续探索更多的循环。然后我继续学习编程中最重要的事情之一,函数。我详细了解了 Python 中的函数和方法、文档字符串、最佳实践以及范围。我会尽量用清晰和简单的术语来解释。
循环继续
While 循环
While 循环是另一种根据特定条件多次运行代码块的方法。在处理 while 循环时,我们需要小心一点,以免意外地创建一个无限循环,该循环会一直执行,直到它们使我们的系统崩溃!
hungry = True while(hungry): # This is always true so it keeps printing until system crashes! print('Give me something to eat!!')
但是 while 循环很酷。它们容易编写且容易阅读。我们只需要告诉解释器什么时候停止循环。它可以通过使用 break 语句停止循环执行并中断循环或通过使条件为 false 来停止执行来完成。
hungry = True
while(hungry):
print('Give me something to eat!!')
break # prints only once and stops the loop execution
hungry = True satisfaction = 0
while(satisfaction < 10):
satisfaction += 1
print('Give me something to eat!!') # prints 10 times
while 循环的另一个特点是它可以与 else 块结合使用。
快速编码练习
让我们在电子邮件列表中找到重复的电子邮件并打印出来。
email_list = ['roger@hey.com','michael@hey.com','roger@hey.com','prince@gmail.com']
duplicate_emails = []
for email in email_list:
if email_list.count(email) > 1 and email not in duplicate_emails:
duplicate_emails.append(email)
print(duplicate_emails)
这就是我解决问题的方法。请在评论中告诉我您将如何解决它。好吧!是时候切换到一个有趣的话题了,函数。
Functions
函数是一个非常重要的概念,它们存在于所有编程语言中。函数允许我们定义一个动作(代码块),然后按照 DRY 的原则重复执行任意次数的动作。到目前为止,我一直在使用 Python 提供的一些内置函数,例如 print、input、len 等。是时候创建一个了。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!