伪代码的基本思想是

a)使复杂代码易于理解,或

b)表达一个想法,即你将要编写代码/尚未想出如何编写代码。在

例如,如果我要制作一个需要从数据库中读取信息的工具,将其解析为字段,只获取用户请求的信息,然后格式化信息并将其打印到屏幕上,我的第一个代码草稿将是简单的伪代码,如下所示:# Header information

# Get user input

# Connect to Database

# Read in values from database

# Gather useful information

# Format information

# Print information

这为我的程序提供了一个基本的结构,这样我就不会迷失方向。另外,如果有人和我一起工作,我们可以把工作分成两部分(他负责编写连接到数据库的代码,而我负责编写代码以获取用户输入)

随着程序的进展,我将用真实的工作代码替换伪代码。在

^{pr2}$

在任何时候,我可能意识到代码中还有其他事情要做,如果我不想停止我正在做的工作,我会添加它们来提醒自己以后再回来编写代码。在# Header information #Don't forget to import the database dbconn class

user_input_row = int(input("Which row (1-10)? "))

#Protect against non-integer inputs so that the program doesn't fail

user_input_column = input("Which column (A, B, C)? "))

#Make sure the user gives a valid column before connecting to the database

dbase = dbconn("My_Database")

#Verify that we have a connection to the database and that the database is populated

row_of_interest = dbase.getrow(user_input_row)

# Separate the row by columns use .split()

# >> User only wants user_input_column

# Gather useful information

# Format information

# >> Make the table look like this:

# C C1 C2 < User's choice

# _________|________|_______

# Title | Field | Group

# Print information

在你完成编码之后,旧的伪代码甚至可以成为你的程序的好注释,这样其他人就可以马上知道你的程序的不同部分在做什么。在

当你不知道如何编写代码,但你知道你想要什么时,伪代码也能很好地工作,例如,如果你有一个关于如何在程序中创建某种循环的问题:my_list = [0,1,2,3,4,5]

for i in range(len(my_list)) but just when i is even:

print (my_list[i]) #How do I get it to print out when i is even?

伪代码可以帮助读者了解您正在尝试做什么,它们可以帮助您更轻松。在

在您的例子中,有用的伪代码(如解释代码的方式)可能如下所示:user_response=input("Input a number: ") # Get a number from user as a string

our_input=float(user_response) # Change that string into a float

def string (our_input):

if (our_input % 15) == 0 : # If our input is divisible by 15

return ("fizzbuzz")

elif (our_input % 3) == 0 : # If our input is divisible by 3 but not 15

return ("fizz")

elif (our_input % 5) == 0 : # If our input is divisible by 5 but not 15

return ("buzz")

else : # If our input is not divisible by 3, 5 or 15

return ("null")

print(string(our_input)) # Print out response

更多推荐

python伪代码例子_函数和操作数的Python伪代码