Gaddis Python 4e Chapter 02 PPT - Compatibility Mode.pdf
Document Details
Uploaded by CalmingDiscernment
null
2018
Tags
Related
- GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING - Question Bank PDF
- Programming, Data Structures And Algorithms Using Python_English (1).pdf
- Lecture 1 Introduction to Python Programming PDF
- Data Structures and Algorithms with Python and C++ PDF
- Data Structures and Algorithms in Python PDF
- Python Programming Notes PDF
Full Transcript
CHAPTER 2 Input, Processing, and 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 N...
CHAPTER 2 Input, Processing, and 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: • • • • • Design the program Write the code Correct syntax errors Test the program Correct logic errors Copyright © 2018 Pearson Education, Ltd. Designing a Program (cont’d.) • Design is the most important part of the program development cycle • Understand the task that the program is to perform • Work with customer to get a sense what the program is supposed to do • Ask questions about program details • Create one or more software requirements 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. 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. • Draw the flowchart of the algorithm for the following example. • Petrol costs SAR2 per litter. Calculate the cost of n litters of petrol. Copyright © 2018 Pearson Education, Ltd. Draw the flowchart of the algorithm for the following examples. 1. Petrol costs SAR2 per litter. Calculate the cost of n litters of petrol. 2. A water bottle costs SAR0.5. Calculate the cost of n bottles of water. Start Flowchart Input the price for one litter Input total number of litters Calculate price by multiplying cost of one litter and total number of litters Display the price Copyright © 2018 Pearson Education, Ltd. End Input, Processing, and Output • Typically, computer performs threestep 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. Displaying Output with the print Function • Function: piece of prewritten code that performs an operation This whole is a • printline function: displays output on Function the statement brackets screen Function • Argument: data given to a function • Example: data that is printed to screen • print(“my name is Kamran”) • Statements in a program execute in that they appear Anything in inverted • commas From top is String to bottom Copyright © 2018 Pearson Education, Ltd. Anything in function brackets is called the order argument Quiz 1 • print(“We are the students of BS Mathematics. We study in University of Jeddah.”) # this line will print something • In the above line, point out the following 1. Function name 2. Argument 3. Statement 4. String 5. Function Brackets 6. Inverted Commas Copyright © 2018 Pearson Education, Ltd. Important notes • print() is used to show something on screen. Example: print(“Programming”) • Comments are used to write notes to understand the code. Example: # this is my first program to print something • Variables are used to store values. Example: a=5, b=7, c=a+b • input() is used to take (read) input from the user Example: a=input(“enter value of a”) • int is used for numbers without point Example: 3,-2,0 • float is used for numbers with point Example: 1.0, 2.55,0.3 • str is used for strings Example: “Saudia”, “University” • turtle is used for working with graphics Example: For drawing a circle using 100 pixels, use the following code import turtle turtle.circle(100) 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. 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. 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. 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. 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 Copyright © 2018 Pearson Education, Ltd. Class activity (26 Sep 2019) 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 (for example, 5, 0, -3), float for real number (for example 1.0, 0.3, 2.85), str used for Name of variable is A storing strings (for example, “Saudia”, “University of Jeddah”) in memory Data type of variable is integer • A=15 Value of variable is 15 • 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. Reassigning a Variable to a Different Type • A variable in Python can refer to items of any type 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. 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. 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 • Two types of division: • / operator performs floating point division • // operator performs integer division • Positive results truncated, negative rounded away from zero 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. 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. Converting Math Formulas to Programming Statements • Operator required for any mathematical operation • When converting mathematical expression to programming statement: • May need to add multiplication operators • May need to insert parentheses 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. 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. 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. More About Data Output • print function displays line of output • Newline character at end of printed data • Special argument end='delimiter' causes print to place delimiter at end of data instead of newline character • print function uses space as item separator • Special argument sep='delimiter' causes print to use delimiter as item separator Copyright © 2018 Pearson Education, Ltd. More About Data Output (cont’d.) • Special characters appearing in string literal • Preceded by backslash (\) • Examples: newline (\n), horizontal tab (\t) • Treated as commands embedded in string • When + operator used on two strings in performs string concatenation • Useful for breaking up a long string literal 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.) • 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 or comma separator Copyright © 2018 Pearson Education, Ltd. Magic Numbers • A magic number is an unexplained numeric value that appears in a program’s code. Example: amount = balance * 0.069 • What is the value 0.069? An interest rate? A fee percentage? Only the person who wrote the code knows for sure. Copyright © 2018 Pearson Education, Ltd. The Problem with Magic Numbers • It can be difficult to determine the purpose of the number. • If the magic number is used in multiple places in the program, it can take a lot of effort to change the number in each location, should the need arise. • You take the risk of making a mistake each time you type the magic number in the program’s code. • For example, suppose you intend to type 0.069, but you accidentally type .0069. This mistake will cause mathematical errors that can be difficult to find. Copyright © 2018 Pearson Education, Ltd. Named Constants • You should use named constants instead of magic numbers. • 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. It can be used instead of the magic number: amount = balance * INTEREST_RATE Copyright © 2018 Pearson Education, Ltd. Advantages of Using Named Constants • Named constants make code self-explanatory (selfdocumenting) • Named constants make code easier to maintain (change the value assigned to the constant, and the new value takes effect everywhere the constant is used) • Named constants help prevent typographical errors that are common when using magic numbers Copyright © 2018 Pearson Education, Ltd.