PY4E exercise chapter4 Functions

  • Exercise 1: Run the program on your system and see what numbers you get. Run the program more than once and see what numbers you get.

The random function is only one of many functions that handle random numbers. The function randint takes the parameters low and high, and returns an integer between low and high (including both).

>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
  • Exercise 2: Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get.
def print_lyrics():
    print("I'm a lumberjack, and I'm okay.")
    print('I sleep all night and I work all day.')


def repeat_lyrics():
    print_lyrics()
    print_lyrics()

repeat_lyrics()

# Code: http://www.py4e.com/code3/lyrics.py

得到报错:NameError: name ‘repeat_lyrics’ is not defined
结论:function应该在第一次执行它之前就已经被建立了。

  • Exercise 3: Move the function call back to the bottom and move the definition of print_lyrics after the definition of repeat_lyrics. What happens when you run this program?

正常执行

  1. Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters (hours and rate).

Enter Hours: 45
Enter Rate: 10
Pay: 475.0

def computepay():
    if fh>40:
        return fh*fr+(fh-40)*fr*0.5
    else:
        return fh*fr

hours=input('Enter Hours:')
rate=input('Enter Rate:')
fh=float(hours)
fr=float(rate)

p=computepay()

print('Pay:',p)
  • Exercise 7: Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.

Score Grade
= 0.9 A
= 0.8 B
= 0.7 C
= 0.6 D
< 0.6 F

score=input('Enter score:')
try:
    fs=float(score)
except:
    print('Bad score')
    quit()
def computegrade():
    if fs<0 or fs>1:
        return 'Bad score'
        quit()
    if fs>=0.9:
        return 'A'
    elif fs>=0.8:
        return 'B'
    elif fs>=0.7:
        return 'C'
    elif fs>=0.6:
        return 'D'
    else:
        return 'F'
p=computegrade()
print(p)

发现自己健忘的很厉害,总是今天学明天忘,要反复呀(ò_óˇ)
还有,我要学习怎么写好看的博客,为啥别人的博客都那么好看…

猜你喜欢

转载自blog.csdn.net/weixin_43511552/article/details/86474395