if语句
if语句常用于条件测试,返回值为True或False。若条件测试结果为True则执行if语句后的语句,否则忽略这些语句。
主要结构有:if、if-else、if-elif-else
示例程序:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 10:04:16 2019
@author: cc
"""
#if语句
'''检查字符串是否相等'''
requested_topping='mushrooms'
if requested_topping!='anch':
print('Hold the anch')
'''比较数字'''
answer=17
if answer==17:
print("The answer is correct!")
'''检查多个条件'''
#and表示同时满足这些条件
age_0=22
age_1=18
if age_0==22 and age_1==18:
print("Right")
else:
print("Wrong")
#or表示或
num=9
if num>=9 or num<=5:
print(num)
'''if-elif-else'''
alien_color=['red','yellow','green']
if 'red' in alien_color:
print("The player gains 5 points")
elif 'green' in alien_color:
print("The next player")
else:
print("game over")
#示例:检查用户名
current_users=['Alice','John','Tom','Mark','Grace']
new_users=['Jimmy','Grace','JOHN','Hellen','Kart']
for nuser in new_users:
'''title()函数将字符串变为首字母大写'''
if nuser.title() in current_users:
print("Please input another username!")
else:
print("This username is not in use")
运行结果:
Hold the anch
The answer is correct!
Right
9
The player gains 5 points
This username is not in use
Please input another username!
Please input another username!
This username is not in use
This username is not in use