Writing Python Programs, Numerical Data Types
|
|
- Pierce Lucas
- 5 years ago
- Views:
Transcription
1 Writing Python Programs, Numerical Data Types Michael Mandel Lecture 2 Methods in Computational Linguistics I The City University of New York, Graduate Center b
2 Outline Writing python programs Software Development Process Example: Temperature Converter Elements of Programs Assignment Statements Definite Loops Example Program: Future Value Computing with nunmbers Numeric Data Types Type Conversions Using the Math Library Example: Factorial
3 Writing python programs Textbook chapter 2
4 Objectives Concepts To know the steps in an orderly software development process. To understand programs following the input, process, output (IPO) pattern and be able to modify them in simple ways. To understand the rules for forming valid Python identifiers and expressions. Specifics: To be able to understand and write: Python statements to output information to the screen assign values to variables get numeric information entered from the keyboard perform a counted loop
5 The software development process Writing python programs
6 The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase. Analyze the problem Determine specification Create a design Implement the design Test/debug the program Maintain the program
7 The Software Development Process Analyze the Problem Figure out exactly the problem to be solved. Try to understand it as much as possible.
8 The Software Development Process Determine Specifications Describe exactly what your program will do. Don t worry about how the program will work, but what it will do. Includes describing the inputs, outputs, and how they relate to one another.
9 The Software Development Process Create a Design Formulate the overall structure of the program. This is where the how of the program gets worked out. Develop your own algorithm that meets the specifications.
10 The Software Development Process Implement the Design Translate the design into a computer language. In this course we will use Python.
11 The Software Development Process Test/Debug the Program Try out your program to see if it worked. If there are any errors (bugs), they need to be located and fixed. This process is called debugging. Your goal is to find errors, so try everything that might break your program!
12 The Software Development Process Maintain the Program Continue developing the program in response to the needs of your users. In the real world, most programs are never completely finished they evolve over time.
13 Example program: Temperature converter Writing python programs
14 Example Program: Temperature Converter Analysis the temperature is given in Celsius, user wants it expressed in degrees Fahrenheit. Specification Input temperature in Celsius Output temperature in Fahrenheit Output = 9/5(input) + 32
15 Example Program: Temperature Converter Design Input, Process, Output (IPO) Prompt the user for input (Celsius temperature) Process it to convert it to Fahrenheit using F = 9/5(C) + 32 Output the result by displaying it on the screen
16 Example Program: Temperature Converter Before we start coding, let s write a rough draft of the program in pseudocode Pseudocode is precise English that describes what a program does, step by step. Using pseudocode, we can concentrate on the algorithm rather than the programming language.
17 Example Program: Temperature Converter Pseudocode: Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as (9/5)*celsius+32 Output fahrenheit Now we need to convert this to Python!
18 Example Program: Temperature Converter # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def convert(): celsius = eval(input("what is the Celsius temperature? ")) fahrenheit = (9/5) * celsius + 32 print("the temperature is ",fahrenheit," degrees Fahrenheit.") convert()
19 Example Program: Temperature Converter Once we write a program, we should test it! >>> What is the Celsius temperature? 0 The temperature is 32.0 degrees Fahrenheit. >>> convert() What is the Celsius temperature? 100 The temperature is degrees Fahrenheit. >>> convert() What is the Celsius temperature? -40 The temperature is degrees Fahrenheit. >>>
20 Elements of programs Writing python programs
21 Elements of Programs Names Names are given to variables (celsius, fahrenheit), modules (main, convert), etc. These names are called identifiers Every identifier must begin with a letter or underscore ( _ ), followed by any sequence of letters, digits, or underscores. Identifiers are case sensitive.
22 Elements of Programs These are all different, valid names X Celsius Spam spam spam Spam_and_Eggs Spam_And_Eggs
23 Elements of Programs Some identifiers are part of Python itself. These identifiers are known as reserved words (or keywords). This means they are not available for you to use as a name for a variable, etc. in your program. and, del, for, is, raise, assert, elif, in, print, etc. For a complete list, see Table 2.1 (p. 32)
24 Elements of Programs Expressions The fragments of code that produce or calculate new data values are called expressions. Literals are used to represent a specific value, e.g. 3.9, 1, 1.0 Simple identifiers can also be expressions. Also included are strings (textual data) and string literals (like "Hello").
25 Elements of Programs >>> x = 5 >>> x 5 >>> print(x) 5 >>> print(spam) NameError is the error when you try to use a variable without a value assigned to it. Traceback (most recent call last): File "<pyshell#15>", line 1, in -toplevelprint spam NameError: name 'spam' is not defined >>>
26 Elements of Programs Simpler expressions can be combined using operators. +, -, *, /, ** Spaces are irrelevant within an expression. The normal mathematical precedence applies. ((x1 x2) / 2*n) + (spam / k**3)
27 Elements of Programs Output Statements print() print(<expr>, <expr>,, <expr>) A print statement can print any number of expressions. Successive print statements will display on separate lines. A bare print() will print a blank line.
28 Elements of Programs print(3+4) print(3, 4, 3+4) print() print(3, 4, end=" "), print(3 + 4) print("the answer is", 3+4) The answer is 7
29 Assignment statements Writing python programs
30 Assignment Statements Simple Assignment <variable> = <expr> variable is an identifier, expr is an expression The expression on the RHS is evaluated to produce a value which is then associated with the variable named on the LHS.
31 Assignment Statements x = 3.9 * x * (1-x) fahrenheit = 9/5 * celsius + 32 x = 5
32 Assignment Statements Variables can be reassigned as many times as you want! >>> myvar = 0 >>> myvar 0 >>> myvar = 7 >>> myvar 7 >>> myvar = myvar + 1 >>> myvar 8 >>>
33 Assignment Statements Variables are like a box we can put values in. When a variable changes, the old value is erased and a new one is written in.
34 Assignment Statements Technically, this model of assignment is simplistic for Python. Python doesn't overwrite these memory locations (boxes). Assigning a variable is more like putting a sticky note on a value and saying, this is x.
35 Assigning Input The purpose of an input statement is to get input from the user and store it into a variable. <variable> = eval(input(<prompt>)) Here, eval is wrapped around the input function.
36 Assigning Input First the prompt is printed The input part waits for the user to enter a value and press <enter> The expression that was entered is evaluated to turn it from a string of characters into a Python value (a number). The value is assigned to the variable. For string input: <var> = input(<prompt>)
37 Assigning Input Beware: the eval function is very powerful and potentially dangerous! When we evaluate user input, we allow the user to enter a portion of our program, which Python will then evaluate.
38 Assigning Input Someone who knows Python could exploit this ability and enter malicious instructions, e.g. capture private information or delete files on the computer. This is called a code injection attack, because an attacker is injecting malicious code into the running program.
39 Assigning Input When writing programs for your own personal use, this is probably not much of an issue. When the input is coming from untrusted sources, like users on the Internet, the use of eval could be disastrous. We will see some safer alternatives in the next chapter.
40 Simultaneous Assignment Several values can be calculated at the same time <var>, <var>, = <expr>, <expr>, Evaluate the expressions in the RHS and assign them to the variables on the LHS
41 Simultaneous Assignment sum, diff = x+y, x-y How could you use this to swap the values for x and y? Why doesn t this work? x = y y = x We could use a temporary variable
42 Simultaneous Assignment We can swap the values of two variables quite easily in Python! x, y = y, x >>> x = 3 >>> y = 4 >>> print x, y 3 4 >>> x, y = y, x >>> print x, y 4 3
43 Simultaneous Assignment We can use this same idea to input multiple variables from a single input statement! Use commas to separate the inputs def spamneggs(): spam, eggs = eval(input("enter # of slices of spam followed by # of eggs: ")) print ("You ordered", eggs, "eggs and", spam, "slices of spam. Yum! ) >>> spamneggs() Enter the number of slices of spam followed by the number of eggs: 3, 2 You ordered 2 eggs and 3 slices of spam. Yum! >>>
44 Definite loops Writing python programs
45 Definite Loops A definite loop executes a definite number of times, i.e., at the time Python starts the loop it knows exactly how many iterations to do. for <var> in <sequence>: <body> The beginning and end of the body are indicated by indentation.
46 Definite Loops for <var> in <sequence>: <body> The variable after the for is called the loop index. It takes on each successive value in sequence. Often, the sequence portion consists of a list of values. A list is a sequence of expressions in square brackets.
47 Definite Loops >>> for i in [0,1,2,3]: print (i) >>> for odd in [1, 3, 5, 7]: print(odd*odd) >>>
48 Definite Loops In chaos.py, what did range(10) do? >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range is a built-in Python function that generates a sequence of numbers, starting with 0. list is a built-in Python function that turns the sequence into an explicit list The body of the loop executes 10 times.
49 Definite Loops for loops alter the flow of program execution, so they are referred to as control structures.
50 Example program: Future value Writing python programs
51 Example Program: Future Value Analysis Money deposited in a bank account earns interest. How much will the account be worth 10 years from now? Inputs: principal, interest rate Output: value of the investment in 10 years
52 Example Program: Future Value Specification User enters the initial amount to invest, the principal User enters an annual percentage rate, the interest The specifications can be represented like this
53 Example Program: Future Value Program Future Value Inputs principal The amount of money being invested, in dollars apr The annual percentage rate expressed as a decimal number. Output The value of the investment 10 years in the future Relatonship Value after one year is given by principal * (1 + apr). This needs to be done 10 times.
54 Example Program: Future Value Design (pseudocode) Print an introduction Input the amount of the principal (principal) Input the annual percentage rate (apr) Repeat 10 times: principal = principal * (1 + apr) Output the value of principal
55 Example Program: Future Value Implementation Each line translates to one line of Python (in this case) Print an introduction print ("This program calculates the future") print ("value of a 10-year investment.") Input the amount of the principal principal = eval(input("enter the initial principal: "))
56 Example Program: Future Value Input the annual percentage rate apr = eval(input("enter the annual interest rate: ")) Repeat 10 times: for i in range(10): Calculate principal = principal * (1 + apr) principal = principal * (1 + apr) Output the value of the principal at the end of 10 years print ("The value in 10 years is:", principal)
57 Example Program: Future Value # A program to compute the value of an investment # carried 10 years into the future def futval(): print("this program calculates the future value of a 10-year investment.") principal = eval(input("enter the initial principal: ")) apr = eval(input("enter the annual interest rate: ")) for i in range(10): principal = principal * (1 + apr) print ("The value in 10 years is:", principal) futval()
58 Example Program: Future Value >>> futval() This program calculates the future value of a 10-year investment. Enter the initial principal: 100 Enter the annual interest rate:.03 The value in 10 years is: >>> futval() This program calculates the future value of a 10-year investment. Enter the initial principal: 100 Enter the annual interest rate:.10 The value in 10 years is:
59 Computing with numbers Textbook chapter 3
60 Objectives Concepts To understand the concept of data types. To be familiar with the basic numeric data types in Python. To understand the fundamental principles of how numbers are represented on a computer. Specifics To be able to use the Python math library. To understand the accumulator program pattern. To be able to read and write programs that process numerical data.
61 Numeric data types Computing with numbers
62 Numeric Data Types The information that is stored and manipulated by computer programs is referred to as data. There are two different kinds of numbers! (5, 4, 3, 6) are whole numbers they don t have a fractional part (.25,.10,.05,.01) are decimal fractions Inside the computer, whole numbers and decimal fractions are represented quite differently! We say that decimal fractions and whole numbers are two different data types.
63 Numeric Data Types The data type of an object determines what values it can have and what operations can be performed on it. Whole numbers are represented using the integer (int for short) data type. These values can be positive or negative whole numbers. Numbers that can have fractional parts are represented as floating point (or float) values.
64 Numeric Data Types How can we tell which is which? A numeric literal without a decimal point produces an int value A literal that has a decimal point is represented by a float (even if the fractional part is 0) Python has a special function to tell us the data type of any value: type() >>> type(3) <class 'int'> >>> type(3.1) <class 'float'> >>> type(3.0) <class 'float'> >>> myint = 32 >>> type(myint) <class 'int'>
65 Numeric Data Types Why do we need two number types? Values that represent counts can t be fractional (you can t have 3 ½ quarters) Most mathematical algorithms are very efficient with integers The float type stores only an approximation to the real number being represented! Since floats aren t exact, use an int whenever possible!
66 Numeric Data Types Operations on ints produce ints, operations on floats produce floats (except for /). >>> >>> >>> 3.0* >>> 3*4 12 >>> 10.0/ >>> 10/ >>> 10 // 3 3 >>> 10.0 //
67 Numeric Data Types Integer division produces a whole number. That s why 10//3 = 3! Think of it as gozinta, where 10//3 = 3 since 3 gozinta (goes into) 10 3 times (with a remainder of 1) 10%3 = 1 is the remainder of the integer division of 10 by 3. a = (a//b)(b) + (a%b)
68 Type conversion & rounding Computing with numbers
69 Type Conversions & Rounding We know that combining an int with an int produces an int, and combining a float with a float produces a float. What happens when you mix an int and float in an expression? x = 5.0 * 2 What do you think should happen?
70 Type Conversions & Rounding For Python to evaluate this expression, it must either convert 5.0 to 5 and do an integer multiplication, or convert 2 to 2.0 and do a floating point multiplication. Converting a float to an int will lose information Ints can be converted to floats by adding.0
71 Type Conversion & Rounding In mixed-typed expressions Python will convert ints to floats. Sometimes we want to control the type conversion. This is called explicit typing. Converting to an int simply discards the fractional part of a float the value is truncated, not rounded.
72 Type Conversion & Rounding To round off numbers, use the built-in round function which rounds to the nearest whole value. If you want to round a float into another float value, you can supply a second parameter that specifies the number of digits after the decimal point.
73 Type Conversions & Rounding >>> float(22//5) 4.0 >>> int(4.5) 4 >>> int(3.9) 3 >>> round(3.9) 4 >>> round(3) 3 >>> round( , 2) 3.14
74 Type Conversions & Rounding >>> int("32") 32 >>> float("32") 32.0 This is useful as a secure alternative to the use of eval for getting numeric data from the user.
75 Type Conversions & Rounding Using int instead of eval ensures the user can only enter valid whole numbers illegal (non-int) inputs will cause the program to crash with an error message. One downside this method does not accommodate simultaneous input.
76 Type Conversions & Rounding # A program to calculate the value of some change in dollars def change(): print("change Counter") print() print("please enter the count of each coin type.") quarters = int(input("quarters: ")) dimes = int(input("dimes: ")) nickels = int(input("nickels: ")) pennies = int(input("pennies: ")) total = quarters *.25 + dimes *.10 + nickels *.05 + pennies *.01 print() print("the total value of your change is", total)
77 Using the math library Computing with numbers
78 Using the Math Library Besides (+, -, *, /, //, **, %, abs), we have lots of other math functions available in a math library. A library is a module with some useful definitions/functions.
79 Using the Math Library Let s write a program to compute the roots of a quadratic equation! x = - - 2a 2 b b 4ac The only part of this we don t know how to do is find a square root but it s in the math library!
80 Using the Math Library To use a library, we need to make sure this line is in our program: import math Importing a library makes whatever functions are defined within it available to the program.
81 Using the Math Library To access the sqrt library routine, we need to access it as math.sqrt(x) Using this dot notation tells Python to use the sqrt function found in the math library module. To calculate the root, you can do discroot = math.sqrt(b*b 4*a*c)
82 Using the Math Library # A program that computes the real roots of a quadratic equation. # Illustrates use of the math library. # Note: This program crashes if the equation has no real roots. import math # Makes the math library available. def quadratic(): print("this program finds the real solutions to a quadratic") print() a, b, c = eval(input("please enter the coefficients (a, b, c): ")) discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print() print("the solutions are:", root1, root2 )
83 Using the Math Library This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 3, 4, -1 What do you suppose this means? This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1, 2, 3 The solutions are: Traceback (most recent call last): File "<pyshell#26>", line 1, in -toplevelmain() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 14, in main discroot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error
84 Using the Math Library If a = 1, b = 2, c = 3, then we are trying to take the square root of a negative number! Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root?
85 Using the Math Library Python Mathematics English pi An approximation of pi e e An approximation of e sqrt(x) p x The square root of x sin(x) sin x The sine of x cos(x) cos x The cosine of x tan(x) tan x The tangent of x asin(x) arcsin x The inverse of sine x acos(x) arccos x The inverse of cosine x atan(x) arctan x The inverse of tangent x
86 Using the Math Library Python Mathematics English log(x) ln x The natural (base e) logarithm of x log10(x) exp(x) ceil(x) floor(x) log 10 e x x x x The common (base 10) logarithm of x The exponential of x The smallest whole number >= x The largest whole number <= x
87 Accumulating results: Factorial Computing with numbers
88 Accumulating Results: Factorial Say you are waiting in a line with five other people. How many ways are there to arrange the six people? is the factorial of 6 (abbreviated 6!) Factorial is defined as: n! = n(n-1)(n-2) (1) So, 6! = 6*5*4*3*2*1 = 720
89 Accumulating Results: Factorial How we could we write a program to do this? Input number to take factorial of: n Compute factorial of n: fact Output: fact
90 Accumulating Results: Factorial How did we calculate 6!? 6*5 = 30 Take that 30, and 30 * 4 = 120 Take that 120, and 120 * 3 = 360 Take that 360, and 360 * 2 = 720 Take that 720, and 720 * 1 = 720
91 Accumulating Results: Factorial What s really going on? We re doing repeated multiplications, and we re keeping track of the running product. This algorithm is known as an accumulator, because we re building up or accumulating the answer in a variable, known as the accumulator variable.
92 Accumulating Results: Factorial The general form of an accumulator algorithm looks like this: Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable
93 Accumulating Results: Factorial It looks like we ll need a loop! fact = 1 for factor in [6, 5, 4, 3, 2, 1]: fact = fact * factor Let s trace through it to verify that this works!
94 Accumulating Results: Factorial Why did we need to initialize fact to 1? There are a couple reasons Each time through the loop, the previous value of fact is used to calculate the next value of fact. By doing the initialization, you know fact will have a value the first time through. If you use fact without assigning it a value, what does Python do?
95 Accumulating Results: Factorial Since multiplication is associative and commutative, we can rewrite our program as: fact = 1 for factor in [2, 3, 4, 5, 6]: fact = fact * factor Great! But what if we want to find the factorial of some other number??
96 Accumulating Results: Factorial What does range(n) return? 0, 1, 2, 3,, n-1 range has another optional parameter! range(start, n) returns start, start + 1,, n-1 But wait! There s more! range(start, n, step) start, start+step,, n-1 list(<sequence>) to make a list
97 Accumulating Results: Factorial Let s try some examples! >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(5,10)) [5, 6, 7, 8, 9] >>> list(range(5,10,2)) [5, 7, 9]
98 Accumulating Results: Factorial Using this souped-up range statement, we can do the range for our loop a couple different ways. We can count up from 2 to n: range(2, n+1) (Why did we have to use n+1?) We can count down from n to 2: range(n, 1, -1)
99 Accumulating Results: Factorial Our completed factorial program: # Program to compute the factorial of a number # Illustrates for loop with an accumulator def factorial(): n = eval(input("please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact * factor print("the factorial of", n, "is", fact) factorial()
100 The Limits of Int What is 100!? >>> factorial() Please enter a whole number: 100 The factorial of 100 is Wow! That s a pretty big number!
101 The Limits of Int Newer versions of Python can handle it, but Python (#0, Apr , 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright Stichting Mathematisch Centrum, Amsterdam >>> import fact >>> fact.main() Please enter a whole number: Traceback (innermost last): File "<pyshell#1>", line 1, in? fact.main() File "C:\PROGRA~1\PYTHON~1.2\fact.py", line 5, in main fact=fact*factor OverflowError: integer multiplication
102 The Limits of Int What s going on? While there are an infinite number of integers, there is a finite range of ints that can be represented. This range depends on the number of bits a particular CPU uses to represent an integer value.
103 The Limits of Int Typical PCs use 32 bits or 64. That means there are 2 32 possible values, centered at 0. This range then is 2 31 to We need to subtract one from the top end to account for 0. But our 100! is much larger than this. How does it work?
104 Handling Large Numbers Does switching to float data types get us around the limitations of ints? If we initialize the accumulator to 1.0, we get >>> main() Please enter a whole number: 30 The factorial of 30 is e+32 We no longer get an exact answer!
105 Handling Large Numbers: Long Int Very large and very small numbers are expressed in scientific or exponential notation e+32 means * Here the decimal needs to be moved right 32 decimal places to get the original number, but there are only 16 digits, so 16 digits of precision have been lost.
106 Handling Large Numbers Floats are approximations Floats allow us to represent a larger range of values, but with fixed precision. Python has a solution, expanding ints! Python ints are not a fixed size and expand to handle whatever value it holds.
107 Handling Large Numbers Newer versions of Python automatically convert your ints to expanded form when they grow so large as to overflow. We get indefinitely large values (e.g. 100!) at the cost of speed and memory
108 Summary
109 Outline Writing python programs Software Development Process Example: Temperature Converter Elements of Programs Assignment Statements Definite Loops Example Program: Future Value Computing with nunmbers Numeric Data Types Type Conversions Using the Math Library Example: Factorial
110 Things to do... Readings from Textbook for next time: Chapter 5: Sequences: Strings, Lists, and Files Practicum 3 Practice computing with numbers Homework 1 posted on course website Turn in via github classroom Go through code examples again Lecture 2 Chapter 2 Chapter 3
111 Any Questions?
112 Acknowledgements Slides adapted & reused from Rachel Rakov's Methods in Computational Linguistics 1 course, Fall 2016 Some slides in this presentation have been adapted from the following sources: Python Programming: An Introduction to Computer Science (third edition) textbook slides, by John Zelle, Franklin, Beedle & Associates,
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 3/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 2 Writing Simple Programs Python Programming, 3/e 1 Objectives n To know the steps in an orderly software development process. n To understand
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 3 Instructor: Long Ma The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications
More informationCITS 1401 Problem Solving & Programming
CITS 1401 Problem Solving & Programming Tim French Lecture 03 Numeric Data Processing (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives of
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 2 Python Programming, 2/e 1 Objectives n To be able to understand and write Python statements to output information to the screen, assign
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 2 The Department of Computer Science Chapter 2 Elements of Programs-Objectives To be able to understand and write Python
More informationCITS 4406 Problem Solving & Programming
CITS 4406 Problem Solving & Programming Tim French Lecture 02 The Software Development Process (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives
More informationLecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming
Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values
More informationLecture Numbers. Richard E Sarkis CSC 161: The Art of Programming
Lecture Numbers Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To understand the concept of data types To be familiar with the basic numeric data types in Python To be able
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 2 Instructor: Long Ma The Department of Computer Science Review Install and test python Basic concept of computers Test simple
More informationCSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial
CSI31 Lecture 5 Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial 1 3.1 Numberic Data Types When computers were first developed, they were seen primarily as
More informationComp 151. More on Arithmetic and intro to Objects
Comp 151 More on Arithmetic and intro to Objects Admin Any questions 2 The Project Lets talk about the project. What do you need A 'accumulator' variable. Start outside of the loop Lets look at your book's
More informationLast Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2
1 Last Time integer/float/string import math math.sqrt() math.pi Python Programming, 2/e 2 Extra Ques:on from Lab 2 Using loops and two print statements, have Python print out the following: * * * * *
More informationComp 151. More on Arithmetic and number types
Comp 151 More on Arithmetic and number types Admin Any questions 2 Strings Remember Strings from last time Strings represent text. Discussion of data representation in a computer 1000001 = 65 (A) 110000
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives æ To understand the programming pattern simple decision and its implementation
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives n To understand the programming pattern simple decision and its implementation
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 1 The Department of Computer Science Objectives 2 To understand the programming pattern simple decision and its implementation
More informationFile processing and decision structures
File processing and decision structures Michael Mandel Lecture 4 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture04final.ipynb
More informationWorlframalpha.com Facebook Report
Worlframalpha.com Facebook Report For Tuesday: have read up through chapter 2 Next week will start chapter 3 New lab today: Simple Programs Integer division? o 1//3 o - 1//3 Range start at something other
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 2 Instructor: Long Ma The Department of Computer Science Quick review one-way or simple decision if :
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 1 Instructor: Long Ma The Department of Computer Science Objectives---Decision Structures 2 To understand the programming
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision
More informationChapter 2 Writing Simple Programs
Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for
More informationIntroduction to Engineering gii
25.108 Introduction to Engineering gii Dr. Jay Weitzen Lecture Notes I: Introduction to Matlab from Gilat Book MATLAB - Lecture # 1 Starting with MATLAB / Chapter 1 Topics Covered: 1. Introduction. 2.
More informationLoop structures and booleans
Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb
More informationIntroduction to Computer Programming in Python Dr. William C. Bulko. Data Types
Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have
More informationMethods CSC 121 Fall 2014 Howard Rosenthal
Methods CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class Learn the syntax of method construction Learn both void methods and methods that
More informationIntroduction to Programming
Introduction to Programming Department of Computer Science and Information Systems Tingting Han (afternoon), Steve Maybank (evening) tingting@dcs.bbk.ac.uk sjmaybank@dcs.bbk.ac.uk Autumn 2017 Week 4: More
More informationChapter 2. Outline. Simple C++ Programs
Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.
More informationComputing with Numbers
Computing with Numbers Example output: Numeric Data Types Numeric Data Types Whole numbers are represented using the integer data type (int for short).values of type int can be positive or negative whole
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationExpressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.
Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions Grace Murray Hopper Expressions Eric Roberts CSCI 121 January 30, 2018 Grace Hopper was one of the pioneers of modern computing, working with
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Mid-term Review Instructor: Long Ma The Department of Computer Science Basic Model of a Computer Input CPU Control Unit Arithmetic
More informationSI Networked Computing: Storage, Communication, and Processing, Winter 2009
University of Michigan Deep Blue deepblue.lib.umich.edu 2009-01 SI 502 - Networked Computing: Storage, Communication, and Processing, Winter 2009 Severance, Charles Severance, C. (2008, December 19). Networked
More informationOutline: Search and Recursion (Ch13)
Search and Recursion Michael Mandel Lecture 12 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture12final.ipynb
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More information" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*
! " if " %&% ifelse!()!() " &% ifelif-else "*+ % + & "*- +bool (.%) "%.* *%!!%.* *%* 0* **!! 0.*%* %. *% % % % +*.* **% * 3 4! * convert.py A program to convert Celsius temps to Fahrenheit by: Susan Computewell
More informationString and list processing
String and list processing Michael Mandel Lecture 3 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture03final.ipynb
More informationArithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37
2.2 Arithmetic 37 This is particularly important when programs are written by more than one person. It may be obvious to you that cv stands for can volume and not current velocity, but will it be obvious
More information6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x
(Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)
More informationMethods CSC 121 Spring 2017 Howard Rosenthal
Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationMethods CSC 121 Fall 2016 Howard Rosenthal
Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods
More informationIntroduction to Python, Cplex and Gurobi
Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python
More informationCOMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.
COMP1730/COMP6730 Programming for Scientists Data: Values, types and expressions. Lecture outline * Data and data types. * Expressions: computing values. * Variables: remembering values. What is data?
More informationC++ Programming Lecture 11 Functions Part I
C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs
More informationLESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long
LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be
More information4. Modules and Functions
4. Modules and Functions The Usual Idea of a Function Topics Modules Using import Using functions from math A first look at defining functions sqrt 9 3 A factory that has inputs and builds outputs. Why
More informationCS 115 Lecture 4. More Python; testing software. Neil Moore
CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement
More informationPython Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17
Python Numbers CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 (adapted from Meeden, Evans & Mayberry) 2 Learning Outcomes To become familiar with the basic
More informationProgramming with Python
Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2
More informationPROGRAMMING WITH MATLAB DR. AHMET AKBULUT
PROGRAMMING WITH MATLAB DR. AHMET AKBULUT OVERVIEW WEEK 1 What is MATLAB? A powerful software tool: Scientific and engineering computations Signal processing Data analysis and visualization Physical system
More informationGoals for This Lecture:
Goals for This Lecture: Understand integer arithmetic Understand mixed-mode arithmetic Understand the hierarchy of arithmetic operations Introduce the use of intrinsic functions Real Arithmetic Valid expressions
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building
More informationData Types and Basic Calculation
Data Types and Basic Calculation Intrinsic Data Types Fortran supports five intrinsic data types: 1. INTEGER for exact whole numbers e.g., 1, 100, 534, -18, -654321, etc. 2. REAL for approximate, fractional
More informationPrimitive Data, Variables, and Expressions; Simple Conditional Execution
Unit 2, Part 1 Primitive Data, Variables, and Expressions; Simple Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Overview of the Programming Process Analysis/Specification
More informationGetting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013
CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?
More informationLesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University
Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only
More informationComputer Programming in MATLAB
Computer Programming in MATLAB Prof. Dr. İrfan KAYMAZ Atatürk University Engineering Faculty Department of Mechanical Engineering What is a computer??? Computer is a device that computes, especially a
More informationPython Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]
Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.
More informationEngineering Problem Solving with C++, Etter/Ingber
Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input
More informationCHAPTER 3: CORE PROGRAMMING ELEMENTS
Variables CHAPTER 3: CORE PROGRAMMING ELEMENTS Introduction to Computer Science Using Ruby A variable is a single datum or an accumulation of data attached to a name The datum is (or data are) stored in
More informationCOMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods
COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information
More informationChapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.
Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing
More informationPython. Objects. Geog 271 Geographic Data Analysis Fall 2010
Python This handout covers a very small subset of the Python language, nearly sufficient for exercises in this course. The rest of the language and its libraries are covered in many fine books and in free
More informationCSCE 120: Learning To Code
CSCE 120: Learning To Code Manipulating Data I Introduction This module is designed to get you started working with data by understanding and using variables and data types in JavaScript. It will also
More informationCMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationIntroduction to Matlab
Introduction to Matlab Kristian Sandberg Department of Applied Mathematics University of Colorado Goal The goal with this worksheet is to give a brief introduction to the mathematical software Matlab.
More informationANSI C Programming Simple Programs
ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double
More informationCS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore
CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:
More informationPIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment
PIC 10A Lecture 3: More About Variables, Arithmetic, Casting, Assignment Assigning values to variables Our variables last time did not seem very variable. They always had the same value! Variables stores
More informationFundamentals of Programming (Python) Getting Started with Programming
Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
More information9 Using Equation Networks
9 Using Equation Networks In this chapter Introduction to Equation Networks 244 Equation format 247 Using register address lists 254 Setting up an enable contact 255 Equations displayed within the Network
More informationOutline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An
CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationChapter 2. Elementary Programming
Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,
More informationCT 229 Java Syntax Continued
CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment
More informationProgram Structure and Format
Program Structure and Format PROGRAM program-name IMPLICIT NONE specification part execution part subprogram part END PROGRAM program-name Comments Comments should be used liberally to improve readability.
More informationCEN 414 Java Programming
CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea
More informationWhat is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment
What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful
More informationGetting Started with Python
Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
More information3.1. Chapter 3: The cin Object. Expressions and Interactivity
Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 The cin Object Standard input stream object, normally the keyboard,
More informationENGR 101 Engineering Design Workshop
ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as
More informationVariables, expressions and statements
Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the
More informationMath 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy.
Math 340 Fall 2014, Victor Matveev Binary system, round-off errors, loss of significance, and double precision accuracy. 1. Bits and the binary number system A bit is one digit in a binary representation
More informationAlgorithms and Programming I. Lecture#12 Spring 2015
Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College August 31, 2015 Outline Outline 1 Chapter 1 Outline Textbook Data Structures and Algorithms Using Python and C++ David M.
More informationChapter 3 Mathematical Functions, Strings, and Objects
Chapter 3 Mathematical Functions, Strings, and Objects 1 Motivations Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as
More information>>> * *(25**0.16) *10*(25**0.16)
#An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines
More informationMAT 003 Brian Killough s Instructor Notes Saint Leo University
MAT 003 Brian Killough s Instructor Notes Saint Leo University Success in online courses requires self-motivation and discipline. It is anticipated that students will read the textbook and complete sample
More informationLecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?
Lecture 14 Math in C Daily Puzzle Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =? Daily Puzzle SOLUTION Eleven plus two = twelve plus one Announcements
More informationTable of Laplace Transforms
Table of Laplace Transforms 1 1 2 3 4, p > -1 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Heaviside Function 27 28. Dirac Delta Function 29 30. 31 32. 1 33 34. 35 36. 37 Laplace Transforms
More informationCustom Variables (Virtual Variables)
Page 1 of 7 Custom Variables (Virtual Variables) Allocate not only allows you to select standard variables, but also allows you to create your own unique demographic variables. You may create new variables
More informationMath Day 2 Programming: How to make computers do math for you
Math Day 2 Programming: How to make computers do math for you Matt Coles February 10, 2015 1 Intro to Python (15min) Python is an example of a programming language. There are many programming languages.
More informationENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20
page 1 of 9 ENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20 Steve Norman Department of Electrical & Computer Engineering University of Calgary November 2017 Lab instructions and
More informationcs1114 REVIEW of details test closed laptop period
python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any
More information