掌握条件语句的结构
if
>>> x = 4
>>> if x % 2 ==0:
... print(x)
... print('x is even number.')
...
4
x is even number.
>>> if x % 2 ==1:
... print(x)
... print('x is even number.')
...
elif
>>> if x % 2 ==1:
... print(x)
... print('x is even number.')
...
>>> if x > 3:
... print(x,'x is more than 3')
... elif x < 3 and x > 0:
... print(x,'x is less than 3')
... else:
... print(x,'x is less than 0')
...
4 x is more than 3
三元操作
>>> x = 3.14
>>> lang = 'python' if x > 4 else 'rust'
>>> lang
'rust'
>>> lang = 'python' if x < 4 else 'rust'
>>> lang
'python'
在程序中正确使用条件语句
例题1:编写程序,判断用户输入的数字事奇数还是偶数
n = input('请输入一个自然数:')
if n.isdigit():
n = int(n)
if n %2 == 0:
print('{0} is a even number.'.format(n))
else:
print('{0} is a odd number.'.format(n))
else:
print('请输入一个自然数')
例题2:编写程序,判断用户输入的网站主域名是否符合规定格式要求
-网站主域名格式:www.xxxx.xxx
domain = input('please input a domain name:')
postfix = ('com','net','cn')
lst = domain.split('.')
if (len(lst) < 2 ) or (len(lst) > 4):
print('sorry! your domain is not right.')
elif lst[-1] not in postfix:
print('The domain does not comply with the regulations.')
else:
print('The domain is right.')