码迷,mamicode.com
首页 > 编程语言 > 详细

python学习进度4(条件判断)

时间:2020-02-07 01:28:51      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:读取   call   --   同学会   一个   意思   自己   order   完整   

------------恢复内容开始------------

计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。

比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现:

age = 20
if age >= 18:
    print(‘your age is‘, age)
    print(‘adult‘)

根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print语句执行了,否则,什么也不做。

也可以给if添加一个else语句,意思是,如果if判断是False,不要执行if的内容,去把else执行了:

age = 3
if age >= 18:
    print(‘your age is‘, age)
    print(‘adult‘)
else:
    print(‘your age is‘, age)
    print(‘teenager‘)

注意不要少写了冒号:

当然上面的判断是很粗略的,完全可以用elif做更细致的判断:

age = 3
if age >= 18:
    print(‘adult‘)
elif age >= 6:
    print(‘teenager‘)
else:
    print(‘kid‘)

elifelse if的缩写,完全可以有多个elif,所以if语句的完整形式就是:

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
else:
    <执行4>

最后看一个有问题的条件判断。很多同学会用input()读取用户的输入,这样可以自己输入,程序运行得更有意思:

birth = input(‘birth: ‘)
if birth < 2000:
    print(‘00前‘)
else:
    print(‘00后‘)

输入1982,结果报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

这是因为input()返回的数据类型是strstr不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情:

s = input(‘birth: ‘)
birth = int(s)
if birth < 2000:
    print(‘00前‘)
else:
    print(‘00后‘)

再次运行,就可以得到正确地结果。但是,如果输入abc呢?又会得到一个错误信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ‘abc‘

原来int()函数发现一个字符串并不是合法的数字时就会报错,程序就退出了。

 

 

 

技术图片

 

 

技术图片

 

python学习进度4(条件判断)

标签:读取   call   --   同学会   一个   意思   自己   order   完整   

原文地址:https://www.cnblogs.com/2205254761qq/p/12271640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!