anesi.info Lifestyle A CONCISE INTRODUCTION TO PROGRAMMING IN PYTHON PDF

A concise introduction to programming in python pdf

Friday, April 12, 2019 admin Comments(0)

To access the Introduction to Programming Using Python Companion Website for . So what are the benefits of learning programming using Python? in industry and academia due to its simple, concise, and intuitive syntax and extensive. A Concise Introduction to Programming in Python, Second Edition provides a hands-on and accessible introduction to writing software in Python, with no prior . Suitable for newcomers to computer science, A Concise Introduction to Programming in Python provides a succinct, yet complete, first course in.


Author: JULIAN ESCAMILLA
Language: English, Spanish, Japanese
Country: Eritrea
Genre: Politics & Laws
Pages: 542
Published (Last): 07.04.2016
ISBN: 781-1-51585-574-3
ePub File Size: 15.61 MB
PDF File Size: 19.12 MB
Distribution: Free* [*Regsitration Required]
Downloads: 27766
Uploaded by: BRENNA

in Computing] Mark J. Johnson - A Concise Introduction to Programming in Python, Second Edition (, - Free ebook download as PDF File .pdf), Text File. A CONCISE INTRODUCTION. TO PROGRAMMING IN. PYTHON. Mark J. Johnson. CRC Press. Taylor & Francis Croup. Boca Raton. London. New York. A Practical Introduction to. Python Programming. Brian Heinold be a concise, but not superficial, treatment on GUI programming. Part III.

Test your function on random lists. Compare your function with the sqrt function. The list function is a type converter like those in Table 2. Features This second edition is thoroughly reorganized and rewritten. Trace the computation of gcd Base cases need to be checked first.

Write as many of the exercises as you can. I will learn to have a normal conversation. I would appreciate hearing any comments. Topics are introduced as needed. In addition to the features outlined above. Feedback Feel free to contact me at johnsonm central. A special thanks goes to the students of COSC Olaf College. About the Author Mark J.. Mark is a graduate of the University of Wisconsin-Madison Ph. Johnson is professor of computer science and mathematics at Central College in Pella.

Each CPU family has its own instruction set. Most instructions boil down to one of a few simple types: RAM is an acronym for random access memory. By following this text. All examples in this text were written with Python 3. It is amazing that these small steps can be combined in so many different ways to build software that is incredibly diverse and complex.

Johnson M.J. A Concise Introduction to Programming in Python

RAM is volatile. Follow the instructions given there to install the latest production version of Python 3 on your system. Python is a popular scripting language available as a free download from www. We begin with a rough picture and gradually fill in details along the way. Once a program is loaded into RAM. When a program is ready to run. They are really just specific sequences of bits in memory. There are two main types of translation: Because of this. This ordering is not meant to be precise.

When a program is compiled. The Python Interpreter When you start Python. TABLE 1. In fact. On the other hand. If you provide it with valid Python. We will explain bits later if you are not sure what they are. The key point to remember about machine languages is that in order to be run by a CPU. The answer is that the programs are translated into machine language first. Python programs are usually interpreted. The interpreter displays the version of Python it was written for.

Try it and see. The interpreter will translate and execute any legal Python code that is typed at this prompt.

Use your Python environment1 to create a new file containing the code in Example 1. Example 1. Python programs. For example. A Python Program That said. Experiment—the interpreter will not mind. Remember that if you are not sure what something will do in Python. After the drawing finishes. After typing the program and saving it. If that does not work. It draws using a framework known as turtle graphics.

The Python Standard. Table 1. Optional extent specifies arc angle. The turtle holds a pen. Python Turtle Graphics Turtle graphics is a type of computer graphics that draws relative to the position of a virtual turtle on the screen.

The turtle may also move with the pen up or initiate other types of drawing such as drawing a dot. Importing Python Modules In order to use these Python turtle functions. At the time of this writing. Library Reference is a good place to look up specific reference information. To import a library module. Comments may appear anywhere in a Python program and are meant for human readers rather than the interpreter.

Remember to import the turtle module at the beginning of all of your turtle graphics programs. The Python Documentation is online. Tutorial provides informal descriptions of how most things work in Python. The star is helpful when you want to use many names from the same module. Comments are used sparingly in this text.

Using the Python Documentation You can imagine that the turtle module must provide many other functions in addition to those listed above. Comments Comments begin with a pound sign and signify that the rest of the line is to be ignored by the interpreter: Text that helps explain your program to others The comments at the top of Example 1. Do not name any of your program files turtle. Be sure to use the documentation set that matches your version of Python.

You may also have questions about exactly how those functions work. Use it when you start to learn a new topic. At the start of a turtle program. Software systems are among the most complicated artifacts ever created by hu- mans. Computation is changing how other academic disciplines do their work. There is nothing quite like getting an idea for a program and seeing it come to life. Compare the results of running these two sequences of steps: Software is everywhere. Programming develops your ability to solve problems.

Determine the center of the circle drawn by this program: Computer science develops your ability to understand systems. Because machine languages are so simplistic. Programming languages are tools for creation: And then showing it to all your friends. Describe in your own words where the circle is relative to the turtle that the circle function draws. Where is the origin? What are the coordinates of the lower-left and upper-right corners?

What are the width and height of the window? Write a program to draw a rectangle units wide and units tall. Write a program to draw something of your choice. Write a program to put a circle inside the square of Example 1. Put a dot at the center of the circle.

Experiment moving the turtle to determine the coordinate system used in the graphics window. Sketch the result of these turtle steps: Write a program to draw an equilateral triangle with side length Write a program to draw a right triangle of any size. Write a program to draw a circle centered at Use this function in a program to draw something. Use the Python documentation to learn about a turtle function not listed in Table 1.

These cannot be reported by the. Try them out to draw your own shapes. Semantic errors are present when a program runs but does not do what its author intended. With spoken languages. The new functions used in this example are listed in Table 1. Program Syntax and Semantics In order to compile or be interpreted.

As you do. If a program has the correct syntax. They will be reported by the compiler or interpreter. Program errors fall into two broad categories based on these terms: Syntax errors are mistakes in the form of the program. Although it may sound obvious. By their nature. Program Flow of Control A program is a sequence of statements.

You will learn different ways to alter this flow. As noted already. Visualize this flow of control as a downward stream of steps. Built-in functions2 are always available and do not need to be imported. Parameters are data items that the function takes as input to use during its execution. Function Parameters Functions communicate with each other through optional parameters and return values.

Each turtle function has a well-defined purpose captured by its name. Functions in Python are either built-in. Values for parameters will be specified when the function is called see below. Python Functions A function in Python is a bundle of code designed to perform a specific task.. A function with two parameters Functions have parameters if they need additional information to accomplish their task.

We will consider return values later. A function with no parameters The simplest functions require no communication and so have no parameters. In contrast. This function requires no additional information in order to know what to do.

Figure 1. Function names are important. In general. The syntax of a function call is: When this expression appears in a program statement that is being executed. In the case of goto. This flexibility is an important part of the power of functions in programming languages.

Calling Functions Every function has the capacity to perform a task. A function call requests execution of the function with particular arguments passed as the values for its parameters if any. Write a program to draw the same square as Example 1. Classify each of these errors as syntactic or semantic: Draw a diagram like Fig.

Use Tables 1. Give the name of the parameter in each case. Put a dot at the center of the square. Hide the turtle so that only the message is visible. Write a program to draw an ice cream cone: But you may have noticed that the turtle needs to start at the bottom of the circle and then call the circle function—as long as the turtle is pointing to the right. Write a program to draw a silo: Use the optional extent parameter of the circle function. Using functions you write yourself is no different from using any of the library or built-in functions.

Hide the turtle at the end. Remember from the last section that when we call a function Defining Functions A function definition specifies the code that will be executed when the function is called. The syntax of a function definition is: Function definitions have two parts: Header The first line of a function definition. The parentheses are always required.

There are few hard-and-fast rules. The block ends at the first line that is not indented. Lines 14—20 of Example 1. We will consider line 7 shortly. Blank lines are allowed inside a block. Be careful of very short names: Code that is indented underneath a line ending in a colon is called a block or suite. Docstring Comments Docstring comments describe functions to other programmers. Body The body of the function is made up of all the statements that are indented underneath the header.

The body of a function is the code that will be executed when the function is called. Function definitions usually appear near the top of Python programs. Like other comments. The header ends with a colon. In Example 1. Naming Functions and Parameters As you write your own functions. The only mandatory requirement is that function and parameter names must be legal Python identifiers. These keywords appear in bold in program examples. The actual rules for identifiers are contained in the Python Language Reference.

There is a small set of reserved Python keywords that may not be used as names. Docstrings are enclosed in triple quotes three double-quote " characters.

This is similar to the way we called library functions: This technique is called abstraction. This diversion makes the abstraction work: Abstractions allow you to ignore lower-level details in order to think in terms of higher-level concepts. Calling a Function Changes the Flow of Control The flow of control changes in order to enable this abstraction. A function call creates a diversion in the flow of control to execute the body of the function. In other words. Use it to draw several targets.

Draw using forward and left. Write a square width function to draw a square so that the lower-left corner is put where the turtle is located and the square is oriented in the direction of the turtle. Write two functions. Do not worry about the interlocking.

Requires either Exercise 9 or Use your function to draw some squares. Write a triangle x0. Use your function to draw some triangles.

Use your functions to draw some squares and rectangles. Use your function to draw squares where there are circles in Example 1. Write a silo width. Use your function to draw some rectangles. Draw using goto. Draw so that the lower-left corner is wherever the turtle is located.

Use your function to draw three rectangles. Draw the square using goto. Write a rectangle width. Functions like main that are intended to drive the execution of a program are sometimes known as. Look again at the code to draw a square from Example 1.

Main Function Example 1. It can be summarized as: This is a common way of writing Python programs. Remember that a block ends when the indentation ends. The call to main on line 18 is important—without it. There is a lot to learn about loops. The range function may be called in three different ways. They are most useful when you know ahead of time how many times the loop should run.

For now. All parameters must be integers. Ranges The built-in range function is often used to create sequences in Python for loops. The body of a for loop is like the body of a function: The syntax of a for loop is: The interpreter will not directly show you the values in a range.

The step size may be negative.. Ranges start at 0 unless you specify otherwise. Ranges always end at the last term before reaching the stop value. If you do not specify a start value. The range function is not intuitive at first. That means a loop over range 10 runs 10 times. The third parameter specifies a step size.

When using two parameters like this. Loop Variables Compare the two loops in Example 1. It is equivalent to writing out the body with each different value of n: It is important to see that this sequence has 10 items in it.

To see them. This range starts at 2 and stops before reaching 7. Variables like this whose values are never used are called dummy variables.

List the items generated by range n from line 8 of Example 1. Identify the body of the for loop beginning at line 14 of Example 1. A for loop changes this flow to repeat the body for each item in the given sequence. List the items generated by range 3.

Identify the body of the for loop beginning at line 8 of Example 1. These values are ignored in the body of the loop. After the last item in the sequence. Determine the sequence generated by each of these range expressions: Draw more rings when the radius is larger—as many as will fit. Determine a range expression to produce each of these sequences: Use the polygon function to draw the squares. Use the circle function. Use a loop. Use the polygon function to draw a circle.

Try to predict the output.. Describe the order in which the circles are drawn. Write a program to draw a spiral shape by having the turtle move forward an increasing amount while turning left a decreasing amount. Write a loop for y inside of a loop for x called nested loops to draw a grid of circles with radius 50 spaced units apart.

Use your function to draw three targets of different sizes. Write a program to repeat these steps 36 times: This flexibility to make choices while a program runs is another important key to the power of computation.

