if 语句的一般形式如下,每个条件判断后加冒号:,然后是满足条件后要执行的语句块。在Python我们使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。(补充:Python没有switch-case语句)
if condition_1:
statement_block_1 # Execute if condition_1 is True
elif condition_2:
statement_block_2 # Execute if condition_1 is False & condition_2 is True
elif condition_3:
statement_block 3 # Execute if condition_3 is True and 1 & 2 are False
else:
statement_block_3 # Execute if previous conditions are all Falser
具体例子:
age = 12
if age = 13 and age <= 18:
print(“teenager”)
else:
print(“adult”)
# Boolean check
game_over = True
if game_over:
print('Game Over :(')
alive = False
if alive:
print('Alive')
else:
print('You died :(')
数值比较:
# Numerical comparisons
age = 18
print(age == 18)
# , =
if age <= 21:
print('You can\'t drink!')
if 常用的操作运算符,等号的判断使用的是 ==,=是用来赋值的
操作符
描述
<
小于
<=
小于或等于
>
大于
>=
大于或等于
==
等于,比较两个值是否相等
!=
不等于
字符串相等性比较:
# check for equality
car ='bmw'
print(car == 'bmw')
print(car == 'audi')
# checking for equality is case sensitive
print(car == 'Bmw')
print(car.upper() == 'BMW')
# checking for inequality
if car != 'audi':
print('I want an Audi')
列表遍历 + 条件判断:
# simple example use for and if
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# List checking
cars = ['bmw', 'audi', 'toyota']
if 'bmw' in cars:
print('I will buy the bmw')
programmers = ['enoch', 'fandy']
new_programmer = 'alice'
if new_programmer not in programmers:
print(f"{new_programmer.title()} should also be hired")
多条件判断(不需要括号):
# Checking multiple conditoins
age_1 = 22
age_2 = 18
if (age_1 >= 21) and (age_2 >= 21):
print('You can both drink.')
else:
print('You can\'t drink together.')
# parentheses are not required
if age_1 >= 21 or age_1 >= 21:
print('one of you can drink.')
age_1 >= 21 and age_2 >= 21
if 嵌套
我们可以把if…elif…else结构放入另一个if…elif…else结构中:
num = int(input(“Please input an number: “))
if num % 2 == 0:
if num % 3 == 0:
print(“Your input can be divisible by 2 and 3”)
else:
print(“Your input can be divisible by 2, but cannot be divisible by 3.”)
else:
if num % 3 == 0:
print(“Your input can be divisible by 3, but cannot be divisible by 2.”)
else:
print(“Your input can’t be divisible by both 2 and 3”)
行内表达式,Python中没有类似其他语言的三目操作符:condition?value1:value2,但是有if-else行内表达式:var = var if condition else var 2
height = 180
result = "tall" if height >= 180 else 'short'
print(result)
# Letting the user choose when to quit
prompt = "Enter 'quit' to end the program."
message = ""
while message != 'quit':
message = input(prompt)
print(message)
或者我们使用一个变量当做条件标记,当变量为False时候,循环语句就会自动结束:
# Using a flag
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
我们也可以在语句中使用break,当符合break条件时,就直接结束循环:
# Using break to exit a loop
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd like to go to {city.title()}")
有时我们需要循环能更灵活地执行,我们可以使用continue,直接跳过当前的循环,进入下一次循环:
# Using continue in a loop
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num)
friends = []
prompt = "Enter your friend's name: "
while True:
friend = input(prompt)
if (friend == 'q'):
break
friends.append(friend)
print(friends)
我们也可以使用循环,将一个列表中的元素全部添加到另一个列表中:
# Moving items from one list to another
unconfirmed_users = ['alice', 'brain', 'candace']
confirmed_users = []
while unconfirmed_users:
confirmed_users.append(unconfirmed_users.pop())
for user in confirmed_users:
print(user)
我们还可以通过循环语句,将列表中的某一个特定元素完全删除干净:
# Removing all instances of specific values from a list
pets = ['dog', 'cat', 'dog', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
print(pets)
list = [1, 2, 3, 4, 5, 6]
for i in list:
print(i)
# 内置的序列类型 list, tuple, dict, set 都能迭代
tup = ("Python", 1991)
for i in tup:
print(i)
Range函数
Python中的range函数可以生成一系列的数字:
# range(start, stop)
for i in range(1, 10):
print(i)
# range(stop) start from 0
for i in range(10):
print(i)
# range(start, stop, step)
for i in range(0, 13, 5):
print(i)
# tuple
tup = ('python', 'java', 'c++')
for i in tup:
print(i)
# dictionary
dic = {'language': 'Python', 'version': '3.7.4'}
for key in dic: # key是乱序的:输出和插入的顺序不同
print(key, dic[key])
# set
versions = set(['python2.7', 'python3.0', 'python3.7', 'python2.7'])
for version in versions:
print(version) # 输出结果也不是按照输入的顺序
Python 中的
for
句法实际上实现了设计模式中的
迭代器模式
,所以我们自己也可以按照迭代器的要求创造迭代器对象,以便在
for
语句中使用。 只要类中实现了
__iter__
和
next
函数,那么对象就可以在
for
语句中使用。 以下我们创建 Fibonacci 迭代器对象:
# define a Fib class
class Fib(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
# using Fib object
for i in Fib(5):
print(i)
This Sliding Bar can be switched on or off in theme options, and can take any widget you throw at it or even fill it with your custom HTML Code. Its perfect for grabbing the attention of your viewers. Choose between 1, 2, 3 or 4 columns, set the background color, widget divider color, activate transparency, a top border or fully disable it on desktop and mobile.
Recent Tweets
Newsletter
Sign-up to get the latest news and update information. Don't worry, we won't send spam!
[contact-form-7 id="3145" title="Sliding Bar Form"]