Menu
Home
Log in / Register
 
Home arrow Computer Science arrow Data Structures and Algorithms with Python
< Prev   CONTENTS   Next >

1.8 The Main Function

Programs are typically written with many function definitions and function calls. One function definition is written by convention in Python, usually called the main function. This function contains code the program typically executes when it is first started. The general outline of a Python program is given in Sect. 1.8.1.

1.8.1 Python Program Structure

1 # Imports at the top.

2 import turtle

3

4 # other function definitions followed by the main function definition

5 def main():

6 # The main code of the program goes here

7 t = turtle.Turtle()

8

9 # this code calls the main function to get everything started. The condition in this

10 # if statement evaluates to True when the module is executed by the interpreter, but

11 # not when it is imported into another module.

12 if name == " main ":

13 main()

The if statement at the end of the code in Sect. 1.8.1 is the first code executed after the import statements. The if statement's condition evaluates to True when the program is run as a stand-alone program. Sometimes we write modules that we may want to import into another module. Writing this if statement to call the main function makes the module execute its own main function when it is run as a stand-alone program. When the module is imported into another module it will not execute its main function. Later you will have the opportunity to write a module to be imported into another module so it is a good habit to form to always call the main function in this way.

1.9 Reading from a File

To begin our drawing program, let's assume that a picture is stored in a file and we wish to read this file when the program is started. We'll assume that each line of the file contains a drawing command and its associated data. We'll keep it simple and stick to drawing commands that look like this in the input file:

• goto, x, y, width, color

• circle, radius, width, color

• beginfill, color

• endfill

• penup

• pendown

Each line of the file will contain a record with the needed information. We can draw a picture by providing a file with the right sequence of these commands. The file in Sect. 1.9.1 contains records that describe a pickup truck.

1.9.1 A Text File with Single Line Records

1 beginfill, black

2 circle, 20, 1, black

3 endfill

4 penup

5 goto, 120, 0, 1, black

6 pendown

7 beginfill, black

8 circle, 20, 1, black

9 endfill

10 penup

11 goto, 150, 40, 1, black

12 pendown

13 beginfill, yellow

14 goto, -30, 40, 1, black

15 goto, -30, 70, 1, black

16 goto, 60, 70, 1, black 17 goto, 60, 100, 1, black 18 goto, 90, 100, 1, black 19 goto, 115, 70, 1, black 20 goto, 150, 70, 1, black

21 goto, 150, 40, 1, black

22 endfill

To process the records in the file in Sect. 1.9.1, we can write a Python program that reads the lines of this file and does the appropriate turtle graphics commands for each record in the file. Since each record (i.e. drawing command) is on its own line in the file format described in Sect. 1.9.1, we can read the file by using a for loop to read the lines of the file. The code of Sect. 1.9.2 is a program that reads these commands and processes each record in the file, drawing the picture that it contains.

1.9.2 Reading and Processing Single Line Records

1 # This imports the turtle graphics module.

2 import turtle

3

4 # The main function is where the main code of the program is written.

5 def main():

6 # This line reads a line of input from the user.

7 filename = input("Please enter drawing filename: ")

8

9 # Create a Turtle Graphics window to draw in.

10 t = turtle.Turtle()

11 # The screen is used at the end of the program.

12 screen = t.getscreen()

13

14 # The next line opens the file for "r" or reading. "w" would open it for

15 # writing, and "a" would open the file to append to it (i.e. add to the

16 # end). In this program we are only interested in reading the file.

17 file = open(filename, "r")

18

19 # The following for loop reads the lines of the file, one at a time

20 # and executes the body of the loop once for each line of the file.

21 for line in file:

22

23 # The strip method strips off the newline character at the end of the line

24 # and any blanks that might be at the beginning or end of the line.

25 text = line.strip()

26

27 # The following line splits the text variable into its pieces.

28 # For instance, if text contained "goto, 10, 20, 1, black" then

29 # commandList will be equal to ["goto", "10", "20", "1", "black"] after

30 # splitting text.

31 commandList = text.split(",")

32

33 # get the drawing command

34 command = commandList[0]

35

36 if command == "goto":

37 # Writing float(commandList[1]) makes a float object out of the

38 # string found in commandList[1]. You can do similar conversion

39 # between types for int objects.

40 x = float(commandList[1])

41 y = float(commandList[2])

42 width = float(commandList[3])

43 color = commandList[4].strip()

44 t.width(width)

45 t.pencolor(color)

46 t.goto(x,y)

47 elif command == "circle":

48 radius = float(commandList[1])

49 width = float(commandList[2])

50 color = commandList[3].strip()

51 t.width(width)

52 t.pencolor(color)

53 t.circle(radius)

54 elif command == "beginfill":

55 color = commandList[1].strip()

56 t.fillcolor(color)

57 t.begin_fill()

58 elif command == "endfill":

59 t.end_fill()

60 elif command == "penup":

61 t.penup()

62 elif command == "pendown":

63 t.pendown()

64 else:

65 print("Unknown command found in file:",command)

66

67 #close the file

68 file.close()

69

70 #hide the turtle that we used to draw the picture.

71 t.ht()

72

73 # This causes the program to hold the turtle graphics window open

74 # until the mouse is clicked.

75 screen.exitonclick()

76 print("Program Execution Completed.")

77

78

79 # This code calls the main function to get everything started.

80 if name == " main ":

81 main()

When you have a data file where each line of the file is its own separate record, you can process those records as we did in Sect. 1.9.2. The general pattern is to open the file, use a for loop to iterate through the file, and have the body of the for loop process each record. The pseudo-code in Sect. 1.9.3 is the abstract pattern for reading one-line records from a file.

1.9.3 Pattern for Reading Single Line Records from a File

1 # First the file must be opened.

2 file = open(filename,"r")

3

4 # The body of the for loop is executed once for each line in the file.

5 for line in file:

6 # Process each record of the file. Each record must be exactly one line of the

7 # input file. What processing a record means will be determined by the

8 # program you are writing.

9 print(line)

10

11 # Closing the file is always a good idea, but it will be closed when your program

12 # terminates if you do not close it explicitly.

13 file.close()

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel