Introduction to Computers and Programming: Chapter 1 PDF

Summary

This document is an introductory textbook chapter from CSBP119, covering fundamental concepts in computer science, including hardware and software components, data storage, and the basics of programming with Python. It is published by Pearson Education, Ltd. and focuses on algorithms and problem-solving. The chapter explores the CPU, memory, input/output devices, as well as how computers store data.

Full Transcript

CSBP119 Algorithms & Problem Solving CIT, UAEU Click to add text CHAPTER 1 Introduction to Computers and Programming Copyright © 2018 Pearson Education, Ltd. ...

CSBP119 Algorithms & Problem Solving CIT, UAEU Click to add text CHAPTER 1 Introduction to Computers and Programming Copyright © 2018 Pearson Education, Ltd. Topics Introduction Hardware and Software How Computers Store Data How a Program Works Using Python Copyright © 2018 Pearson Education, Ltd. Introduction Computers can be programmed Designed to do any job that a program tells them to Program: set of instructions that a computer follows to perform a task Commonly referred to as Software Programmer: person who can design, create, and test computer programs Also known as software developer Copyright © 2018 Pearson Education, Ltd. Hardware and Software Hardware: The physical devices that make up a computer Computer is a system composed of several components that all work together Typical major components: Central processing unit Main memory Secondary storage devices Input and output devices Copyright © 2018 Pearson Education, Ltd. The CPU Central processing unit (CPU): the part of the computer that actually runs programs Most important component Without it, cannot run software Microprocessors: CPUs located on small chips Copyright © 2018 Pearson Education, Ltd. Main Memory Main memory: where computer stores a program while program is running, and data used by the program Known as Random Access Memory or RAM CPU is able to quickly access data in RAM Volatile memory used for temporary storage while program is running Contents are erased when computer is off Copyright © 2018 Pearson Education, Ltd. Secondary Storage Devices Secondary storage: can hold data for long periods of time Programs normally stored here and loaded to main memory when needed Types of secondary memory Disk drive: magnetically encodes data onto a spinning circular disk Solid state drive: faster than disk drive, no moving parts, stores data in solid state memory Flash memory: portable, no physical disk Optical devices: data encoded optically Copyright © 2018 Pearson Education, Ltd. Input Devices Input: data the computer collects from people and other devices Input device: component that collects the data Examples: keyboard, mouse, touchscreen, scanner, camera Copyright © 2018 Pearson Education, Ltd. Output Devices Output: data produced by the computer for other people or devices Can be text, image, audio, or bit stream Output device: formats and presents output Examples: video display, printer Copyright © 2018 Pearson Education, Ltd. Software Everything the computer does is controlled by software General categories: Application software System software Application software: programs that make computer useful for every day tasks Examples: word processing, email, games, and Web browsers Copyright © 2018 Pearson Education, Ltd. How Computers Store Data All data in a computer is stored in sequences of 0s and 1s Byte: just enough memory to store letter or small number Divided into eight bits Bit: electrical component that can hold positive or negative charge, like on/off switch The on/off pattern of bits in a byte represents data stored in the byte Copyright © 2018 Pearson Education, Ltd. Storing Numbers Bit represents two values, 0 and 1 Computers use binary numbering system Position of digit j is assigned the value 2j-1 To determine value of binary number sum position values of the 1s Byte size limits are 0 and 255 0 = all bits off; 255 = all bits on To store larger number, use several bytes Copyright © 2018 Pearson Education, Ltd. Storing Characters Data stored in computer must be stored as binary number Characters are converted to numeric code, numeric code stored in memory Most important coding scheme is ASCII ASCII is limited: defines codes for only 128 characters Unicode coding scheme becoming standard Compatible with ASCII Can represent characters for other languages Copyright © 2018 Pearson Education, Ltd. How a Program Works CPU designed to perform simple operations on pieces of data Examples: reading data, adding, subtracting, multiplying, and dividing numbers Understands instructions written in machine language and included in its instruction set Each brand of CPU has its own instruction set To carry out meaningful calculation, CPU must perform many operations Copyright © 2018 Pearson Education, Ltd. How a Program Works (cont’d.) Program must be copied from secondary memory to RAM each time CPU executes it CPU executes program in cycle: Fetch: read the next instruction from memory into CPU Decode: CPU decodes fetched instruction to determine which operation to perform Execute: perform the operation Copyright © 2018 Pearson Education, Ltd. How a Program Works (cont’d.) Figure 1-16 The fetch-decode-execute cycle Copyright © 2018 Pearson Education, Ltd. From Machine Language to Assembly Language Impractical for people to write in machine language Assembly language: uses short words (mnemonics) for instructions instead of binary numbers Easier for programmers to work with Assembler: translates assembly language to machine language for execution by CPU Copyright © 2018 Pearson Education, Ltd. High-Level Languages Low-level language: close in nature to machine language Example: assembly language High-Level language: allows simple creation of powerful and complex programs No need to know how CPU works or write large number of instructions More intuitive to understand Copyright © 2018 Pearson Education, Ltd. Key Words, Operators, and Syntax: an Overview Key words: predefined words used to write program in high-level language Each key word has specific meaning Operators: perform operations on data Example: math operators to perform arithmetic Syntax: set of rules to be followed when writing program Statement: individual instruction used in high- level language Copyright © 2018 Pearson Education, Ltd. Compilers and Interpreters Programs written in high-level languages must be translated into machine language to be executed Compiler: translates high-level language program into separate machine language program Machine language program can be executed at any time Copyright © 2018 Pearson Education, Ltd. Compilers and Interpreters (cont’d.) Interpreter: translates and executes instructions in high-level language program Used by Python language Interprets one instruction at a time No separate machine language program Source code: statements written by programmer Syntax error: prevents code from being translated Copyright © 2018 Pearson Education, Ltd. Compilers and Interpreters (cont’d.) Figure 1-19 Executing a high-level program with an interpreter Copyright © 2018 Pearson Education, Ltd. Using Python Python must be installed and configured prior to use One of the items installed is the Python interpreter Python interpreter can be used in two modes: Interactive mode: enter statements on keyboard Script mode: save statements in Python script Copyright © 2018 Pearson Education, Ltd. Interactive Mode When you start Python in interactive mode, you will see a prompt Indicates the interpreter is waiting for a Python statement to be typed Prompt reappears after previous statement is executed Error message displayed If you incorrectly type a statement Good way to learn new parts of Python Copyright © 2018 Pearson Education, Ltd. Writing Python Programs and Running Them in Script Mode Statements entered in interactive mode are not saved as a program To have a program use script mode Save a set of Python statements in a file The filename should have the.py extension To run the file, or script, type python filename at the operating system command line Copyright © 2018 Pearson Education, Ltd. Copyright © 2018 Pearson Education, Ltd. Summary This chapter covered: Main hardware components of the computer Types of software How data is stored in a computer Basic CPU operations and machine language Fetch-decode-execute cycle Complex languages and their translation to machine code Installing Python and the Python interpreter modes Copyright © 2018 Pearson Education, Ltd. CSBP119 Algorithms & Problem Solving CIT, UAEU CHAPTER 2 Input, Processing, & Output Copyright © 2018 Pearson Education, Ltd. Topics Designing a Program Input, Processing, and Output Displaying Output with print Function Comments Variables Reading Input from the Keyboard Performing Calculations More About Data Output Named Constants Introduction to Turtle Graphics Copyright © 2018 Pearson Education, Ltd. Designing a Program Programs must be designed before they are written Program development cycle: Copyright © 2018 Pearson Education, Ltd. Designing a Program (cont’d.) Determine the steps that must be taken to perform the task Break down required task into a series of steps Create an algorithm, listing logical steps that must be taken Algorithm: set of well-defined logical steps that must be taken to perform a task Copyright © 2018 Pearson Education, Ltd. Pseudocode Pseudocode: fake code Informal language that has no syntax rule Not meant to be compiled or executed Used to create model program No need to worry about syntax errors, can focus on program’s design Can be translated directly into actual code in any programming language Copyright © 2018 Pearson Education, Ltd. Example Write a program that calculates and displays the gross pay of an employee Algorithm in Pseudocode: 1. Input the number of hours worked 2. Input the hourly pay rate 3. Calculate gross pay as the number of hours worked times the hourly pay rate 4. Display the gross pay Copyright © 2018 Pearson Education, Ltd. Flowcharts Flowchart: diagram that graphically depicts the steps in a program Ovals are terminal symbols Parallelograms are input and output symbols Rectangles are processing symbols Symbols are connected by arrows that represent the flow of the program Copyright © 2018 Pearson Education, Ltd. Copyright © 2018 Pearson Education, Ltd. Input, Processing, and Output Typically, computer performs three-step process Receive input Input: any data that the program receives while it is running Perform some process on the input Example: mathematical calculation Produce output Copyright © 2018 Pearson Education, Ltd. Functions Function: piece of prewritten code that performs an operation Argument: data given to a function Statements in a program execute in the order that they appear From top to bottom Copyright © 2018 Pearson Education, Ltd. Example: Displaying Output with the print Function print ('Hello World') print function: displays output on the screen Argument: data that is printed to screen, which is the string Hello World Copyright © 2018 Pearson Education, Ltd. Strings and String Literals String: sequence of characters that is used as data String literal: string that appears in actual code of a program Must be enclosed in single (') or double (") quote marks String literal can be enclosed in triple quotes (''' or """) Enclosed string can contain both single and double quotes and can have multiple lines Copyright © 2018 Pearson Education, Ltd. Examples print ('Hello World') print ("I can display single 'quotes' here!") print ('I can display double "quotes" here') print ("""I can display 'single' and "double" quotes here""") Output: Hello World I can display single 'quotes' here! I can display double "quotes" here I can display 'single' and "double" quotes here Copyright © 2018 Pearson Education, Ltd. Comments Comments: notes of explanation within a program Ignored by Python interpreter Intended for a person reading the program’s code Begin with a # character End-line comment: appears at the end of a line of code Typically explains the purpose of that line Copyright © 2018 Pearson Education, Ltd. Example #this is a Python comment #this program displays Hello World print ('Hello World') #display statement Output: Hello World Copyright © 2018 Pearson Education, Ltd. Variables Variable: name that represents a value stored in the computer memory Used to access and manipulate data stored in memory A variable references the value it represents Assignment statement: used to create a variable and make it reference data General format is variable = expression Example: age = 29 Assignment operator: the equal sign (=) Copyright © 2018 Pearson Education, Ltd. Example #this program creates two variables width = 10 length = 5 print('width') #display the string width print(width) #display the variable width print(length) Output: width 10 5 Copyright © 2018 Pearson Education, Ltd. Variables (cont’d.) In assignment statement, variable receiving value must be on left side A variable can be passed as an argument to a function Variable name should not be enclosed in quote marks You can only use a variable if a value is assigned to it Copyright © 2018 Pearson Education, Ltd. Variable Naming Rules Rules for naming variables in Python: Variable name cannot be a Python key word Variable name cannot contain spaces First character must be a letter or an underscore After first character may use letters, digits, or underscores Variable names are case sensitive Variable name should reflect its use Copyright © 2018 Pearson Education, Ltd. Examples Copyright © 2018 Pearson Education, Ltd. Displaying Multiple Items with the print Function Python allows one to display multiple items with a single call to print Items are separated by commas when passed as arguments Arguments displayed in the order they are passed to the function Items are automatically separated by a space when displayed on screen Use end to change the ending of a printed string Use sep to change the separator between printed strings Copyright © 2018 Pearson Education, Ltd. Example #this program demonstrates variables and multiple outputs width = 10 length = 5 print('The width is ', width) print('The length is ', length) Output: The width is 10 The length is 5 Copyright © 2018 Pearson Education, Ltd. Example #this program demonstrates the use of end #default end is a new line print('The width is 10', end='&') print('The length is 5', end=‘??') Output: The width is 10 & The length is 5 ?? Copyright © 2018 Pearson Education, Ltd. Example #this program demonstrates the use of sep #default separator is a space print('The width is 10’, 'The length is 5', sep=‘#') Output: The width is 10 # The length is 5 Copyright © 2018 Pearson Education, Ltd. Variable Reassignment Variables can reference different values while program is running Garbage collection: removal of values that are no longer referenced by variables Carried out by Python interpreter A variable can refer to item of any type Variable that has been assigned to one type can be reassigned to another type Copyright © 2018 Pearson Education, Ltd. Example # This program demonstrates variable reassignment # Assign a value to the dollars variable dollars = 2.75 print('I have', dollars, 'in my account') #reassign a different value to dollars dollars = 99.95 print('Now I have', dollars, 'in my account') Output: I have 2.75 in my account Now I have 99.95 in my account Copyright © 2018 Pearson Education, Ltd. Numeric Data Types, Literals, and the str Data Type Data types: categorize value in memory e.g., int for integer, float for real number, str used for storing strings in memory Numeric literal: number written in a program No decimal point considered int, otherwise, considered float Some operations behave differently depending on data type Copyright © 2018 Pearson Education, Ltd. Example x=99 print(x) x='Take me to your leader' print(x) Output: 99 Take me to your leader Copyright © 2018 Pearson Education, Ltd. Reading Input from the Keyboard Most programs need to read input from the user Built-in input function reads input from keyboard Returns the data as a string Format: variable = input(prompt) prompt is typically a string instructing user to enter a value Does not automatically display a space after the prompt Copyright © 2018 Pearson Education, Ltd. Example #first display the prompt and store the input in name name=input("what is your name? ") #then display a greeting print('Hi', name) Output: what is your name? Hi Holly Copyright © 2018 Pearson Education, Ltd. Reading Numbers with the input Function input function always returns a string Built-in functions convert between data types int(item) converts item to an int float(item) converts item to a float Nested function call: general format: function1(function2(argument)) value returned by function2 is passed to function1 Type conversion only works if item is valid numeric value, otherwise, throws exception Copyright © 2018 Pearson Education, Ltd. Example #read the hours hours_str = input('How many hours did you work?') hours = int(hours_str) #convert string to int #read and convert in one line (nested function call) rate = float(input('what is your hourly rate?')) print('hours', hours) Print('rate', rate) Copyright © 2018 Pearson Education, Ltd. Performing Calculations Math expression: performs calculation and gives a value Math operator: tool for performing calculation Operands: values surrounding operator Variables can be used as operands Resulting value typically assigned to variable Copyright © 2018 Pearson Education, Ltd. Python Math Operators Copyright © 2018 Pearson Education, Ltd. Example #read the hours hours_str = input('How many hours did you work?') hours = int(hours_str) #convert string to int #read and convert in one line (nested function call) rate = float(input('what is your hourly rate?')) #calculate gross pay: gross_pay = hours*rate print('gross pay', gross_pay) Copyright © 2018 Pearson Education, Ltd. Exercise Convert the following algorithm to python code 1. Input the original price of an item 2. Calculate the discount as 20 percent of the original price 3. Subtract the discount from the original price. This is the sale price 4. Display the sale price Copyright © 2018 Pearson Education, Ltd. Integer vs. Floating Point Division Two types of division: / operator performs floating point division // operator performs integer division Positive results truncated, negative rounded away from zero result_1 = 5 / 2 #floating point division result_2 = 5 // 2 #integer division print('floating point division result', result_1) print('integer division result', result_2) Output: floating point division result 2.5 integer division result 2 Copyright © 2018 Pearson Education, Ltd. Operator Precedence and Grouping with Parentheses Python operator precedence: 1. Operations enclosed in parentheses Forces operations to be performed before others 2. Exponentiation (**) 3. Multiplication (*), division (/ and //), and remainder (%) 4. Addition (+) and subtraction (-) Higher precedence performed first Same precedence operators execute from left to right Copyright © 2018 Pearson Education, Ltd. Example outcome = 12.0 + 6.0 / 3.0 Copyright © 2018 Pearson Education, Ltd. More Examples Copyright © 2018 Pearson Education, Ltd. Exercise: Calculating the Average Convert the following pseudocode to python 1. Input the first test score 2. Input the second test score 3. Input the third test score 4. Calculating the average by adding the three scores then dividing the sum by 3 5. Display the average Copyright © 2018 Pearson Education, Ltd. The Exponent Operator and the Remainder Operator Exponent operator (**): Raises a number to a power x ** y = xy Remainder operator (%): Performs division and returns the remainder a.k.a. modulus operator e.g., 4%2=0, 5%2=1 Typically used to convert times and distances, and to detect odd or even numbers Copyright © 2018 Pearson Education, Ltd. Example #calculate 4 squared result = 4**2 print('4 squared is', result) #calculate 17 mod 3 result = 17%3 print('17 mod 3 is', result) Output 4 squared is 16 17 mod 3 is 2 Copyright © 2018 Pearson Education, Ltd. Mixed-Type Expressions and Data Type Conversion Data type resulting from math operation depends on data types of operands Two int values: result is an int Two float values: result is a float int and float: int temporarily converted to float, result of the operation is a float Mixed-type expression Type conversion of float to int causes truncation of fractional part Copyright © 2018 Pearson Education, Ltd. Example fvalue = 2.6 print(int(fvalue)) fvalue = -2.9 print(int(fvalue)) Output 2 -2 Copyright © 2018 Pearson Education, Ltd. Breaking Long Statements into Multiple Lines Long statements cannot be viewed on screen without scrolling and cannot be printed without cutting off Multiline continuation character (\): Allows to break a statement into multiple lines result = var1 * 2 + var2 * 3 + \ var3 * 4 + var4 * 5 Copyright © 2018 Pearson Education, Ltd. Breaking Long Statements into Multiple Lines Any part of a statement that is enclosed in parentheses can be broken without the line continuation character. print("Monday's sales are", monday, "and Tuesday's sales are", tuesday, "and Wednesday's sales are", Wednesday) total = (value1 + value2 + value3 + value4 + value5 + value6) Copyright © 2018 Pearson Education, Ltd. Escape Characters Special characters appearing in string literal Preceded by backslash (\) Examples: newline (\n), horizontal tab (\t) Copyright © 2018 Pearson Education, Ltd. String Concatenation When + operator used on two strings in performs string concatenation Useful for breaking up a long string literal print('this is ' + 'one string.') print('Enter the amount ' + 'of sales for each day and ' + 'press Enter.') Copyright © 2018 Pearson Education, Ltd. Formatting Numbers Can format display of numbers on screen using built-in format function Two arguments: Numeric value to be formatted Format specifier Returns string containing formatted number Format specifier typically includes precision and data type Can be used to indicate scientific notation, comma separators, and the minimum field width used to display the value Copyright © 2018 Pearson Education, Ltd. Formatting Numbers (cont’d.) Before formatting amount_due = 5000.0 monthly_payment = amount_due / 12.0 print('the monthly payment is', monthly_payment) Output The monthly payment is 416.666666667 After formatting print('formatted output', format(monthly_payment, '.2f') Output formatted output 416.67 Copyright © 2018 Pearson Education, Ltd. Formatting Numbers (cont’d.) The format specifier is a string that contains special characters specifying how the numbers should be formatted Example: '.2f'.2 specifies the precision to be 2 decimal places f indicates that it's a floating point number Copyright © 2018 Pearson Education, Ltd. Formatting Numbers (cont’d.) We can also specify a minimum field width, which is minimum number of spaces to display for a value Useful when we want to print numbers aligned in columns Width = 1000.0 Length = 5.0 print(format(width, '10.1f')) print(format(length, '10.1f')) Output Copyright © 2018 Pearson Education, Ltd. Formatting Numbers (cont’d.) The % symbol can be used in the format string of format function to format number as percentage To format an integer using format function: Use d as the type designator Do not specify precision Can still use format function to set field width Copyright © 2018 Pearson Education, Ltd. Examples print(format(0.5, '%')) print(format(0.5, '.0%')) Output 50.000000% 50% print(format(12, '10d')) print(format(12000, '10d')) Output 12 12000 Copyright © 2018 Pearson Education, Ltd. Named Constants A named constant is a name that represents a value that does not change during the program's execution. Example: INTEREST_RATE = 0.069 This creates a named constant named INTEREST_RATE, assigned the value 0.069. amount = balance * INTEREST_RATE Copyright © 2018 Pearson Education, Ltd. Optional Slides TURTLE GRAPHICS Copyright © 2018 Pearson Education, Ltd. Introduction to Turtle Graphics Python's turtle graphics system displays a small cursor known as a turtle. You can use Python statements to move the turtle around the screen, drawing lines and shapes. Copyright © 2018 Pearson Education, Ltd. Introduction to Turtle Graphics To use the turtle graphics system, you must import the turtle module with this statement: On PyCharm import turtle This loads the turtle module into memory On Google colab !pip3 install ColabTurtlePlus import ColabTurtlePlus.Turtle as turtle turtle.initializeTurtle() Copyright © 2018 Pearson Education, Ltd. Moving the Turtle Forward Use the turtle.forward(n) statement to move the turtle forward n pixels. >>> import turtle >>> turtle.forward(100) >>> Copyright © 2018 Pearson Education, Ltd. Turning the Turtle The turtle's initial heading is 0 degrees (east) Use the turtle.right(angle) statement to turn the turtle right by angle degrees. Use the turtle.left(angle) statement to turn the turtle left by angle degrees. Copyright © 2018 Pearson Education, Ltd. Turning the Turtle >>> import turtle >>> turtle.forward(100) >>> turtle.left(90) >>> turtle.forward(100) >>> Copyright © 2018 Pearson Education, Ltd. Turning the Turtle >>> import turtle >>> turtle.forward(100) >>> turtle.right(45) >>> turtle.forward(100) >>> Copyright © 2018 Pearson Education, Ltd. Setting the Turtle's Heading Use the turtle.setheading(angle) statement to set the turtle's heading to a specific angle. >>> import turtle >>> turtle.setheading(0) >>> turtle.forward(50) >>> turtle.setheading(90) >>> turtle.forward(100) >>> turtle.setheading(180) >>> turtle.forward(50) >>> turtle.setheading(270) >>> turtle.forward(100) >>> Copyright © 2018 Pearson Education, Ltd. Setting the Pen Up or Down When the turtle's pen is down, the turtle draws a line as it moves. By default, the pen is down. When the turtle's pen is up, the turtle does not draw as it moves. Use the turtle.penup() statement to raise the pen. Use the turtle.pendown() statement to lower the pen. Copyright © 2018 Pearson Education, Ltd. Setting the Pen Up or Down >>> import turtle >>> turtle.forward(50) >>> turtle.penup() >>> turtle.forward(25) >>> turtle.pendown() >>> turtle.forward(50) >>> turtle.penup() >>> turtle.forward(25) >>> turtle.pendown() >>> turtle.forward(50) >>> Copyright © 2018 Pearson Education, Ltd. Drawing Circles Use the turtle.circle(radius) statement to draw a circle with a specified radius. >>> import turtle >>> turtle.circle(100) >>> Copyright © 2018 Pearson Education, Ltd. Drawing Dots Use the turtle.dot() statement to draw a simple dot at the turtle's current location. >>> import turtle >>> turtle.dot() >>> turtle.forward(50) >>> turtle.dot() >>> turtle.forward(50) >>> turtle.dot() >>> turtle.forward(50) >>> Copyright © 2018 Pearson Education, Ltd. Changing the Pen Size and Drawing Color Use the turtle.pensize(width) statement to change the width of the turtle's pen, in pixels. Use the turtle.pencolor(color) statement to change the turtle's drawing color. See Appendix D in your textbook for a complete list of colors. >>> import turtle >>> turtle.pensize(5) >>> turtle.pencolor('red') >>> turtle.circle(100) >>> Copyright © 2018 Pearson Education, Ltd. Working with the Turtle's Window Use the turtle.bgcolor(color) statement to set the window's background color. See Appendix D in your textbook for a complete list of colors. Use the turtle.setup(width, height) statement to set the size of the turtle's window, in pixels. The width and height arguments are the width and height, in pixels. For example, the following interactive session creates a graphics window that is 640 pixels wide and 480 pixels high: >>> import turtle >>> turtle.setup(640, 480) >>> Copyright © 2018 Pearson Education, Ltd. Resetting the Turtle's Window The turtle.reset() statement: Erases all drawings that currently appear in the graphics window. Resets the drawing color to black. Resets the turtle to its original position in the center of the screen. Does not reset the graphics window’s background color. The turtle.clear() statement: Erases all drawings that currently appear in the graphics window. Does not change the turtle's position. Does not change the drawing color. Does not change the graphics window’s background color. The turtle.clearscreen() statement: Erases all drawings that currently appear in the graphics window. Resets the drawing color to black. Resets the turtle to its original position in the center of the screen. Resets the graphics window’s background color to white. Copyright © 2018 Pearson Education, Ltd. Working with Coordinates The turtle uses Cartesian Coordinates Copyright © 2018 Pearson Education, Ltd. Moving the Turtle to a Specific Location Use the turtle.goto(x, y) statement to move the turtle to a specific location. >>> import turtle >>> turtle.goto(0, 100) >>> turtle.goto(−100, 0) >>> turtle.goto(0, 0) >>> The turtle.pos() statement displays the turtle's current X,Y coordinates. The turtle.xcor() statement displays the turtle's current X coordinate and the turtle.ycor() statement displays the turtle's current Y coordinate. Copyright © 2018 Pearson Education, Ltd. Animation Speed Use the turtle.speed(speed) command to change the speed at which the turtle moves. The speed argument is a number in the range of 0 through 10. If you specify 0, then the turtle will make all of its moves instantly (animation is disabled). Copyright © 2018 Pearson Education, Ltd. Hiding and Displaying the Turtle Use the turtle.hideturtle() command to hide the turtle. This command does not change the way graphics are drawn, it simply hides the turtle icon. Use the turtle.showturtle() command to display the turtle. Copyright © 2018 Pearson Education, Ltd. Displaying Text Use the turtle.write(text) statement to display text in the turtle's graphics window. The text argument is a string that you want to display. The lower-left corner of the first character will be positioned at the turtle’s X and Y coordinates. Copyright © 2018 Pearson Education, Ltd. Displaying Text >>> import turtle >>> turtle.write('Hello World') >>> Copyright © 2018 Pearson Education, Ltd. Filling Shapes To fill a shape with a color: Use the turtle.begin_fill() command before drawing the shape Then use the turtle.end_fill() command after the shape is drawn. When the turtle.end_fill() command executes, the shape will be filled with the current fill color Copyright © 2018 Pearson Education, Ltd. Filling Shapes >>> import turtle >>> turtle.hideturtle() >>> turtle.fillcolor('red') >>> turtle.begin_fill() >>> turtle.circle(100) >>> turtle.end_fill() >>> Copyright © 2018 Pearson Education, Ltd. Keeping the Graphics Window Open When running a turtle graphics program outside IDLE, the graphics window closes immediately when the program is done. To prevent this, add the turtle.done() statement to the very end of your turtle graphics programs. This will cause the graphics window to remain open, so you can see its contents after the program finishes executing. Copyright © 2018 Pearson Education, Ltd. Summary This chapter covered: The program development cycle, tools for program design, and the design process Ways in which programs can receive input, particularly from the keyboard Ways in which programs can present and format output Use of comments in programs Uses of variables and named constants Tools for performing calculations in programs The turtle graphics system Copyright © 2018 Pearson Education, Ltd. CSBP119 Algorithms & Problem Solving CIT, UAEU CHAPTER 3 Decision Structures and Boolean Logic Copyright © 2018 Pearson Education, Ltd. Topics The if Statement The if-else Statement Comparing Strings Nested Decision Structures and the if-elif-else Statement Logical Operators Boolean Variables Turtle Graphics: Determining the State of the Turtle Copyright © 2018 Pearson Education, Ltd. Decision Structure Sequence structure: set of statements that execute in the order they appear Decision structure: specific action(s) performed only if a condition exists Also known as selection structure Control structure: logical design that controls order in which set of statements execute Copyright © 2018 Pearson Education, Ltd. Single Decision Structure In flowchart, diamond represents true/false condition that must be tested Actions can be conditionally executed Single alternative decision structure (one-way selection): provides only one alternative path of execution Performed only when a condition is true If condition is not true, exit the structure Copyright © 2018 Pearson Education, Ltd. Example Figure 3-1 A single alternative decision structure Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3-5 The if Statement Python syntax: if condition: Statement1 Statement2 First line known as the if clause Includes the keyword if followed by condition The condition can be true or false When the if statement executes, the condition is tested, and if it is true the block statements are executed. otherwise, block statements are skipped Copyright © 2018 Pearson Education, Ltd. Relational Operators and Boolean Expressions and Relational operator: determines whether a specific relationship exists between two values Example: greater than (>) Boolean expression: expression tested by if statement to determine if it is true or false Example: a > b true if a is greater than b; false otherwise Copyright © 2018 Pearson Education, Ltd. Relational Operators and Boolean Expressions (cont’d.) >= and y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x >> x = 1 Enter >>> y = 0 Enter >>> y < x Enter True >>> x < y Enter False >>> Copyright © 2018 Pearson Education, Ltd. Boolean Expressions in Flowchart Using a Boolean expression with the > relational operator Copyright © 2018 Pearson Education, Ltd. Relational Operators and Decision Block Any relational operator can be used in a decision block Example: if balance == 0 Example: if payment != balance Copyright © 2018 Pearson Education, Ltd. Example Write a program to find if the test score is higher than 95. HIGH_SCORE = 95 test = int(input('Enter the score for test: ' )) if test >= HIGH_SCORE: print('Congratulations!’) print('That is a great score!') Copyright © 2018 Pearson Education, Ltd. Exercise Write a program to find the absolute value of a number. Copyright © 2018 Pearson Education, Ltd. The if-else Statement Dual alternative decision structure (two-way selection): two possible paths of execution – One is taken if the condition is true, and the other if the condition is false Syntax: if condition: statements else: other statements if clause and else clause must be aligned Statements must be consistently indented Copyright © 2018 Pearson Education, Ltd. The if-else Statement (2 of 3) Figure 3-5 A dual alternative decision structure Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 15 The if-else Statement (3 of 3) Figure 3-6 Conditional execution in an if-else statement Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 16 Comparing Strings Strings can be compared using the == and != operators String comparisons are case sensitive Strings can be compared using >, =, and name2: print('Mary is greater than Mark') else: print('Mary is not greater than Mark') Program Output: Mary is greater than Mark Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 18 Nested Decision Structures A decision structure can be nested inside another decision structure Commonly needed in programs Example: Determine if someone qualifies for a loan, they must meet two conditions: Must earn at least $30,000/year Must have been employed for at least two years Check first condition, and if it is true, check second condition Copyright © 2018 Pearson Education, Ltd. Nested Decision Structures Flowchart Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 20 Nested Decision Structures rules Important to use proper indentation in a nested decision structure Important for Python interpreter Makes code more readable for programmer Rules for writing nested if statements: else clause should align with matching if clause Statements in each block must be consistently indented Copyright © 2018 Pearson Education, Ltd. Nested Decision Structures Example MIN_SALARY = 30000.0 # The minimum annual salary MIN_YEARS = 2 # The minimum years on the job salary = float(input('Enter your annual salary: ‘)) years_on_job = int(input('Enter the number of years employed: ')) if salary >= MIN_SALARY: if years_on_job >= MIN_YEARS: print('You qualify for the loan.’) else: print('You must have been employed for at least’, MIN_YEARS,'years to qualify.') else: print('You must earn at least $’, format(MIN_SALARY, ',.2f’), ' per year to qualify.', sep='') Copyright © 2018 Pearson Education, Ltd. The if-elif-else Statement if-elif-else statement: special version of a decision structure Makes logic of nested decision structures simpler to write Can include multiple elif statements Syntax: if condition_1: statement(s) elif condition_2: statement(s) Insert as many elif clauses elif condition_3: as necessary. statement(s) else statement(s) Copyright © 2018 Pearson Education, Ltd. The if-elif-else Statement (cont’d.) Alignment used with if-elif-else statement: if, elif, and else clauses are all aligned Conditionally executed blocks are consistently indented if-elif-else statement is never required, but logic easier to follow Can be accomplished by nested if-else Code can become complex, and indentation can cause problematic long lines Copyright © 2018 Pearson Education, Ltd. The if-elif-else Statement Flowchart Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 25 The if-elif-else Statement Example if score >= 90: print('Your grade is A.') elif score >= 80: print('Your grade is B.') elif score >= 70: print('Your grade is C.') elif score >= 60: print('Your grade is D.') else: print('Your grade is F.') Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 3 - 26 Logical Operators Logical operators: operators that can be used to create complex Boolean expressions and operator and or operator: binary operators, connect two Boolean expressions into a compound Boolean expression not operator: unary operator, reverses the truth of its Boolean operand Copyright © 2018 Pearson Education, Ltd. The and Operator Takes two Boolean expressions as operands Creates compound Boolean expression that is true only when both sub expressions are true Can be used to simplify nested decision structures Truth table for the and operator Expression Value of the Expression false and false false false and true false true and false false true and true true Copyright © 2018 Pearson Education, Ltd. The or Operator Takes two Boolean expressions as operands Creates compound Boolean expression that is true when either of the sub expressions is true Can be used to simplify nested decision structures Truth table for the or operator Expression Value of the Expression false or false false false or true true true or false true true or true true Copyright © 2018 Pearson Education, Ltd. Short-Circuit Evaluation Short circuit evaluation: deciding the value of a compound Boolean expression after evaluating only one sub expression Performed by the or and and operators For or operator: If left operand is true, compound expression is true. Otherwise, evaluate right operand For and operator: If left operand is false, compound expression is false. Otherwise, evaluate right operand Copyright © 2018 Pearson Education, Ltd. The not Operator Takes one Boolean expressions as operand and reverses its logical value Sometimes it may be necessary to place parentheses around an expression to clarify to what you are applying the not operator Truth table for the not operator Expression Value of the Expression true false false true Copyright © 2018 Pearson Education, Ltd. Checking Numeric Ranges with Logical Operators To determine whether a numeric value is within a specific range of values, use and Example: x >= 10 and x 20 Copyright © 2018 Pearson Education, Ltd. Boolean Variables Boolean variable: references one of two values, True or False Represented by bool data type Commonly used as flags Flag: variable that signals when some condition exists in a program Flag set to False → condition does not exist Flag set to True → condition exists Copyright © 2018 Pearson Education, Ltd. Optional Slides TURTLE GRAPHICS Copyright © 2018 Pearson Education, Ltd. Turtle Graphics: Determining the State of the Turtle (1 of 9) The turtle.xcor() and turtle.ycor() functions return the turtle's X and Y coordinates Examples of calling these functions in an if statement: if turtle.ycor() < 0: turtle.goto(0, 0) if turtle.xcor() > 100 and turtle.xcor() < 200: turtle.goto(0, 0) Copyright © 2018 Pearson Education, Ltd. Turtle Graphics: Determining the State of the Turtle (2 of 9) The turtle.heading() function returns the turtle's heading. (By default, the heading is returned in degrees.) Example of calling the function in an if statement: if turtle.heading() >= 90 and turtle.heading() 0: turtle.speed(0) Copyright © 2018 Pearson Education, Ltd. Turtle Graphics: Determining the State of the Turtle (9 of 9) See In the Spotlight: The Hit the Target Game in your textbook for numerous examples of determining the state of the turtle. Copyright © 2018 Pearson Education, Ltd. Summary This chapter covered: Decision structures, including: Single alternative decision structures Dual alternative decision structures Nested decision structures Relational operators and logical operators as used in creating Boolean expressions String comparison as used in creating Boolean expressions Boolean variables Determining the state of the turtle in Turtle Graphics Copyright © 2018 Pearson Education, Ltd. CSBP119 Algorithms & Problem Solving CIT, UAEU Chapter 4 Repetition Structures Copyright © 2018 Pearson Education, Ltd. 4-1 Topics Introduction to Repetition Structures The while Loop: a Condition-Controlled Loop The for Loop: a Count-Controlled Loop Calculating a Running Total Sentinels Input Validation Loops Nested Loops Turtle Graphics: Using Loops to Draw Designs Copyright © 2018 Pearson Education, Ltd. 4-2 Introduction to Repetition Structures Often have to write code that performs the same task multiple times Disadvantages to duplicating code Makes program large Time consuming May need to be corrected in many places Repetition structure: makes computer repeat included code as necessary Includes condition-controlled loops and count- controlled loops Copyright © 2018 Pearson Education, Ltd. 4-3 The while Loop: a Condition- Controlled Loop (1 of 4) while loop: while condition is true, do something Two parts: Condition tested for true or false value Statements repeated as long as condition is true In flow chart, line goes back to previous part General format: while condition: statements Copyright © 2018 Pearson Education, Ltd. 4-4 The while Loop: a Condition- Controlled Loop (2 of 4) Figure 4-1 The logic of a while loop Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 4-5 The while Loop: a Condition- Controlled Loop (3 of 4) In order for a loop to stop executing, something has to happen inside the loop to make the condition false Iteration: one execution of the body of a loop while loop is known as a pretest loop Tests condition before performing an iteration Will never execute if condition is false to start with Requires performing some steps prior to the loop Copyright © 2018 Pearson Education, Ltd. 4-6 The while Loop: a Condition- Controlled Loop (4 of 4) Example: Try this code Figure 4-3 Flowchart for Program 4-1 Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 4-7 Infinite Loops Loops must contain within themselves a way to terminate Something inside a while loop must eventually make the condition false Infinite loop: loop that does not have a way of stopping Repeats until program is interrupted Occurs when programmer forgets to include stopping code in the loop Example: Remove lines 19 to 21 from the previous example and run it again. What is the output? Copyright © 2018 Pearson Education, Ltd. 4-8 The for Loop: a Count-Controlled Loop (1 of 2) Count-Controlled loop: iterates a specific number of times Use a for statement to write count-controlled loop Designed to work with sequence of data items Iterates once for each item in the sequence General format: for variable in [val1, val2, etc]: statements Target variable: the variable which is the target of the assignment at the beginning of each iteration Copyright © 2018 Pearson Education, Ltd. 4-9 The for Loop: a Count-Controlled Loop (2 of 2) Example: Try this code Figure 4-4 The for loop Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 4 - 10 Using the range Function with the for Loop The range function simplifies the process of writing a for loop range returns an iterable object Iterable: contains a sequence of values that can be iterated over range characteristics: One argument: used as ending limit Two arguments: starting value and ending limit Three arguments: third argument is step value Copyright © 2018 Pearson Education, Ltd. 4 - 11 Using the Target Variable Inside the Loop Purpose of target variable is to reference each item in a sequence as the loop iterates Target variable can be used in calculations or tasks in the body of the loop Example: Try this code Example: calculate square root of each number in a range from 25 until 100 (can you implement it ?) Copyright © 2018 Pearson Education, Ltd. 4 - 12 Letting the User Control the Loop Iterations Sometimes the programmer does not know exactly how many times the loop will execute Can receive range inputs from the user, place them in variables, and call the range function in the for clause using these variables Example: Try this code - Be sure to consider the end cases: range does not include the ending limit Copyright © 2018 Pearson Education, Ltd. 4 - 13 Generating an Iterable Sequence that Ranges from Highest to Lowest The range function can be used to generate a sequence with numbers in descending order Make sure starting number is larger than end limit, and step value is negative Example: range(10, 0, -1) Example: What will the following code display ? Copyright © 2018 Pearson Education, Ltd. 4 - 14 Calculating a Running Total (1 of 2) Programs often need to calculate a total of a series of numbers Typically include two elements: A loop that reads each number in series An accumulator variable Known as program that keeps a running total: accumulates total and reads in series At end of loop, accumulator will reference the total Copyright © 2018 Pearson Education, Ltd. 4 - 15 Calculating a Running Total (2 of 2) Example: Change the following code to match the flowchart Figure 4-6 Logic for calculating a running total Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 4 - 16 The Augmented Assignment Operators (1 of 2) In many assignment statements, the variable on the left side of the = operator also appears on the right side of the = operator Augmented assignment operators: special set of operators designed for this type of job Shorthand operators Copyright © 2018 Pearson Education, Ltd. 4 - 17 The Augmented Assignment Operators (2 of 2) Table 4-2 Augmented assignment operators Operator Example Usage Equivalent To += x += 5 x = x + 5 −= y −= 2 y = y − 2 *= z *= 10 z = z * 10 /= a /= b a = a / b %= c %= 3 c = c % 3 //= x //= 3 x = x // 3 **= y **= 2 y = y**2 Copyright © 2018 Pearson Education, Ltd. 4 - 18 Sentinels Sentinel: special value that marks the end of a sequence of items When program reaches a sentinel, it knows that the end of the sequence of items was reached, and the loop terminates Must be distinctive enough so as not to be mistaken for a regular value in the sequence Example: when reading an input file, empty line can be used as a sentinel Copyright © 2018 Pearson Education, Ltd. 4 - 19 Input Validation Loops (1 of 3) Computer cannot tell the difference between good data and bad data If user provides bad input, program will produce bad output GIGO: garbage in, garbage out It is important to design program such that bad input is never accepted Copyright © 2018 Pearson Education, Ltd. 4 - 20 Input Validation Loops (2 of 3) Input validation: inspecting input before it is processed by the program If input is invalid, prompt user to enter correct data Commonly accomplished using a while loop which repeats as long as the input is bad If input is bad, display error message and receive another set of data If input is good, continue to process the input Copyright © 2018 Pearson Education, Ltd. 4 - 21 Input Validation Loops (3 of 3) Example: Try this code Figure 4-7 Logic containing an input validation loop Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 4 - 22 Nested Loops (1 of 3) Nested loop: loop that is contained inside another loop Example: analog clock works like a nested loop Hours hand moves once for every twelve movements of the minutes hand: for each iteration of the “hours,” do twelve iterations of “minutes” Seconds hand moves 60 times for each movement of the minutes hand: for each iteration of “minutes,” do 60 iterations of “seconds” Copyright © 2018 Pearson Education, Ltd. 4 - 23 Nested Loops (2 of 3) Example: Try this code What is the output? Example: Now add the hours loop What is the output? Figure 4-8 Flowchart for a clock simulator Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 4 - 24 Nested Loops (3 of 3) Key points about nested loops: Inner loop goes through all of its iterations for each iteration of outer loop Inner loops complete their iterations faster than outer loops Total number of iterations in nested loop: number of iterations of inner loop X number of iterations of outer loop Copyright © 2018 Pearson Education, Ltd. 4 - 25 Optional Slides TURTLE GRAPHICS Copyright © 2018 Pearson Education, Ltd. 4 - 26 Turtle Graphics: Using Loops to Draw Designs (1 of 4) You can use loops with the turtle to draw both simple shapes and elaborate designs. For example, the following for loop iterates four times to draw a square that is 100 pixels wide: for x in range(4): turtle.forward(100) turtle.right(90) Copyright © 2018 Pearson Education, Ltd. 4 - 27 Turtle Graphics: Using Loops to Draw Designs (2 of 4) This for loop iterates eight times to draw the octagon: for x in range(8): turtle.forward(100) turtle.right(45) Copyright © 2018 Pearson Education, Ltd. 4 - 28 Turtle Graphics: Using Loops to Draw Designs (3 of 4) You can create interesting designs by repeatedly drawing a simple shape, with the turtle tilted at a slightly different angle each time it draws the shape. NUM_CIRCLES = 36 # Number of circles to draw RADIUS = 100 # Radius of each circle ANGLE = 10 # Angle to turn for x in range(NUM_CIRCLES): turtle.circle(RADIUS) turtle.left(ANGLE) Copyright © 2018 Pearson Education, Ltd. 4 - 29 Turtle Graphics: Using Loops to Draw Designs (4 of 4) This code draws a sequence of 36 straight lines to make a "starburst" design. START_X = -200 # Starting X coordinate START_Y = 0 # Starting Y coordinate NUM_LINES = 36 # Number of lines to draw LINE_LENGTH = 400 # Length of each line ANGLE = 170 # Angle to turn turtle.hideturtle() turtle.penup() turtle.goto(START_X, START_Y) turtle.pendown() for x in range(NUM_LINES): turtle.forward(LINE_LENGTH) turtle.left(ANGLE) Copyright © 2018 Pearson Education, Ltd. 4 - 30 Summary This chapter covered: Repetition structures, including: Condition-controlled loops Count-controlled loops Nested loops Infinite loops and how they can be avoided range function as used in for loops Calculating a running total and augmented assignment operators Use of sentinels to terminate loops Using loops to draw turtle graphic designs Copyright © 2018 Pearson Education, Ltd. 4 - 31