Write a mycircle radius function that uses the polygon function to mimic the library circle function. New turtle functions used in this program are given in Table 1. Use your function in a loop to draw several circles. The name comes from the fact that true-false conditions are used to decide which code to execute. Conditional statements are also known as selection statements because testing a condition can be thought of as selecting an option.

Conditional statements allow a program to execute different code depending on what happens as the program runs. In Python. The simplest is: True and False are. We will see other forms of the if statement in Section 1. Boolean Expressions Conditions in Python are written as boolean expressions. If the condition is false. When calling functions.. Using Functions with Return Values In addition to whatever work they do. First consider the call to forward in line 8: Evaluate these boolean expressions: Describe the effects of each.

Determine which block s will be executed in this code fragment: Block B Block C. Try smaller and larger values in the call range on line 16 of Exam- ple 1. You probably took this for granted in reading Example 1.

Notice how the return value is used: When it is called. Then we can imagine the if statement as in Fig. Suppose the current x-coordinate is Try smaller and larger values in the call move 10 on line 17 of Example 1.

A Concise Introduction to Programming in Python - CRC Press Book

Functions without return values are sometimes referred to as procedures to emphasize the difference. Compare this to calling xcor on line 9: But it is important to become aware of using return values as you write your own programs.

Modify Example 1. See the exercises there. Describe how the return value is used. Look in the Python documentation to see if the turtle shape function has a return value. Using xcor and ycor. Have it turn a different angle at each edge. Write a program so that the turtle turns left when it gets close to any edge of the turtle window. Modify Exercise 13 so that the turtle is blue when it is on the right half of the window and red when it is on the left half.

It will be better to wait until Section 1. Describe what happens if xcor is called in a program on a line by itself: Block B if 2! Block C Block D 7. Find the one function used in Example 1. Add another if statement to the move function in Example 1. Experiment with the angles to try to keep the turtle on screen. Look in the Python documentation to see if the turtle speed function has a return value.

When the loop runs. The body is repeatedly executed until the condition is False. In the spiral function of Example 1. What is different is that after the body executes.

The Python while loop combines the ability of an if statement to test a condition with the ability of a for loop to repeat. Figure Use Ctrl-C to stop the program or look for an option to restart your interpreter or shell if you execute an infinite loop. A while loop may be infinite if its condition never fails..

In some cases. Notice also how the only way to continue to the following statement is for the boolean condition to be false. Comparing for and while Loops The major differences between for and while loops are: These principles will help you choose between the two.

Rewrite each loop in Exercise 3 as a for loop with a range. Determine the number of times this loop body will execute: List all of the values taken on by the step variable in Example 1. Of those values. Chapter 2 will explore these concepts in much more detail. Indicate the value of step that stops the loop if any.

Line 8 assigns the variable step to refer to the value in firststep: List all of the values taken on by the step variable in each of the loops below.

Rewrite each loop in Exercise 4 as a for loop with a range. Think of variables in Python as names of values. Rewrite Example 1. Experiment with the parameters of the spiral function.

Then write one program to draw three different spirals in different locations. Rewrite the main function of Example 1. Rewrite the polygon function of Example 1. Other forms of the if statement allow choosing from among two or more options.

When circles are drawn on pixel-based displays, they cannot be perfect, so they are usually drawn as polygons with many sides. The mycircle function adapts the number of sides in the polygon to the radius, so that more sides are used for larger circles. It requires the polygon function from Section 1. An if statement. In this case, body1 is executed if the condition is true; otherwise, body2 is executed.

When the choice is more complex than either-or, a sequence of tests may be checked by using one or more elif clauses, again with an optional else:.

Later tests are checked only if all preceding tests are false. So, an if-else chooses between two options, whereas an if-elif-else chain chooses from any number of options. Separate vs. Dependent Questions Compare these two sequences of statements: B B The questions on the left are separate, and both questions will always be asked. For example, if score is 93, then both the A and B sections will run. The second question on the right is dependent on the answer to the first: In this case, if score is 93, only the A section will run.

