文章目录
习题11:提问
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?")
print ("So, you're %r old, %r tall and %r heavy." %(age, height, weight))
输出结果为
How old are you?35
How tall are you?180
How much do you weigh?140
So, you're '35' old, '180' tall and '140' heavy.
问题15、16、17:文件的读写操作
问题20:函数和文件
from sys import argv
script, input_file = argv
def print_all(f):
print (f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print (line_count, f.readline())
#打开文件
current_file = open(input_file,encoding = 'utf-8')
#展示文件全部内容
print ("First let's print the whole file:\n")
print_all(current_file)
#重新定义展示文章行号
print ("Now let's rewind, kind of like a tape.")
rewind(current_file)
#展示文件的前三行内容
print ("Let's print three lines:")
current_line = 1 #设置开始行行号
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
输出结果为
First let's print the whole file:
To all the people out there.
I say I don't like my hair.
I need to shave it off.
Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to shave it off.
习题21:函数可以返回东西
def add(a, b):
print ("ADDING %d + %d" % (a, b))
return a + b
def subtract(a, b):
print ("SUBTRACTING %d - %d" % (a, b))
return a - b
def multiply(a, b):
print ("MULTIPLYING %d * %d" % (a, b))
return a * b
def divide(a, b):
print ("DIVIDING %d / %d" % (a, b))
return a / b
print ("Let's do some math with just functions!")
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print ("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height,weight, iq))
print('\n')#换行符
# A puzzle for the extra credit, type it in anyway.
print ("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq,2))))
print ("That becomes: ", what, "\n Can you do it by hand?")
输出结果为
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74