python中如何使用if语句

发布时间:2021-07-05 16:02:51 作者:Leah
来源:亿速云 阅读:356

今天就跟大家聊聊有关python中如何使用if语句,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。


if语句:判断语句,根据条件判断是否继续执行


输入:

#!/usr/bin/python 

# Filename: if.py


number = 23 

guess = int(input('Enter an integer : '))


if guess == number:    

    print('Congratulations, you guessed it.') 

# New block starts here    


    print('(but you do not win any prizes!)') 

# New block ends here 


elif guess < number:    

    print('No, it is a little higher than that') 

# Another block    

# You can do whatever you want in a block ... 


else:    

print('No, it is a little lower than that')    

# you must have guess > number to reach here


print('Done') 

# This last statement is always executed, after the if statement is executed 


第一遍运行输出:

 $ python if.py

Enter an integer : 50    

No, it is a little lower than that    

Done 

第二遍运行输出:

 $ python if.py    

Enter an integer : 22

No, it is a little higher than that    

Done

第三遍运行输出:

 $ python if.py    

Enter an integer : 23    

Congratulations, you guessed it.    (but you do not win any prizes!)    

Done 


解释:

上面的执行代码时一个猜数字的小游戏,运行程序后,提示输入一个数字,用户通过在控制台输入数字来执行猜数字。


if语句在这里起判断作用,如果条件满足(即猜的数字相等)就提示猜对。

如果条件没满足会执行if条件的分支语句elif,

2级判断:猜的数字太小了

如果条件仍然没满足,继续会执行if条件的分支语句elif,3级判断:猜的数字太大了


所有可判断的条件执行完毕,输出结果。


输入一个数字进行if条件判断,只会有1种输出:要么是相等提示,猜对;要么是大了;要么是小了。

输入:

if True:    

print('Yes, it is true') 

输出:

Yes, it is true

解释:

if语句结构

if 条件 :

    print(“内容”)


注意上面的冒号,以及冒号后的语句缩进。


看完上述内容,你们对python中如何使用if语句有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. Python中elif语句的使用方法
  2. python中if语句的写法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:如何解决jsp中的rar文件连接乱码问题

下一篇:Python中怎么实时显示进度条

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》