Another way to think about the difference is to ask yourself if you need to run the second test when the first is true. Use separate if statements to ask independent questions, each of which will always be asked; use an if-elif chain to choose one from among several options. Boolean Operations To express more complex conditions in any form of if or while, Python provides boolean and, or, and not operations. Both parts need to be true for an and to be true. Only use boolean values with these operations.

They can be used with other types, but those idioms are more advanced, and the results may be unexpected. Draw a flow-of-control diagram like Fig. Determine which block s will be executed in these code fragments: Block B Block B else: Block C Block C else: Incorporate Example 1. Rewrite Exercise 15 of Section 1. It combines two comparisons in one. Start the turtle moving at an angle. It uses the randrange function from the random library to generate values that appear random.

Random walks are not only fun to watch. Rewrite Exercise 14 of Section 1. Importing Specific Names To import only specific names from a module. Do not worry too much about getting the turtle to bounce precisely against the box. The last two sections of this chapter provide more practice with turtles before moving on to numeric data in Chapter 2. Extend the previous exercise to draw a box in which the turtle will bounce.

You might also like: NETWORK PROGRAMMING IN C PDF

As you continue to use these in different contexts. Use this form with most libraries. Nested Function Calls Example 1. The argument to left needs to be an angle. Consider the call on line 9 to left randrange 0. Explain why or why not. Write a function call to return a random angle between 0 and degrees not necessarily an integer. Such an expression is known as a nested function call.

Write a function call to return a random odd integer between 1 and Identify the two other nested function calls besides line 9 in Example 1. It may help to view this expression from the inside out. Write a function call to return a random integer between 1 and Rewrite line 14 of Example 1. Can Example 1. Write a function call to return a random angle between 45 and 90 degrees not necessarily an integer. Describe the region of the window to which the turtle is restricted by the while loop on line 14 of Example 1.

List the possible values from which the randrange expression on line 9 of Example 1. Write a program to draw 50 random squares in the turtle window. Use a function to draw each rectangle. If it had subcompo- nents. Tasks and Subtasks Functions help solve complex problems by allowing us to think in terms of tasks and subtasks. Use a random thickness for each line.

Write a program to draw 50 random line segments in the turtle window. One way to help decide what various functions ought to do is by separating responsibilities between them.

Do not restrict either value to integers. Use the function to draw something. Use a function to draw each square. Write a program to draw 20 random circles in the turtle window.

The eye is responsible for drawing its shape. If other components such as a nose or mouth are included. For instance. This section will give you practice in using functions to help solve problems. The face is responsible for drawing its outer shape a circle. In doing so.

So the face function decides where to put the eyes. The basic principle is that each function should be designed to accomplish one well-defined task. Write a program to draw 50 random rectangles in the turtle window. They happen to have the same names. The face parameters specify the center of the entire face.

Relative Locations and Sizes Locations are determined relative to the specified center point of each com- ponent. What makes this work in Python is a concept called scope. The scope of any variable is the region in a program where the variable may be used. Scope of Parameters In programs like Example 1. It makes sure the pen is up before moving to the starting point. Top-Down and Bottom-Up Design Top-down design starts with large process steps and gradually breaks each one down until there is enough detail to implement it.

A bottom-up approach. This is a type of defensive programming because the function defends itself against what a caller might or might not have done beforehand. This makes it easier to use. It is a helpful technique when writing functions for subtasks. Scope is convenient. Bottom-up works in reverse. In the context of Example 1. Neither technique is always better. Use your function to draw several stick figures of different sizes.

Write a function to draw a house based on the principles of this section. Write a nose x. Write a program to draw a line of faces horizontally across the screen. Include separate functions for the body. Write a mouth x. Include separate functions for components such as the base.

Create your own drawing based on the principles of this section. Give your faces a body by developing a stick figure function. Modify the eye function to add an inner filled eyeball.

