(翻译)30天学习Python👨‍💻第五天——流程控制和循环1

386 阅读6分钟

30天学习Python👨‍💻第五天——流程控制和循环1

我们已经学习了四天的Python了,到目前为止,我已经介绍了Python的一些基本语法和数据类型,以及如何使用内置函数和方法对它们执行操作,以及一些最佳实践。这可能是Python中比较枯燥的部分,因为只是触及了它的表面。今天我的短期目标是理解逻辑和程序控制语句,以及使用循环执行重复任务。

条件逻辑

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中的条件控制语句。它被用来执行基于某些条件的逻辑。如果条件不满足,另一个条件分支将会执行。与JavaScript相比,我注意到不同的是if-else语句块后面不是花括号{},而是使用:代替。条件中的语句块也是有缩进的。

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): ## 在JavaScript中 and 需要被替换为 && 
  print('You are allowed to drive')
else:
  print('You are not allowed to drive')

上面的代码中在一条表达式中检查两个条件以执行代码块。and关键字用来检查当两个条件结果同时为True时,只有这个代码块会被执行。这样的语法是非常容易阅读的。Python代码更具可读性。

缩进

缩进是用空格/制表符分离代码的方式,解释器会根据缩进区分不同的代码块,执行相应的代码。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')

# 现在没有缩进
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')
# 上面的这一行代码总会被执行,因为它会被当做单独的一行

真值与假值

  • 计算结果为true的值称作Truthy (真值)
  • 计算结果为false的值称作Falsy(假值)

当我们进行条件检查时,条件表达式会利用类型转化计算得到布尔值。下面的值进行类型转化时都是falsy,除此之外都是truthy

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] - 空list
  • {} - 空dict
  • () - 空tuple
  • '' - 空str
  • b'' -空bytes
  • set() - 空 set
  • range, 如range(0)
  • objects 的方法
    • 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')

三元运算符

当我开始接触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中的?对比来巩固我的知识体系。

短路

当我们在一条语句中检查多个条件时,当第一个条件为false时,编译器能够智能的忽略掉剩余的条件。这就是我们所说的短路。下面的这个例子很好的解释了这一点

knows_javascript = True
knows_python = True

if(knows_javascript or knows_python): # 不会检查knows_python的值
  print('Javscript or python developer')
else:
  print('Some other developer')
knows_javascript = False
knows_python = True

if(knows_javascript and knows_python): # 不会检查knows_python的值
  print('Javscript or python developer')
else:
  print('Some other developer')

or是python的另一个条件操作符。可以参考这篇关于短路的文章

逻辑运算符

除了andor,在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

Python运算符

一些奇特的操作

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循环

循环允许多次重复执行一个代码块。在Python中,for是基本的循环方式,它可以遍历iterable(可迭代)对象。

for item in 'Python': # String是可迭代的
  print(item) # 打印出字符串中所有的字符

for item in [1,2,3,4,5]: # List是可迭代的
    print(item) # 一次性打印出所有数字

for item in {1,2,3,4,5}: # Set是可迭代的
    print(item)

for item in (1,2,3,4,5): # Tuple是可迭代的
    print(item)

Iterable(可迭代)

iterable是一组可以进行迭代的数据。这意味着这个集合中的元素可以一个接一个的进行处理操作。列表、字符串、元组、集合和字典都是可以迭代的。在可迭代数据上执行的操作是迭代,当前正在被处理的项称为迭代器。

player = {
  'firstname': 'Virat',
  'lastname': 'Kohli',
  'role': 'captain'
}

for item in player: # 遍历player的键
  print(item) # 打印所有的键

for item in player.keys(): 
  print(item) # 打印所有的键

for item in player.values():
  print(item) # 打印所有的键

for item in player.items():
  print(item) # 打印所有的键和值

for key, value in player.items():
  print(key, value) # 使用解构打印所有的键和值

range

range是Python中的一个可迭代对象,常被用作生成一个范围内的数值。通常用来在循环中生成一个列表。Range接受三个参数,startstopstep,第二和第三个参数是可选的。

for item in range(10):
  print('python') # 打印python十次

for item in range(0,10,1):
    print('hello') # 打印hello十次

for item in range(0, 10, 2):
    print('hii') # 打印hii五次

for item in range(10, 0, -1):
    print(item) # 逆序打印

print(list(range(10))) # 生成一个包含十个元素的列表

枚举

当我们进行循环操作,需要获取迭代器的索引时,enumerate是很有用的。

for key, value in enumerate(range(10)): # 使用解构
  # 译者注:f-string格式化字符串在3.6以后才支持
  print(f'key is {key} and value is {value}') # 同时打印键和值

这就是我们今天的所有内容了。明天将涵盖循环和函数的其他部分,以完成Python基础的学习。

一点花一点时间,一步步完成我们学习Python的目标。

希望你能喜欢这个系列,并且能够从中汲取一些价值。

原文链接

30 Days of Python 👨‍💻 - Day 5 - Conditions & Loops I