Python学习日记(三)

理解if语句在Python中的应用
本文深入探讨了Python中if语句的基本用法及其多种结构,包括if、if-else和if-elif-else语句。通过实例演示了如何进行条件测试,比较字符串和数字,以及如何检查多个条件。此外,还展示了如何使用if语句进行用户验证。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值