1 / 68

CSC 131 - Introduction to Computer Science I

CSC 131 - Introduction to Computer Science I. Algorithm Design & Introduction To Programming in Python. Devon M. Simmonds Computer Science Department University of North Carolina Wilmington Wilmington, NC 28403 simmondsd@uncw.edu http://www.uncw.edu/people/simmondsd/

zion
Télécharger la présentation

CSC 131 - Introduction to Computer Science I

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. CSC 131 - Introduction to Computer Science I Algorithm Design & Introduction To Programming in Python Devon M. Simmonds Computer Science Department University of North Carolina Wilmington Wilmington, NC 28403 simmondsd@uncw.edu http://www.uncw.edu/people/simmondsd/ _____________________________________________________________ Chapters 1 & 2 of course text

  2. Overview

  3. Writing Simple Programs: Variables, Expressions & Statements

  4. Basic Program Tasks: Input, Processing, and Output • Typically, a program performs three types of tasks: • Input • Receive Input (any data that the program receives while it is running) • Processing • Perform computation on the input • Output • Send results of computations to users # Python program to add two numbers # Get the first number str1 = input("Please enter 1st number: ") num1 = int(str1)#Convert str1 to int # Get the second number str2 = input ("Please enter 2nd number: ") num1 = int(str1)#Convert str1 to int # Add the two numbers sum = num1 + num2 # Print the result print ("The sum is: ", sum) Variables, Expressionsand Statements:

  5. 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 Variables, Expressionsand Statements:

  6. 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 Variables, Expressionsand Statements:

  7. Comments • Comments: notes of explanation within a program • Ignored by Python interpreter • Intended for a person reading the program’s code • Single-line comments begin with a # character • Multi-line comments: enclosed in a pair of three quote marks: ''' Comments ''' • End-line comment: appears at the end of a line of code • Typically explains the purpose of that line ''' Python program to input and add two numbers ''' # Get the first number str1 = input("Please enter 1st number: ") num1 = int(str1)#Convert str1 to int # Get the second number str2 = input ("Please enter 2nd number: ") num2 = int(str1)#Convert str1 to int # Add the two numbers sum = num1 + num2 # Print the result print ("The sum is: ", sum) Variables, Expressionsand Statements:

  8. Identifiers: Names for Things • Identifiers: names for data, functions, and other items used in a program. • Str1, num1, str2, num2, input, sum, print • Variable: a location in memory • Used to store data, code • Variables are given names: identifiers ''' Python program to input and add two numbers ''' # Get the first number str1 = input("Please enter 1st number: ") num1 = int(str1)#Convert str1 to int # Get the second number str2 = input ("Please enter 2nd number: ") num2 = int(str1)#Convert str1 to int # Add the two numbers sum = num1 + num2 # Print the result print ("The sum is: ", sum) Variables, Expressionsand Statements:

  9. 0x000 0x001 0x002 0x003 0x004 0x005 0x006 0x007 Variables in Algorithms • Variables are simply a name given to represent a place in memory. How do we instruct the computer to put a value at a specific address? Memory addresses By assigning a name to each address that we want to use.

  10. 0x000 0x001 length = 72; 0x002 0x003 72 0x004 0x005 0x006 0x007 Variables in Algorithms The process of assigning a name to a memory location is called variable declaration. The value of a variable may be changed aName= “John” John Bolt aName = “Bolt” The variable length is a symbolic name for the memory location 0x003 Memory addresses

  11. Identifiers & Variables • Variable names are used to access and manipulate data stored in memory • A variable name references the value it represents • Assignment statement: used to create a variable and make it reference data • General format is identifier = expression • Example: age = 29 • Assignment operator: the equal sign (=) Variables, Expressionsand Statements:

  12. Identifiers • An identifier is a sequence of characters that consists of letters, digits, underscores (_), and asterisk (*). • An identifier must start with a letter or an underscore. It cannot start with a digit. • An identifier cannot be a reserved word. (See Appendix A, "Python Keywords," for a list of reserved words.) Reserved words have special meanings in Python, which we will later. • An identifier can be of any length.

  13. Assignment Statements x = 1 # Assign 1 to x x = x + 1 i = j = k = 1

  14. Assignment Statements (cont’d.) • In assignment statement, variable receiving the value must be on left side • That is the item being changed is on the left of the equal sign • You can only use a variable if a value is assigned to it Variables, Expressionsand Statements:

  15. Simultaneous Assignment var1, var2, ..., varn = exp1, exp2, ..., expn x, y = y, x # Swap x with y

  16. Named Constants The value of a variable may change during the execution of a program, but a named constant or simply constant represents permanent data that never changes. Python does not have a special syntax for naming constants. You can simply create a variable to denote a constant. To distinguish a constant from a variable, use all uppercase letters to name a constant.

  17. Numerical Data Types • integer: e.g., 3, 4 • float: e.g., 3.0, 4.0 • String e.g., “To be or not to be …”

  18. Numeric Operators

  19. Overflow When a variable is assigned a value that is too large (in size) to be stored, it causes overflow. For example, executing the following statement causes overflow. >>>245.0 ** 1000 OverflowError: 'Result too large'

  20. Underflow When a floating-point number is too small (i.e., too close to zero) to be stored, it causes underflow. Python approximates it to zero. So normally you should not be concerned with underflow.

  21. Scientific Notation Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase.

  22. Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

  23. Augmented Assignment Operators Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8

  24. Type Conversion and Rounding datatype(value) i.e., int(4.5) => 4 float(4) => 4.0 str(4) => “4” round(4.6) => 5 round(4.5) => 4

  25. Software Development Process

  26. Requirement Specification A formal process that seeks to understand the problem and document in detail what the software system needs to do. This phase involves close interaction between users and designers. Most of the examples in this book are simple, and their requirements are clearly stated. In the real world, however, problems are not well defined. You need to study a problem carefully to identify its requirements.

  27. System Analysis Seeks to analyze the business process in terms of data flow, and to identify the system’s input and output. Part of the analysis entails modeling the system’s behavior. The model is intended to capture the essential elements of the system and to define services to the system.

  28. System Design The process of designing the system’s components. This phase involves the use of many levels of abstraction to decompose the problem into manageable components, identify classes and interfaces, and establish relationships among the classes and interfaces.

  29. IPO The essence of system analysis and design is input, process, and output. This is called IPO.

  30. Implementation The process of translating the system design into programs. Separate programs are written for each component and put to work together. This phase requires the use of a programming language like Python. The implementation involves coding, testing, and debugging.

  31. Testing Ensures that the code meets the requirements specification and weeds out bugs. An independent team of software engineers not involved in the design and implementation of the project usually conducts such testing.

  32. Deployment Deployment makes the project available for use.

  33. Maintenance Maintenance is concerned with changing and improving the product. A software product must continue to perform and improve in a changing environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes.

  34. Displaying Output with the print Function • Function: piece of prewritten code that performs an operation • print function: displays output on the screen • Argument: data given to a function • Example: data that is printed to screen • Statements in a program execute in the order that they appear • From top to bottom Variables, Expressionsand Statements:

  35. 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 Variables, Expressionsand Statements:

  36. 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 Variables, Expressionsand Statements:

  37. 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 Variables, Expressionsand Statements:

  38. Reassigning a Variable to a Different Type • A variable in Python can refer to items of any type Variables, Expressionsand Statements:

  39. 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 Variables, Expressionsand Statements:

  40. 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 • Type conversion only works if item is valid numeric value, otherwise, throws exception Variables, Expressionsand Statements:

  41. 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 Variables, Expressionsand Statements:

  42. Operator Precedence and Grouping with Parentheses • 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 Variables, Expressionsand Statements:

  43. 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 Variables, Expressionsand Statements:

  44. 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 Variables, Expressionsand Statements:

  45. 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 Variables, Expressionsand Statements:

  46. 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 • Example: print(‘my first name is’,\ first_name) Variables, Expressionsand Statements:

  47. 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 Variables, Expressionsand Statements:

  48. What is a program? • A sequence of instructions written in machine language that tells the CPU to take action (i.e. add two numbers) in a specific order • In this course we will learn to create programs

  49. Fetch-Decode-Execute-Store CPU operates on a simple (but fast) cycle: • Fetch: fetch instruction from memory • Decode: Decode requirements (args, etc.) • Execute: Perform operation • Store: move needed results to memory • Repeat

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

More Related