基础知识

函数太重要,咱们的程序如果是大厦……好吧……咱们现在的本事只能盖个小趴趴房,那函数就是我们盖房子的石头。

函数有多重要?嗯…从配的图是我美大王瑟兰迪尔就可以看出!

什么是函数?为什么要用函数?

函数是能完成独立功能的模块,有了函数,我们要用其实现的功能,直接调用就可以了,而不用把同样的代码敲两遍三遍四遍。

这不仅大幅减少代码长度,提高代码的利用率,也可以减少出错的几率,隔离错误的影响范围。实现同样功能的重复代码,一个错误,重复代码出现的范围都受波及。

好不容易锁定错误,改动一个,其他都得跟着改,发生遗漏再平常不过。用函数进行模块化,也就把错误困起来,对我们定位查找纠正错误也是大大有益的。

函数还提高程序的可读性,可读性是平常程序宁可牺牲效率也要增加的指标呀!

随着功力的增加,总有一天我们也能写出解决大的复杂问题的程序,学会把大问题敲碎,敲成一个个小问题,然后用函数来实现是必须哒。

在视频中我们讲解了:函数的基础知识,变量的作用域、演示凯撒密码的程序使用函数后的效果、一扫而过python自带模块math里的函数

程序实例:根据用户输入图形用相应函数算出图形面积;用户输入一个数,把这个数以内的素数全部列出来;用户输入任意个数字,函数给出数字之和

函数视频:

 

# ---------- PROBLEM : SOLVE FOR X ----------
# Make a function that receives an algebraic equation like
# x + 4 = 9 and solve for x
# x will always be the 1st value received and you only
# will deal with addition

# Receive the string and split the string into variables
def solve_eq(equation):
    x, add, num1, equal, num2 = equation.split()

    # Convert the strings into ints
    num1, num2 = int(num1), int(num2)

    # Convert the result into a string and join (concatenate)
    # it to the string "x = "
    return "x = " + str(num2 - num1)


print(solve_eq("x + 4 = 9"))
# shape area

import math

def get_area(shape):

	# switch the lowercase for easy comparison
	shape = shape.lower()

	if shape == 'rectangle':
		rectangle_area()
	elif shape == 'circle':
		circle_area()
	else:
		print("Please enter rectangle or cirle")

# Create function that calculates the rectangle area
def rectangle_area():

	length = float(input("Enter the length: "))
	width = float(input("Enter the width: "))

	area = length * width

	print("The area of the rectangle is", area)

# Create function that calculates the circle area
def circle_area():

	radius = float(input("Enter the radius: "))

	area = math.pi * math.pow(radius, 2)

	print("The area of the circle is {:.2f}".format(area))

# Ask the user what shape they want
shape_type = input("Get area for what shape: ")

# Call a function that will route to the correct function
get_area(shape_type)
# judge if prime or not

def isprime(num):
	for i in range(2, num):
		if (num % i) == 0:
			return False

	return True

# get all primes within numMax
def getPrimes(numMax):

	primes = []

	for num1 in range(2, numMax):

		if isprime(num1):
			primes.append(num1)

	return primes

maxNum = int(input("Search for primes up to: "))

listOfPrimes = getPrimes(maxNum)

for prime in listOfPrimes:
	print(prime, end=', ')

# ---------- PROBLEM : CAESAR'S CIPHER ----------
# Receive a message and then encrypt it by shifting the
# characters by a requested amount to the right
# A becomes D, B becomes E for example
# Also decrypt the message back again

# Cycle through each character in the message
def cipher(befMessage, key):

	aftMessage = ''
	for char in befMessage:

		# if it is a letter
		if char.isalpha():

			# Get unicode and add the shift amount
			char_code = ord(char) + key

			# if uppercase
			if char.isupper():

				# if greater than 'Z'
				if char_code > ord('Z'):
					char_code -= 26

				# if less than 'A'
				if char_code < ord('A'):
					char_code += 26

			# if lowercase
			if char.islower():

				# if greater than 'z'
				if char_code > ord('z'):
					char_code -= 26

				# if less than 'a'
				if char_code < ord('a'):
					char_code += 26

			# Convert from code to letter and add to message
			aftMessage += chr(char_code)

		# if not a letter leave the character as is
		else:
			aftMessage += char
	return aftMessage

# Receive the message to encrypt and the number of characters to shift
message = input("Enter your message: ")
key = int(input("How many characters should we shift(-26 ~ 26) "))

secret_message = cipher(message, key)

# print the encrypted message
print("Encrypted message: ", secret_message)

# To decrypt the only thing that changes is the sign of the key
key = -key

orig_message = cipher(secret_message, key)

# print the original message
print("Decrypted message: ", orig_message)
# ---------- PROBLEM : CAESAR'S CIPHER ----------

# Cycle through each character in the message
def shift(befMessage, key):

	aftMessage = ''
	for char in befMessage:

		# if it is a letter
		if char.isalpha():

			# Get unicode and add the shift amount
			char_code = ord(char) + key

			# if uppercase and greater than 'Z' or lowercase and greater than 'z'
			if (char.isupper() and char_code > ord('Z')) or (char.islower() and char_code > ord('z')):
					char_code -= 26

			# if uppercase and less than 'A' or lowercase and less than 'a'
			elif (char.isupper() and char_code < ord('A')) or (char.islower() and char_code < ord('a')):
					char_code += 26

			# Convert from code to letter and add to message
			aftMessage += chr(char_code)

		# if not a letter leave the character as is
		else:
			aftMessage += char
	return aftMessage

# Receive the message to encrypt and the number of characters to shift
message = input("Enter your message: ")
key = int(input("How many characters should we shift(-26 ~ 26) "))

secret_message = shift(message, key)

# print the encrypted message
print("Encrypted message: ", secret_message)

# To decrypt the only thing that changes is the sign of the key
key = -key

orig_message = shift(secret_message, key)

# print the original message
print("Decrypted message: ", orig_message)

1 1 1 1 1 1 1 1 1 1 Rating 2.00 (3 Votes)

感谢你对 Python ABC 的支持!

5 元

10 元

20 元

30 元

50 元

100 元


Alipay logo