跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
学习Python已有4天令人兴奋的经验。到目前为止,我已经能够涵盖Python的一些基本语法以及数据类型,以及如何使用内置函数和方法以及一些最佳实践对它们执行操作。这可能是枯燥的部分,划伤了Python的表面。今天,我的短期目标是了解逻辑和条件编程以及使用Python中的循环执行重复任务。确实很有趣!
条件逻辑 Conditional Logic
age = input('Please enter your age')
if(int(age) >= 18):
print('You are allowed to enter the club')
else:
print('Sorry! you are not allowed!')
上面是Python中if-else条件语句的示例。它用于根据某些条件执行逻辑。如果不满足条件,则执行else块中的代码。来自JavaScript世界,我注意到的区别是if-else块周围没有花括号,并且:
在条件语句之后使用了a 。条件语句中的代码块也会缩进。我将这两件事连接到了我的Python心理模型。
exam_score = input('Enter your exam score')
if(int(exam_score) > 90):
print('You have got grade A+')
elif(int(exam_score) > 80):
print('You have got grade A')
else:
print('You have got grade B')
如果有多个条件需要执行,则使用一个elif
块。在包括JavaScript在内的许多其他编程语言中,它称为else if
块。可以有任意数量的else if
块来检查不同的条件。Python使它更紧凑。
is_adult = True
is_licensed = True
if(is_adult and is_licensed): ## In JavaScript && is used instead of 'and'
print('You are allowed to drive')
else:
print('You are not allowed to drive')
上面的代码在单个表达式中检查两个条件以执行该块。该and
关键字用于如果双方的条件评估为检查True
然后只执行块。这种语法很容易阅读!Python绝对更具可读性。
缩进 Indentation
缩进是使用空格/制表符分隔代码行的方式,以便解释器可以区分代码块并相应地执行代码。Python不像JavaScript那样不使用花括号,而是使用缩进来对代码块进行分块。通过自动执行缩进,代码编辑器使我们的生活变得轻松。我用作游乐场的在线编辑器Repl也可以做到这一点。
if(10 > 8):
print('Such a silly logic. I will get printed')
else:
print('I will never get printed')
print('I am not get printed coz I am indented')
# Now without indentation
if(10 > 8):
print('Such a silly logic. I will get printed')
else:
print('I will never get printed')
print('I will be printed anyways coz I am not indented')
# The above line gets printed always as interpreter treats it as a new line
真假 Truthy and Falsy
- 评估为真的值称为Truthy
- 评估为false的值称为Falsy
检查条件时,使用类型转换将条件内的表达式评估为布尔值。现在,所有值都被认为是“真实的”,但以下值是“虚假的”:
None
False
0
0.0
0j
Decimal(0)
Fraction(0, 1)
[]
-一个空的list
{}
-一个空的dict
()
-一个空的tuple
''
-一个空的str
b''
-一个空的bytes
set()
-一个空的set
- 一个空的
range
,像range(0)
- 为其对象
obj.__bool__()
退货False
obj.__len__()
退货0
username = 'santa' # bool('santa') => True
password = 'superSecretPassword' # bool('superSecretPassword') => True
if username and password:
print('Details found')
else:
print('Not found')
三元运算符 Ternary Operator
在使用Python中的三元运算符的语法时,我发现它一开始有点令人困惑,但随后发现与我在JavaScript世界中熟悉的相比,它相当易于阅读
is_single = True
message = 'You can date' if is_single else 'you cannot date'
# result = (value 1) if (condition is truthy) else (value 2)
print(message) # You can date
三元运算符有时也称为条件表达式。这是在单个语句中检查条件的一种非常方便的方法。我将其与?
JavaScript 的运算符语法进行了比较,以巩固我的思维模式。
Short-Circuiting
在单个语句中检查多个逻辑条件时,如果第一个条件失败,则解释器足够聪明,可以忽略其余的条件检查。这称为短路。用一个例子可以更好地解释
knows_javascript = True
knows_python = True
if(knows_javascript or knows_python): # doesn't depend on value of knows_python
print('Javscript or python developer')
else:
print('Some other developer')
knows_javascript = False
knows_python = True
if(knows_javascript and knows_python): # doesn't depend on value of knows_python
print('Javscript or python developer')
else:
print('Some other developer')
该or
是python另一个条件运算符。
逻辑运算符 Logical Operators
除此之外 and
,or
也有少数是在Python逻辑运算符,如not
,>
, <
,==
,>=
,<=
,!=
print(10 > 100) # False
print(10 < 100) # True
print(10 == 10) # True
print(10 != 50) # True
print(2 > 1 and 2 > 0) # True
print(not(True)) # False
print(not False) # True
Some quirky operations
print(True == True) #True
print('' == 1) # False
print([] == 1) # False
print(10 == 10.0) # True
print([] == []) # True
==
检查双方的值。如果它们不相似,它将转换类型。
Python具有严格的检查运算符is
,用于检查值及其内存位置。它几乎类似于===
JavaScript中的运算符。
print(True is True) # True
print('' is 1) # False
print([] is 1) # False
print(10 is 10.0) # False
print([] is []) # False
对于循环 For Loops
循环允许多次运行一个代码块。在Python中,循环的基本形式是for
可以遍历可迭代对象的循环。
for item in 'Python': # String is iterable
print(item) # prints all characters of the string
for item in [1,2,3,4,5]: # List is iterable
print(item) # prints all numbers one at a time
for item in {1,2,3,4,5}: # Set is iterable
print(item)
for item in (1,2,3,4,5): # Tuple is iterable
print(item)
可迭代的 Iterable
一个迭代是可以重复的数据的集合。这意味着可以逐个处理集合中的项目。列表,字符串,元组,集合和字典都是可迭代的。对iterable执行的操作是迭代,正在处理的当前项称为iterator。
player = {
'firstname': 'Virat',
'lastname': 'Kohli',
'role': 'captain'
}
for item in player: # iterates over the keys of player
print(item) # prints all keys
for item in player.keys():
print(item) # prints all keys
for item in player.values():
print(item) # prints all values
for item in player.items():
print(item) # prints key and value as tuple
for key, value in player.items():
print(key, value) # prints key and value using unpacking
range
range
是Python中用于生成一系列数字的可迭代对象。它通常在循环中使用并生成列表。范围接受2个和3个可选的3个输入参数启动,停止和步进
for item in range(10):
print('python') # prints python 10 times
for item in range(0,10,1):
print('hello') # prints hello 10 times
for item in range(0, 10, 2):
print('hii') # prints hii 5 times
for item in range(10, 0, -1):
print(item) # prints in reverse order
print(list(range(10))) # generates a list of 10 items
枚举 enumerate
enumerate
当我们在循环时需要迭代器的索引时很有用。
for key, value in enumerate(range(10)): # using unpacking techique
print(f'key is {key} and value is {value}') # prints key and value at the same time
今天就这些。将覆盖循环和函数的其余部分,以Python基础知识结束。
有一天度过了美好的一天towards向着我学习Python的目标又迈出了一步。
跟着我们一起学 Python 30天课程目录:
- 跟着我们一起学 Python 30天课程-第30天-免费Python资源
- 跟着我们一起学 Python 30天课程-第29天-自动化测试
- 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
- 跟着我们一起学 Python 30天课程-第27天-ML和数据科学I
- 跟着我们一起学 Python 30天课程-第26天-机器学习基础
- 跟着我们一起学 Python 30天课程-第25天-Web 开发进阶
- 跟着我们一起学 Python 30天课程-第24天-Web开发基础
- 跟着我们一起学 Python 30天课程-第23天-网页爬虫
- 跟着我们一起学 Python 30天课程-第22天-脚本额外功能Scripting Extras
- 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
- 跟着我们一起学 Python 30天课程-第20天-调试和测试
- 跟着我们一起学 Python 30天课程-第19天-正则表达式
- 跟着我们一起学 Python 30天课程-第18天-文件I / O
- 跟着我们一起学 Python 30天课程-第17天-外部模块External Modules
- 跟着我们一起学 Python 30天课程-第16天-模块基础Module Basics
- 跟着我们一起学 Python 30天课程-第15天-生成器Generators
- 跟着我们一起学 Python 30天课程-第14天-错误处理Error Handling
- 跟着我们一起学 Python 30天课程-第13天-Decorators
- 跟着我们一起学 Python 30天课程-第12天-Lambda Expressions & Comprehensions
- 跟着我们一起学 Python 30天课程-第11天-函数编程Functional Programming基础
- 跟着我们一起学 Python 30天课程-第10天-OOP Missing Pieces
- 跟着我们一起学 Python 30天课程-第9天-OOP Pillars
- 跟着我们一起学 Python 30天课程-第8天-OOP基础知识
- 跟着我们一起学 Python 30天课程-第7天-开发环境搭建(Developer Environment)
- 跟着我们一起学 Python 30天课程-第6天-循环II和函数(Loops II & Functions)
- 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
- 跟着我们一起学 Python 30天课程-第4天-数据类型III(Data Types III)
- 跟着我们一起学 Python 30天课程-第3天-数据类型II(Data Types II)
- 跟着我们一起学 Python 30天课程-第2天-数据类型I(Data Types I)
- 跟着我们一起学 Python 30天课程-第1天-简介
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。