笨办法学python第六天

本文通过几个具体的Python函数实例展示了如何进行数学运算和字符串处理,包括定义和使用自定义函数来实现加减乘除等基本数学操作,以及利用Python的强大字符串功能完成转义字符处理、文本格式调整和公式计算。
摘要由CSDN通过智能技术生成

练习21

# --coding:utf-8--
def add(a,b):
    print "ADDING %d + %d" %(a,b)
    return a+b

def substract(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 = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)

print "Age:%d,Height:%d,Weight:%d,IQ:%d" %(age,height,weight,iq)

# A puzzle for the extra credit,type it in anyway.

print "Here is a puzzle."

what = add(age,substract(height,multiply(weight,divide(iq,2))))

print "That becomes:",what,"Can you do it by hand?"

练习24

# --coding:utf-8--

print "Let's practice everything." #普通的打印

print 'You\'d need to know \'bout escapes with \\ that do \nnewlines and \t tabs.' #使用转义字符\的打印

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \ the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""                 #使用三引号进行文本处理

print "------------------------"
print poem  #打印变量
print "------------------------"

five = 10 - 2 + 3 - 6
print "This should be five:%s" %five    #打印表达式

def secret_formula(stared):     #定义一个函数,进行计算和打印操作
    jelly_beans = stared * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans,jars,crates

start_point = 10000

beans,jars,crates = secret_formula(start_point)

print "With a starting point of : %d" % start_point
print "We'd have %d beans,%d jars,and %d crates." %(beans,jars,crates)

start_point /= 10
print "We can also do that this way:"
print "We'd have %d beans,%d jars,and %d crates." %secret_formula(start_point)

练习25

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    return sorted(words)

def print_first_word(words):
    word = words.pop(0)
    print word

def print_last_word(words):
    word = words.pop(-1)
    print word

def sort_sentence(sentence):
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值