1 / 38

Designing a Program: Input, Processing, and Output

Learn about the essential steps involved in designing a program, including input, processing, and output, as well as using the print function and variables. Understand the importance of comments and how to read input from the keyboard.

dlinke
Télécharger la présentation

Designing a Program: Input, Processing, and Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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 (user) to get a sense what the program is supposed to do • Ask questions about program details • Create one or more software requirements • In college course make sure you understand your professor’s requirements

  4. 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

  5. Algorithms • Set of well-defined logical steps • Must be performed in order to perform a task • Example: Making a cup of instant coffee • Remove lid from coffee jar • Put lid down on counter • Remove 1 tsp of coffee from jar • Place that coffee in a cup • Add 8 oz of boiling water to cup • Use teaspoon to stir water and coffee mixture • Stir 10 revolutions • Remove teaspoon from cup and place on counter Is this adequate? Is it detailed enough? Is anything ambiguous?

  6. Class Exercise • Write an algorithm that explains how to make a Peanut Butter and Jelly sandwich • Assume the person does not know anything about how to make sandwiches

  7. Pseudocode • Pretend 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

  8. Flowcharts • Diagram that graphically depict 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

  9. Input, Processing, and Output • Typically, computer performs three-step process • Receive input • Any data that the program receives while it is running • Perform some process on the input • Example: mathematical calculation • Produce output

  10. print Function • Function: piece of prewritten code that performs an operation • Calling a function: when programmers ask that a function execute • print function: displays output on the screen • Notice it is all lower case • Argument: data given to a function • Ex: print ("Hello from Python")

  11. String Literals • String: sequence of characters • Can be anything you can type on keyboard • Can be a word, sentence, name, nonsense • String literal: string that appears in program code • Must be enclosed in single (') or double (") quote marks • Putting a quote in string requires special instructions • Must be enclosed in triple quotes (''' or """) • Allows enclosed string to contain both single and double quotes and can have multiple lines Examples: print("Kate Austen") print('''Cara O'Brian''' "Cara O’Brian") print('Asheville, NC 28899')

  12. 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 # This program displays a person's name and address. print('Kate Austen') # Name print('123 Full Circle Drive') # Street address print('Asheville, NC 28899') # City, state, and ZIP

  13. Variables • Name that represents a value stored in computer memory • Used to remember, access and manipulate data stored in memory • Variable references the value • Assignment statement - used to create a variable and make it reference the desired data • General format is • variable = expression • Expression is the value, mathematical equation or function that results in a value • Assignment operator: the equal sign (=) • Examples: • age = 29 • age = current_year– birth_year

  14. Variables • In assignment statement, variable receiving value must be on left side • You cannot use a variable UNTIL a value is assigned to it • Otherwise will "get name 'variable name' is not defined" • A variable can be passed as an argument to a function, like print • Do not enclose variable name in quotes

  15. Variable Naming Rules • Rules for naming variables in Python • Should be short, but descriptive • First character must be a letter or an underscore • After first character may use letters, digits, or underscores • Variable name cannot be a Python keyword • Variable name cannot contain spaces • Use underscore instead • Variable names are case sensitive • Variable name should reflect its use • Ex: grosspay, payrate • Separate words: gross_pay, pay_rate

  16. Example Program message = "Hello Python world!" print(message) Output: Hello Python world!

  17. Change Variable Value message = "Hello Python world!" print(message) message = "Hello world!” # message has new value print(message) # something different is printed Output: Hello Python world! Hello world!

  18. Displaying Multiple Items with the print Function • Python can display multiple items on one line • Items to print are separated by commas • The items are passed as arguments • Displayed in order they are passed to print function • Items are automatically separated by a space when displayed on screen # This program demonstrates printing # multiple items on one line room = 503 print('I am staying in room number', room) Output: I am staying in room number 503

  19. Print String and Variable width = 10 length = 5 print('width is', width) print('length is', length) print('width') Output: width is 10 length is 5 width

  20. Variable Naming Errors • 3dGraph # What is wrong with this variable? • Error: variable can’t start with number • Mixture#3 # What is wrong with this variable? • Error: variable may only use letters, digits or underscores • temperature = 74.5 # Create a variable • print(tempereture) # What is wrong with this variable? • Error: misspelled variable name • Gives error: NameError: name ‘temperature’ is not defined • temperature = 74.5 # Create a variable • print(Temperature) # What is wrong with this variable? • # Error: inconsistent use of case

  21. Variable Reassignment • Variables can reference different values while program is running # This program demonstrates variable reassignment. # Assign a value to the dollars variable. dollars = 2.75 print('I had $', dollars, 'in my account.') # Reassign dollars so it references a different value. dollars = 99.95 print('But now I have $', dollars, 'in my account!') Output: I had $ 2.75 in my account. But now I have $ 99.95 in my account!

  22. Data Types • Categorize value in memory • Written in memory differently • int for integer • float for real number • str used for storing strings in memory

  23. Numeric Literal • Number written in a program • int - whole number. Doesn’t have decimal point • Examples: 7, 124, -9 • If number with decimal point is placed in int variable, number is truncated to smallest number • float - has decimal point • Examples: 1.5. 3.14159, 5.0

  24. Changing Case in String • You can change lower case letters in a string to upper case and vice versa • First assign a string to a variable • Ex: name = “adalovelace” • To upper case first letter of each word in a string • Add suffix .title() to variable name • Example: print (name.title()) • Produces: Ada Lovelace • print(name.upper()) • Produces: ADA LOVELACE • print(name.lower()) • Produces: adalovelace

  25. Combining/Concatenating Strings • You can merge two strings together • Example first_name = “Ada” last_name = “Lovelace” full_name = first_name + “ “ + last_name print (full_name) • Produces Ada Lovelace

  26. Syntax Error • When the Python interpreter doesn’t recognize something in your program as recognizable Python code • Ex: print('Cara O’Brian') has a single quote between single quotes. Python sees the third quote and doesn’t know how to handle that • Computers are very picky on syntax • Thonny IDE gives help with errors

  27. 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 telling user to enter a value • Does not automatically display a space after the prompt • You will need to add one at the end of the string so what user types doesn't merge with the string prompt

  28. Input Example Program # Get the user's first name. first_name = input('Enter your first name: ') # Get the user's last name. last_name = input('Enter your last name: ') # Print a greeting to the user. print('Hello', first_name, last_name) Output: Enter your first name: Anthony Enter your last name: Manno Hello Anthony Manno

  29. Reading Numbers with input • inputfunction always returns a string • Need to convert strings to numbers (type conversion) • int(item) converts item to an int • float(item) converts item to a float • This requires a Nested Function Call where you get input from the user AND convert it to a number in same line • General format: • function1(function2(argument)) • value returned by function2 is passed to function1 • Example: int( input("what is the temperature? ")) • This gets what they user typed and sends it immediately to function that converts it to an integer • Type conversion only works if item is valid numeric value, otherwise, gives error

  30. Numeric Input Example # Get the user's name, age, and income. name = input('What is your name? ') age = int(input('What is your age? ')) income = float(input('What is your income? ')) # Display the data. print('Here is the data you entered:') print('Name:', name) print('Age:', age) print('Income:', income) Output: What is your name? Anthony What is your age? 20 What is your income? 10000 Here is the data you entered: Name: Anthony Age: 20 Income: 10000.0

  31. Performing Calculations • Math expression: performs calculation and gives a value • Math operator: tool for performing calculation • Resulting value typically assigned to variable • Example: 12 + 2 • Value returned is 14 • Operands: values surrounding operator • Variables can be used as operands • Example with variables “PayRate” and “HoursWorked” • Salary = PayRate * HoursWorked • Two types of division: • / operator performs floating point division • // operator performs integer division • Positive results truncated, negative rounded away from zero

  32. Math Program # Assign a value to the salary variable. salary = 2500.0 # Assign a value to the bonus variable. bonus = 1200.0 # Calculate the total pay by adding salary # and bonus. Assign the result to pay. pay = salary + bonus # Display the pay. print('Your pay is $', pay) Output: Your pay is $ 3700.0

  33. Exponentiation and Remainder • Exponent operator (**): Raises a number to a power • x ** y = xy • Remainder operator (%): Performs division and returns the remainder • a.k.a. modulus operator • Ex: 4%2=0, 5%2=1 • Example uses • Convert times and distances • Detect odd or even numbers

  34. Operator Precedence • Python operator precedence • Operations enclosed in parentheses • Forces operations to be performed before others • Exponentiation (**) • Multiplication (*), division (/ and //), and remainder (%) • Addition (+) and subtraction (-) • Higher precedence performed first • Same precedence operators execute from left to right

  35. Zen of Python • Guiding principles for writing code with Python to write well-designed, elegant and efficient code • Beautiful is better than ugly • Explicit is better than implicit • Simple is better than complex • Complex is better than complicated • Readability counts • In the face of ambiguity, refuse the temptation to guess • Now is better than never. • Although never is often better than right now

  36. Exercises • Do exercises for lab 2a • It is due next class

More Related