Write separate functions for different subcomponents. Write a helper line x0. Use your function to draw several houses of different sizes. Write a loop for y inside of a loop for x called nested loops to fill the screen with faces. Write a program to draw faces in random locations and of random sizes. Modify the eye function to add an inner filled eyeball placed in a random location inside the eye.

It illustrates several important new concepts. Enter two values to find the larger. The syntax of an assignment statement is: Python variable names may be any legal identifier that is not a keyword see page Assignment Variables are assigned values by assignment statements.

In this chapter. Evaluate the expression on the right. Context matters with variable names. Variables As we saw in Chapter 1. Different variable names allow a program to keep track of different values as the program runs. The value must be determined before being named. Assign the variable on the left to refer to that value. In all cases. Visualizing Assignment View assignments as creating an arrow from the variable to the value. Then 17 and 10 are added together.

In to a introduction python programming pdf concise

Variables must be assigned a value before use. The mechanism to send a value from a function back to its caller is the return statement. Local Variables in Functions Variables used for the first time inside the body of a function are called local variables because they may only be used locally inside that function. In Example 2. The scope see page 39 of a local variable is the body of the function in which it is defined—the same as the scope of function parameters.

Any attempts to access a local variable from outside the function definition will fail. In it. Even though the input prompt is optional. The value in a return is optional. TABLE 2.

Values output with print are separated by single spaces in the output. Start becoming aware of these types. The input function requests information from the user running the program. Strings written with double quotes may contain single quotes. In particular.

Pdf in a concise python programming introduction to

Print value1. Because return statements immediately terminate the function. An Introduction to Types Every data element in a Python program has a specific type that determines the operations the item supports as well as its range of possible values. Table 2. This means that all Python functions return something.. Triple-quoted strings may extend across multiple lines. Example 2. Input and Output Example 2.

What is somewhat unusual in Python is that if no value is specified in a return statement. To see how. Describe the differences. Variables can help unravel nested function calls. For the input of numeric data. Change Example 2. Describe and explain the result. Describe what happens. Write assignment statements to swap their values. Suppose x and y have been assigned values. Write a mymin2 x. Write a myabs x function to return the absolute value of x. Determine the final values of each variable in these sequences of assignment statements.

Rewrite the mymax2 function of Example 2. Determine the output of this code fragment: Include a main to test your function. In that case. Draw pictures to help determine the final values of each variable in these sequences of assignment statements.

Write a function grade score to return the corresponding letter grade for a given numerical score. Rewrite the main of Example 2. It uses the basic arithmetic operations in Table 2. Write a median3 x. Write a mymax3 x. That is. Write a mymin3 x. Same as pow x. If two or more of the values happen to be the same.

Result is a float. Order of Operations Calculations in Python follow the normal rules of arithmetic. Operators of higher precedence are computed first. These include rules for deciding the order of operations. Mark J. Mark is a graduate of the University of Wisconsin-Madison Ph. Olaf College. We provide complimentary e-inspection copies of primary textbooks to instructors considering our books for course adoption.

A Concise Introduction to Programming in Python

CPD consists of any educational activity which helps to maintain and develop knowledge, problem-solving, and technical skills with the aim to provide better health care through higher standards. It could be through conference attendance, group discussion or directed reading to name just a few examples. We provide a free online form to document your learning and a certificate for your records. Already read this title? Stay on CRCPress. Exclusive web offer for individuals on print book only.

Preview this Book. Select Format: Add to Wish List. Close Preview.

Toggle navigation Additional Book Information. Description Table of Contents Author s Bio. Summary Suitable for newcomers to computer science, A Concise Introduction to Programming in Python provides a succinct, yet complete, first course in computer science using the Python programming language. The book features: Short, modular chapters with brief and precise explanations, intended for one class periodEarly introduction of basic procedural cons. Table of Contents Foundations: Computer Systems and Software.

Python Program Components. For Loops. Computer Memory: If Statements. Algorithm Design and Debugging. While Loops. Newton's Method. Collections and Files: Building Strings. Program Performance. Heat Diffusion. String Methods. File Compression.