(读书笔记)笨办法学python-(习题1-40)


习题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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值