sec6.1
def getPentagonaNumber(n):
m = n * (3 * n - 1) / 2
print(format(m, "8.0f"), end = '')
k = 100
for i in range(1, k + 1):
getPentagonaNumber(i)
if i % 10 == 0:
print()
sec6.2
def sumDigits(n):
x = 0
while n > 10:
x = x + n % 10
n = n // 10
x = x + n
print(x)
y = eval(input("number: "))
sumDigits(y)
sec6.5
def displaySortedNumbers(num1, num2, num3):
if num1 > num2:
num1, num2 = num2, num1
if num1 > num3:
num1, num3 = num3, num1
if num2 > num3:
num2, num3 = num3, num2
print("The sorted numbers are ", num1, num2, num3)
x, y, z = eval(input("Enter three numbers: "))
displaySortedNumbers(x, y, z)
sec6.8
def celsiusToFahrenheit(celsius):
fahreheit = (9 / 5) * celsius + 32
return (format(fahreheit, "10.2f"))
def fahrenheitToCelsius(fahreheit):
celsius = (5 / 9) * (fahreheit - 32)
return (format(celsius, "8.2f"))
print("Celsius\tFahrenheit\t|\tFahrenheit\tCelsius")
for i in range(10):
m = 40 - i
n = 120 - i * 10
print(m, '\t', celsiusToFahrenheit(m), '\t|\t',
n, '\t', fahrenheitToCelsius(n))
sec6.10
# Check whether number is prime
def isPrime(number):
divisor = 2
while divisor <= number / 2:
if number % divisor == 0:
# If true, number is not prime
return False # number is not a prime
divisor += 1
return True # number is prime
count = 0
for i in range(1, 10000 + 1):
if isPrime(i):
print(format(i, "<6.0f"), end='')
count += 1
if count % 20 == 0:
print()
sec6.16
def numberOfDaysInAYear(year):
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
year = 366
else:
year =365
return year
for i in range(2010, 2020 + 1):
print(i, "year:", numberOfDaysInAYear(i))
sec6.37
from random import randint
import turtle
def getRandomCharacter(ch1, ch2):
return chr(randint(ord(ch1), ord(ch2)))
def getRandomLowerCaseLetter():
return getRandomCharacter('a', 'z')
for i in range(1, 101):
s = getRandomLowerCaseLetter()
turtle.write(s, font=(8))
turtle.penup()
turtle.forward(20)
if i % 15 == 0:
turtle.goto(0, -i*2)
turtle.pendown()
turtle.done()
sec6.38
import turtle
def drawLine(x1, y1, x2, y2, color = "black", size = 1):
turtle.color(color)
turtle.pensize(size)
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
turtle.hideturtle()
turtle.done()
drawLine(3,4,100,200,"red",7)
sec6.47
import turtle
def drawChessboard(startx, endx, starty, endy):
turtle.speed(50000)
i = abs((endx - startx) / 8)
j = abs((endy - starty) / 8)
count = 1
x = startx
y = starty
while x < endx:
while y > endy:
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
if count % 2 == 0:
turtle.begin_fill()
turtle.color("black")
turtle.forward(i)
turtle.right(90)
turtle.forward(j)
turtle.right(90)
turtle.forward(i)
turtle.right(90)
turtle.forward(j)
turtle.right(90)
turtle.end_fill() # draw black
else:
turtle.color("black")
turtle.forward(i)
turtle.right(90)
turtle.forward(j)
turtle.right(90)
turtle.forward(i)
turtle.right(90)
turtle.forward(j)
turtle.right(90) # draw white
count += 1
y -= j
count += 1
y = starty
x += i
drawChessboard(-300, -100, 100, -100)
drawChessboard(100, 200, 100, 0)
turtle.hideturtle()
turtle.done()
ckp6.1
'''
Function can be used to define reusable code and organize and simplify code.
'''
ckp6.2
'''
A function definition consists of the function's name, parameters, and body.
Calling a function executes the code in the function.
There are two ways to call a function, depending on whether or not it returns a value.
If the function returns a value, a call to that function is usually treated as a value.
If a function does not return a value, the call to the function must be a statement.
'''
ckp6.3
# Return the max of two numbers
def max(num1, num2):
result = num1 if num1 > num2 else num2
return result
def main():
i = 5
j = 2
k = max(i, j) # Call the max function
print("The larger number of", i, "and", j, "is", k)
main() # Call the main function
ckp6.4
True
ckp6.5
def xFunction(x, y):
print(x + y)
return
xFunction(1, 2)
'''
Yes!
'''
ckp6.6
'''
A function contains a header and body. The header begins with the def keyword, followed
by the function’s name and parameters, and ends with a colon.
The variables in the function header are known as formal parameters or simply parameters.
A parameter is like a placeholder: When a function is invoked, you pass a value to the parameter.
This value is referred to as an actual parameter or argument. Parameters are optional;
that is, a function may not have any parameters. For example, the random.random() function
has no parameters.
'''
ckp6.7
'''
def salesCommission(amount, rate):
value
def printCalender(month, year):
not value
def squareRoot(number):
value
def isEven(number):
not value
def printMessage(message, times):
not value
def monthlyPayment(loan, years, interest):
value
def lowercaseLetter(letter):
not value
'''
ckp6.8
def function1(n, m):
function2(3.4)
def function2(n):
if n > 0:
return 1
elif n == 0:
return 0
elif n < 0:
return -1
function1(2, 3)
ckp6.9
def main():
print(min(5, 6))
def min(n1, n2):
smallest = n1
if n2 < smallest:
smallest = n2
main() # Call the main function
ckp6.10
def main():
print(min(min(5, 6), (51, 6)))
def min(n1, n2):
smallest = n1
if n2 < smallest:
smallest = n2
main() # Call the main function
ckp6.12
'''
Suppose a function header is as follows:
def f(p1, p2, p3, p4):
Which of the following calls are correct?
f(1, p2 = 3, p3 = 4, p4 = 4) true
f(1, p2 = 3, 4, p4 = 4) false
f(p1 = 1, p2 = 3, 4, p4 = 4) false
f(p1 = 1, p2 = 3, p3 = 4, p4 = 4) true
f(p4 = 1, p2 = 3, p3 = 4, p1 = 4) true
'''
ckp6.15
'''
def main():
max = 0
getMax(1, 2, max)
print(max)
def getMax(value1, value2, max):
if value1 > value2:
max = value1
else:
max = value2
main()
def main():
i = 1
while i <= 6:
print(function1(i, 2))
i += 1
def function1(i, num):
line = ""
for j in range(1, i):
line += str(num) + " "
num *= 2
return line
main()
def main():
# Initialize times
times = 3
print("Before the call, variable", "times is", times)
# Invoke nPrintln and display times
nPrint("Welcome to CS!", times)
print("After the call, variable", "times is", times)
# Print the message n times
def nPrint(message, n):
while n > 0:
print("n = ", n)
print(message)
n -= 1
main()
'''
def main():
i = 0
while i <= 4:
function1(i)
i += 1
print("i is", i)
def function1(i):
line = " "
while i >= 1:
if i % 3 != 0:
line += str(i) + " "
i -= 1
print(line)
main()
ckp6.16
def main():
max = 0
getMax(1, 2, max)
def getMax(value1, value2, max):
if value1 > value2:
max = value1
else:
max = value2
print(max)
main()
ckp6.17
'''
def function(x):
print(x)
x = 4.5
y = 3.4
print(y)
x = 2
y = 4
function(x)
print(x)
print(y)
'''
def f(x, y = 1, z = 2):
return x + y + z
print(f(1, 1, 1))
print(f(y = 1, x = 2, z = 3))
print(f(1, z = 3))
ckp6.18
def function():
x = 4.5
y = 3.4
print(x)
print(y)
function()
print(x)
print(y)
'''
x, y都是不是实参,且是函数里的东西。没有确定的值
'''
ckp6.19
x = 10
if x < 0:
y = -1
else:
y = 1
print("y is", y)
ckp6.20
def f(w = 1, h = 2):
print(w, h)
f()
f(w = 5)
f(h = 24)
f(4, 5)
ckp6.21
def main():
nPrintln(5)
def nPrintln(n, message = "Welcome to Python!"):
for i in range(n):
print(message)
main() # Call the main function
ckp6.22
'''
With default arguments, you can define a function once, and call the function in many
different ways. This achieves the same effect as defining multiple functions with the
same name in other programming languages.
If you define multiple functions in Python,the later definition replaces the previous definitions.
'''
ckp6.23
def f(x, y):
return x + y, x - y, x * y, x / y
t1, t2, t3, t4 = f(9, 5)
print(t1, t2, t3, t4)
#一个函数可以输出多个数值
GCDFunction
# Return the gcd of two integers
def gcd(n1, n2):
gcd = 1 # Initial gcd is 1
k = 2 # Possible gcd
while k <= n1 and k <= n2:
if n1 % k == 0 and n2 % k == 0:
gcd = k # Update gcd
k += 1
return gcd # Return gcd
list6.1
# Return the max of two numbers
def max(num1, num2):
if num1 > num2:
result = num1
else:
result = num2
return result
def main():
i = 5
j = 2
k = max(i, j) # Call the max function
print("The larger number of", i, "and", j, "is", k)
main() # Call the main function
list6.2
# Print grade for the score
def printGrade(score):
if score >= 90.0:
print('A')
elif score >= 80.0:
print('B')
elif score >= 70.0:
print('C')
elif score >= 60.0:
print('D')
else:
print('F')
def main():
score = eval(input("Enter a score: "))
print("The grade is ", end = " ")
printGrade(score)
main() # Call the main function
list6.3_ReturnGrandeFunction
# Return the grade for the score
def getGrade(score):
if score >= 90.0:
return 'A'
elif score >= 80.0:
return 'B'
elif score >= 70.0:
return 'C'
elif score >= 60.0:
return 'D'
else:
return 'F'
def main():
score = eval(input("Enter a score: "))
print("The grade is", getGrade(score))
main() # Call the main function
list6.4_Increment
def main():
x = 1
print("Before the call, x is", x)
increment(x)
print("After the call, x is", x)
def increment(n):
n += 1
print("\tn inside the function is", n)
main() # Call the main function
list6.6_TestGCDFunction
from GCDFunction import gcd # Import the gcd function
# Prompt the user to enter two integers
n1 = eval(input("Enter the first integer: "))
n2 = eval(input("Enter the second integer: "))
print("The greatest common divisor for", n1,
"and", n2, "is", gcd(n1, n2))
list6.11_RandomCharacter
from random import randint # import randint
# Generate a random character between ch1 and ch2
def getRandomCharacter(ch1, ch2):
return chr(randint(ord(ch1), ord(ch2)))
# Generate a random lowercase letter
def getRandomLowerCaseLetter():
return getRandomCharacter('a', 'z')
# Generate a random uppercase letter
def getRandomUpperCaseLetter():
return getRandomCharacter('A', 'Z')
# Generate a random digit character
def getRandomDigitCharacter():
return getRandomCharacter('0', '9')
# Generate a random character
def getRandomASCIICharacter():
return chr(randint(0, 127))
list6.13_PrintCalendar
# Print the calendar for a month in a year
def printMonth(year, month):
# Print the headings of the calendar
printMonthTitle(year, month)
# Print the body of the calendar
printMonthBody(year, month)
# Print the month title, e.g., May 1999
def printMonthTitle(year, month):
print(" ", getMonthName(month), " ", year)
print("——————————————————————————————————————————")
print(" Sun Mon Tue Wed Thu Fri Sat")
# Print month body
def printMonthBody(year, month):
# Get start day of the week for the first date in the month
startDay = getStartDay(year, month)
# Get number of days in the month
numberOfDaysInMonth = getNumberOfDaysInMonth(year, month)
# Pad space before the first day of the month
i = 0
for i in range(0, startDay):
print(" ", end = " ")
for i in range(1, numberOfDaysInMonth + 1):
print(format(i, "4d"), end = " ")
if (i + startDay) % 7 == 0:
print() # Jump to the new line
# Get the English name for the month
def getMonthName(month):
if month == 1:
monthName = "January"
elif month == 2:
monthName = "February"
elif month == 3:
monthName = "March"
elif month == 4:
monthName = "April"
elif month == 5:
monthName = "May"
elif month == 6:
monthName = "June"
elif month == 7:
monthName = "July"
elif month == 8:
monthName = "August"
elif month == 9:
monthName = "September"
elif month == 10:
monthName = "October"
elif month == 11:
monthName = "November"
else:
monthName = "December"
return monthName
# Get the start day of month/1/year
def getStartDay(year, month):
START_DAY_FOR_JAN_1_1800 = 3
# Get total number of days from 1/1/1800 to month/1/year
totalNumberOfDays = getTotalNumberOfDays(year, month)
# Return the start day for month/1/year
return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7
# Get the total number of days since January 1, 1800
def getTotalNumberOfDays(year, month):
total = 0
# Get the total days from 1800 to 1/1/year
for i in range(1800, year):
if isLeapYear(i):
total = total + 366
else:
total = total + 365
# Add days from Jan to the month prior to the calendar month
for i in range(1, month):
total = total + getNumberOfDaysInMonth(year, i)
return total
# Get the number of days in a month
def getNumberOfDaysInMonth(year, month):
if (month == 1 or month == 3 or month == 5 or month == 7 or
month == 8 or month == 10 or month == 12):
return 31
if month == 4 or month == 6 or month == 9 or month == 11:
return 30
if month == 2:
return 29 if isLeapYear(year) else 28
return 0 # If month is incorrect
# Determine if it is a leap year
def isLeapYear(year):
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def main():
# Prompt the user to enter year and month
year = eval(input("Enter full year (e.g., 2001): "))
month = eval(input(("Enter month as number between 1 and 12: ")))
# Print calendar for the month of the year
printMonth(year, month)
main() # Call the main function
list6.15_UseCustonTurtleFunctions
import turtle
from UsefulTurtleFunctions import *
# Draw a line from (-50, -50) to (50, 50)
drawLine(-50, -50, 50, 50)
# Write text at (-50, -60)
writeText("Testing useful Turtle functions", -50, -60)
# Draw a point at (0, 0)
drawPoint(0, 0)
# Draw a circle at (0, 0) with radius 80
drawCircle(0, 0, 80)
# Draw a rectangle at (0, 0) with width 60 and height 40
drawRectangle(0, 0, 60, 40)
turtle.hideturtle()
turtle.done()
PrimeNumberFunction
# Check whether number is prime
def isPrime(number):
divisor = 2
while divisor <= number / 2:
if number % divisor == 0:
# If true, number is not prime
return False # number is not a prime
divisor += 1
return True # number is prime
def printPrimeNumbers(numberOfPrimes):
NUMBER_OF_PRIMES = 50 # Number of primes to display
NUMBER_OF_PRIMES_PER_LINE = 10 # Display 10 per line
count = 0 # Count the number of prime numbers
number = 2 # A number to be tested for primeness
# Repeatedly find prime numbers
while count < numberOfPrimes:
# Print the prime number and increase the count
if isPrime(number):
count += 1 # Increase the count
print(number, end = "\t")
if count % NUMBER_OF_PRIMES_PER_LINE == 0:
# Print the number and advance to the new line
print()
# Check if the next number is prime
number += 1
def main():
print("The first 50 prime numbers are")
printPrimeNumbers(50)
main() # Call the main function
UsefulTurtleFunction
import turtle
# Draw a line from (x1, y1) to (x2, y2)
def drawLine(x1, y1, x2, y2):
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
# Write a string s at the specified location (x, y)
def writeText(s, x, y):
turtle.penup() # Pull the pen up
turtle.goto(x, y)
turtle.pendown() # Pull the pen down
turtle.write(s) # Write a string
# Draw a point at the specified location (x, y)
def drawPoint(x, y):
turtle.penup() # Pull the pen up
turtle.goto(x, y)
turtle.pendown() # Pull the pen down
turtle.begin_fill() # Begin to fill color in a shape
turtle.circle(3)
turtle.end_fill() # Fill the shape
# Draw a circle centered at (x, y) with the specified radius
def drawCircle(x = 0, y = 0, radius = 10):
turtle.penup() # Pull the pen up
turtle.goto(x, y - radius)
turtle.pendown() # Pull the pen down
turtle.circle(radius)
# Draw a rectangle at (x, y) with the specified width and height
def drawRectangle(x = 0, y = 0, width = 10, height = 10):
turtle.penup() # Pull the pen up
turtle.goto(x + width / 2, y + height / 2)
turtle.pendown() # Pull the pen down
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(width)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(width)