python_exercise_1

Exercise 1.1: The interpreter
Open the Python interpeter. What happens when you input the following statements:
(a)
3 + 1
(b) 3 * 3
(c) 2 ** 3

(d) "Hello, world!"


Exercise 1.2: Scripts
Now copy the above to a script, and save it as script1.py. What happens if you run the script? (try:
python script1.py). Can you fix this (hint: use the print function)




Exercise 1.3: More interpreter
Explain the output of the following statements if executed subsequently:
(a)
’py’ + ’thon’(输出python,其实就是将两个字符串连接成为一个大的字符串)
(b) ’py’ * 3 + ’thon’(输出pypypython,其实就是将将py重复3次,然后和thon一起链接形成更大的字符串)
(c) ’py’ - ’py’(抛出异常,TypeError: unsupported operand type(s) for -: 'str' and 'str')
(d) ’3’ + 3(抛出异常,TypeError: must be str, not int)
(e) 3 * ’3’(将'3'重复三遍)
(f) a            (抛出异常,NameError: name 'a' is not defined)
(g) a = 3(无输出)

(h) a (输出3)


Exercise 1.4: Booleans
Explain the output of the following statements:
(a)
1 == 1    (True)
(b) 1 == True(True,默认1就是True)
(c) 0 == True(False,True == 1 != 0)
(d) 0 == False(True)
(e) 3 == 1 * 3(True)
(f) (3 == 1) * 3(输出0,因为3!=1,因此0*3 == 0)
(g) (3 == 3) * 4 + 3 == 1(False,左边等于7 ,右边等于1,7!=1)
(h) 3**5 >= 4**4 (False,左边等于15,右边等于16,15<16)

Exercise 1.5: Integers
Explain the output of the following statements:
(a)
5 / 3(输出1.6666666666666667,默认就是除不尽就是浮点除法了)
(b) 5 % 3(输出2)
(c) 5.0 / 3(输出1.6666666666666667)
(d) 5 / 3.0(输出1.6666666666666667)
(e) 5.2 % 3 (输出2.2,商为1,余数只好为2)
(f) 2001 ** 200 (pytho大数相乘还是支持的)

Exercise 1.6: Floats
Explain the output of the following statements:
(a)
2000.3 ** 200 (compare with above)()(小数乘法貌似都是3.1565130025242204e+261的方式给出的,用到2000.3的时候已经溢出了)
(b)
1.0 + 1.0 - 1.0(由于1.0比较小,不会忽略相加的1.0,因此结果等于1.0)

(c) 1.0 + 1.0e20 - 1.0e20 (由于e20比较大,所以忽略了1.0,使得1.0e20+1.0 == 1.0e20)


Exercise 1.7: Variables
Write a script where the variable name holds a string with your name. Then, assuming for now your
name is
John Doe, have the script output: Hello, John Doe! (and obviously, do not use print "Hello,
John Doe!"
.

Exercise 1.8: Type casting
Very often, one wants to \cast" variables of a certain type into another type. Suppose we have variable
x = ’123’, but really we would like x to be an integer.
This is easy to do in Python, just use
desiredtype(x), e.g. int(x) to obtain an integer.
Try the following and explain the output
(a)
float(123)(将123整数转化为单精度浮点数)
(b) float(’123’)(将123字符串转化为单精度浮点数)
(c) float(’123.23’)(将123.23字符串转化为单精度浮点数)
(d) int(123.23)(将12323浮点数整数转化为整数)
(e) int(’123.23’)(将123.23字符串转化为整数)
(f) int(float(’123.23’))(将123.23字符串转化为单精度浮点数然后转化为整数)
(g) str(12)(将12整数转化为字符串)
(h) str(12.2)(将12.2浮点数转化为字符串)
(i) bool(’a’)(将字符串转化为布尔数,ASCII非0则为一)
(j) bool(0)(将整数转化为布尔数)
(k) bool(0.1) (将浮点数转化为布尔数)

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页