Python——条件分支

本文详细介绍了Python中的条件分支结构,包括基本if语句、处理用户输入、if-else结构、if-elif-else多条件判断、if与and、or的组合使用以及条件嵌套。通过实例演示了如何在不同情况下正确使用缩进来避免语法错误,并提到了将用户输入转换为整数以进行比较的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、基本if语句(尤其要注意缩进!)

answer="YES"

answerInput=input("would you like eat pork ?")

if answerInput.upper() == answer.upper():     #技巧:两边使用同样的函数,解决在不能确定大小写或者忘记大小写,                                                                                   #而且无需区分大小写的情况

     print("OK!")

     print("10 yuan!")                  #缩进是必要的!试验去掉缩进的情况!

print("please do yourself!")


answer=input("Would you like express shipping?")

if answer.lower() == "yes" :       #注意最后的 “:”

     print("That will be an extra $10") 

print("Have a nice day")


2、Ctrl+k+c:Python注释多行


3、处理用户输入

deposit=input("How much would you like to deposit? ")

if deposit > 100 :         #错误!str不能和int比较!

     print("You get a free toaster!")

print("Have a nice day")


解决办法(1):

deposit=input("How much would you like to deposit? ")

if int(deposit) > 100 :

     print("You get a free toaster!")

print("Have a nice day")


解决办法(2):

deposit=int(input("How much would you like to deposit? "))

if deposit > 100 :

     print("You get a free toaster!")

print("Have a nice day")


4、if 、else

deposit=input("How much would you like to deposit? ")

if int(deposit) > 100:

    print("You get a free toaster!")

else:

print("Enjoy your mug!")

print("Have a nice day!")


输入50、100、150


 5、if、elif、elif......

country = input("Where are you from? " ) 
if country == "CANADA" :
    print("Hello") 
elif country == "GERMANY" :
    print("Guten Tag") 
elif country == "FRANCE" :
    print("Bonjour")
else :
    print("Aloha/Ciao/G’Day")

6、if    and


6、if    or


7、if     and    or  混合使用!

最好是添加括号,显式区别优先级!或者不要混合使用and、or!

if country == "CANADA"  and  (pet == "MOOSE" or  pet == "BEAVER") :

    print("Do you play hockey too")


8、嵌套

monday = True 

freshCoffee = False 

if monday :     

     if not freshCoffee :

          print("go buy a coffee!")

    print("I hate Mondays")

print("now you can start work")    #尤其注意这些缩进,变换一下,试验一下各种缩进的情况





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值