【练习题】第五章--条件循环(Think Python)

//--地板除。例:5//4=1

%--求模。例:5//3=2

如果你用Python2的话,除法是不一样的。在两边都是整形的时候,常规除法运算符/就会进行地板除法,而两边只要有一侧是浮点数就会进行浮点除法。

复合语句中语句体内的语句数量是不限制的,但至少要有一个。有的时候会遇到一个语句体内不放语句的情况,比如空出来用来后续补充。这种情况下,你就可以用pass语句,就是啥也不会做的

if x < 0:
    pass
if x < y:     
    print('x is less than y') 
elif x > y:     
    print('x is greater than y') 
else:     
    print('x and y are equal')

Python提供了更简洁的表达方法:

if 0 < x < 10:
    print('x is a positive single-digit number.')

调用自身的函数就是递归的;执行这种函数的过程就叫递归运算。 

in python3:

>>> text = input()

in python2:

>>> text = raw_input()

input函数能够把提示内容作为参数:

>>> name = input('What...is your name?\n')
What...is your name?

如果你想要用户来输入一个整形变量,可以把返回的值手动转换一下:

>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
42
>>> int(speed)
42

练习1:

time模块提供了一个名字同样叫做time的函数,会返回当前格林威治时间的时间戳,就是以某一个时间点作为初始参考值。在Unix系统中,时间戳的参考值是1970年1月1号。

(译者注:时间戳就是系统当前时间相对于1970.1.1 00:00:00以秒计算的偏移量,时间戳是惟一的。)

>>> import time
>>> time.time() 1437746094.5735958

写一个脚本,读取当前的时间,把这个时间转换以天为单位,剩余部分转换成小时-分钟-秒的形式,加上参考时间以来的天数。

code:

import time

D=time.time()//(60*60*24)
H=(time.time()%(60*60*24))//(60*60)
M=(time.time()%(60*60*24))%(60*60)//60
S=(time.time()%(60*60*24))%(60*60)%60
print('The time is %dD-%dH-%dM-%S',D,H,M,S)

猜你喜欢

转载自blog.csdn.net/qq_29567851/article/details/83020234