ENGR 102 Engineering Lab I - Computation

Similar documents
Lecture 3. Input, Output and Data Types

Expressions and Variables

ENGR (Socolofsky) Week 02 Python scripts

ENGR 102 Engineering Lab I - Computation

Full file at

BASIC ELEMENTS OF A COMPUTER PROGRAM

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans

Lecture 1. Types, Expressions, & Variables

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Ex: If you use a program to record sales, you will want to remember data:

Full file at

CSE 115. Introduction to Computer Science I

CS 115 Lecture 4. More Python; testing software. Neil Moore

Basic data types. Building blocks of computation

CSEN 102 Introduction to Computer Science

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to programming with Python

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Datatypes, Variables, and Operations

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS112 Lecture: Primitive Types, Operators, Strings

Python Input, output and variables

Variable and Data Type I

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Chapter 2 Getting Started with Python

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

REVIEW. The C++ Programming Language. CS 151 Review #2

Fundamentals of C Programming

Lecture 1. Course Overview, Python Basics

Introduction to Scientific Computing Lecture 1

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Fundamentals of Programming CS-110. Lecture 2

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Lecture 1. Course Overview, Python Basics

2 nd Week Lecture Notes

Exercise: Using Numbers

Python Programming Exercises 1

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

3 The Building Blocks: Data Types, Literals, and Variables

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

ENGR 101 Engineering Design Workshop

Introduction to Programming, Aug-Dec 2008

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CEN 414 Java Programming

Floating-point Arithmetic. where you sum up the integer to the left of the decimal point and the fraction to the right.

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

CSCE 110 Programming I

DaMPL. Language Reference Manual. Henrique Grando

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Computer Components. Software{ User Programs. Operating System. Hardware

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

ENGR 102 Engineering Lab I - Computation

Variables, Constants, and Data Types

PYTHON. Values and Variables

COSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)

Math Day 2 Programming: How to make computers do math for you

Programming with Python

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Topic 2: Introduction to Programming

Chapter 2 Working with Data Types and Operators

Visual C# Instructor s Manual Table of Contents

At full speed with Python

Variable and Data Type I

Built-in Types of Data

Programming Using C Homework 4

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

Introduction to the C++ Programming Language

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

Introduction to TURING

Number Systems. Both numbers are positive

C++ Programming: From Problem Analysis to Program Design, Third Edition

Reserved Words and Identifiers

Fundamentals: Expressions and Assignment

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSE 20. Lecture 4: Number System and Boolean Function. CSE 20: Lecture2

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Chapter 2 Elementary Programming

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CHAPTER 3: CORE PROGRAMMING ELEMENTS

Getting started with Java

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Python Working with files. May 4, 2017

COMS 1003 Fall Introduction to Computer Programming in C. Bits, Boolean Logic & Discrete Math. September 13 th

Fundamental of Programming (C)

These are reserved words of the C language. For example int, float, if, else, for, while etc.

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

Transcription:

ENGR 102 Engineering Lab I - Computation Week 03: Data Types and Console Input / Output Introduction to Types As we have already seen, 1 computers store numbers in a binary sequence of bits. The organization and interpretation of those bits depends on the type of the data stored. We have seen that floating point numbers store the sign of the number, the value of the exponent, and the value of the mantissa, or fractional part of the number (refer to Figure 1). Other data types may have a different number of bits, and each bit could have a different interpretation. For the 32-bit, single-precision floating-point number in Figure 1, the second bit from the left tells the computer whether or not to include 2 8 in the sum of numbers needed to evaluate the exponent of the float. 1 These notes are based closely on a PowerPoint presentation prepared by Dr. John Keyser for the Pilot Course version of ENGR 102. 32 bits 2 8...... 2 2 2 1 2 0 2-1 2-2...... 2-22 1 0 0 0 1 0 0 1 1 1 1 0 0 1 0 1 0 0 1 1 0 0 1 1 1 0 1 0 1 0 0 1 Sign Exponent (8 bits) Mantissa, or Fraction (23 bits) In this lecture, we will focus on the fundamental data types of integers, floating-point numbers, Booleans, 2 and strings. 3 As we learned in the notes for Week 2, Python is dynamically typed, and Python will make choices about data types when you create variables and when you use them. Thus, we need to know what data types our variables are, what the standard operators will do with different data types, and what data types the output of an operation will be. Without this knowledge, calculation errors can easily enter our programs. Figure 1: Schematic of the 32 bits used to store a single-precision, floating point variable. 2 A Boolean variable represents True and False. Booleans only have these two values. 3 As string is a list of characters strung together. We create strings using different combinations of quotation marks. Variables as Objects The most fundamental data type in Python is an object. Every variable and data type is stored as an object. Here, we use the word object with the computer science meaning, as in the phrase objectoriented programming. An object is simply a container that holds

2 engr 102-213 data 4 and methods that can act on that data. 5 We can use Python without realizing that its variables are objects, but we can access much more of the capability in Python if we use this knowledge to access the attributes and methods of Python objects. At this point, we will learn two key aspects of objects: the concepts of initialization and attributes and methods. When we initialize an object, we create it and store the necessary data associated with the object. You used the assignment operator = to create different variables in the previous two weeks of this course. If you write: 4 The object x holds the value 7.15 if we create it with the command x = 7.15 5 Methods are functions that can analyze and manipulate the data stored in the object. For example, floating-point variables have the method.is_integer(), which returns a True/False value as to whether or not the data stored in the variable is an integer. x = 7.15 you create an object x that stores the floating-point value 7.15. If you use x in an expression, 6 the x-object returns the value stored in the object. In this case, x will return 7.15 until a new value is stored in x. When Python created your x variable, it also created some additional variables stored inside x that we call attributes. These should normally be regular Python variables associated with the data stored in the object. As an example, floating point variables can be real or imaginary. It makes sense that floating-point objects have attributes that store the real and imaginary parts of the float. Continuing our example, we access the attributes of an object using the.-operator: 6 You could use a mathematical expression like (7. * x) or you may use x in a print statement like print(x). print(x.real) print(x.imag) will print the real (7.15) and imaginary (0.0) parts of the data stored in our variable x. Attributes are simply additional variables stored inside our object and accessible through the.-operator. In addition to the attributes stored in objects, objects also have internal, built-in functions that can do operations with the data stored in the object. These are also accessed using the.-operator. As an example, floating point variables can express themselves as fractions containing only integer values. The method that returns the numerator and denominator of this fraction for a floating-point variable in Python is called as_integer_ratio(). Because methods are functions (and not attributes, which are stored like variables), you always use (), and possibly additional input data, with methods. Here, we could write: x.as_integer_ratio() and when this line executes, we may see the following output: 7 (4025092166962381, 562949953421312) Using the PyCharm IDE, if you type your variable name and then a., PyCharm will show you a list of all available methods for a given object and some ideas about how to use them. In the remainder of this lecture, we will learn about the fundamental numerical, logical (Boolean), and string data types. We will also learn how to use some of the powerful methods associated with string objects. 7 Try dividing these numbers to verify whether or not this worked and whether or not it produces the output you expect. Why do you think these numbers are so large? Why might this function not return 715 and 100?

engr 102 engineering lab i - computation 3 Number Data Types: int() and float() Our two number-based data types are integers and floats. We create an integer by typing any whole number without a decimal point. 8 8 All of these are integers: 5, 12, -1, We can also convert other data types to integers using int(). The -1024, 1139, etc. int() function works on real numbers and on strings that contain only whole numbers. For example, if we write: age = 12 x = int(age) we first store the value 12 as a string in the variable age, and we then store the value of age in the variable x as an integer. 9 We create a floating-point number by including a decimal point with the number during assignment. 10 Like integers, we can create floats from other data types using the float() function. float() also works on integers and strings, and in this case, the string can define a floating-point number using a decimal. 11 Because Python is dynamically typed, variables can also change their type automatically when they are used. This is powerful and important and can easily be the source of programming 9 If we had entered age = 12., the command int(age) would give an error since the string 12. contains a decimal point, which is not part of an integer. 10 All of these are floats: 5., 12.0, -1.005, 6e-12, 7.0e5, etc. Note that the decimal point is hidden in the number 6e-12 as this is scientific notation for 0.000000000006. 11 What do you think float( 12 ) will return? Try it in Python. errors! Many of our mathematical operators 12 are defined for multi- 12 The standard list of operators is: +, -, *, /, **, //, and %. ple data types, and the type returned after the math operation may depend on the data types of the variables involved. If we add two integers, Python returns an integer; if we add two floats, Python returns a float. What if we add an integer to a float? Python makes a decision, and not all versions of Python may give the same result. For example, if we divide an integer by an integer such that the result has a remainder, Python 3.6 will return a float, but Python 2.7 will return an integer. In other words, if we type: x = 7 / 3 the result is 2.333333... in Python 3.6 and 2 in Python 2.7 since 3 and 7 are both integers and Python makes a decision about what datatype it thinks you likely want for output. Hence, it is very important to know what data type will be returned by mathematical operations. In general, you get what you expect, but not always. Booleans Boolean variables store the values True and False. These two capitalized words are built-in keywords in Python. When used in an operation, True values are assumed to have the value 1, and False values have the value 0. When you create a Boolean variable from an integer or float, though, the numeric value 0 is interpreted as False and any other value is interpreted as True.

4 engr 102-213 The built-in function to create Boolean variables from numbers is bool(). The bool() function can work on floats, integers, and strings. Note that all strings are interpreted as true except for the empty string 13 Hence, bool( 0 ) is True. 14 Strings and String Operations As stated above, we create strings using different combinations of quotation marks. We can use single-quote, double-quotes ", multiple single or double quotes: str1 = strings are fun str2 = ""you can do a lot with a string"" 13 i.e., two single quotation marks without any space between them in Python, this creates an empty string, which is like the number zero: nothing. 14 All of these evaluate to False: 0, 0.0, bool(0), bool(0.), and bool( ); all of these evaluate to True: 1, 1., 5., -13.78455664376, bool( 0 ), bool( False ), etc. Try these in an interactive Python window (ipython) to get familiar with Boolean variables. You can also create strings using the str() function for example, if you want to convert a float to a string. Some of the mathematical operators are also defined for string. For example, the plus sign + means concatenation for strings: it splices two strings together. As a result: my house + is green will produce: my houseis green. To get a space between house and green, we need a space in one of the strings: my house + is green 1 + 2 will produce: 12. Notice that Python does not guess that you wanted to add two integers and convert your strings to integers. Since + is defined as concatenation for strings, when you add two strings, you get the two strings spliced together. The multiplication operator * is also defined for strings and will repeat the string the integer number of times implied by the multiplication. 15 We can use this new understanding of string behavior and type conversions to produce much more readable results from our programs using print(). Consider the case we would like our program to output: 15 Python expects an integer in the string multiplication and will not convert a float to an integer; hence: 3 * you will produce: youyouyou. 3. * you will throw an error. A sphere of radius 12.0 cm contains 7238.2 cubic centimeters We can assemble this string as follows (this is just one of many ways): r = 12. vol = 4. / 3. * pi * r**3 out_text = A sphere of radius + str(r) + cm contains + \ str(vol) + cubic centimeters print(out_text) This gives us most of what we want. When I executed this on my machine, I found: A sphere of radius 12.0 cm contains 7238.229473870882 cubic centimeters

engr 102 engineering lab i - computation 5 We have more decimal points in the volume term than we would like, and we will learn to deal with this later. 16 But, for now, this is better than multiple print() statements. 16 See the examples shown during the lab time this week. We can also use some of the methods available in string objects to help format our strings. Three such methods are ljust(n), rjust(n), and center(n). Each of these will left-justify, right-justify or center a string within a region that is n characters long. Remember, we access methods of objects using the.-operator, which is typed immediately following the name of the object on which we want the method to act: text = str( 2.34 ) text.rjust(8) The second line above will append 4 spaces on the left of the string stored in text. Hence, the value stored in text will now be 2.34 where I have used an underscore to show each of the four leading spaces that were inserted by.rjust(). We will practice more of this in the lecture and lab time this week. Input Instead of writing all of the input data directly in our programs, it would be nice if we could receive input from the user during program operation. One way to do this in Python is using the input() function. If we type input() by itself, the program will stop and wait for the user to type characters until the <enter> key is typed. The function will then return all of the characters typed by the user except for the <enter> key. Usually, we would use the input() function in an assignment operation: in_text = input() Notice that input() returns the string typed by the user, even if the user only typed numbers. If you want the input to be interpreted as a number, you must convert the string to a number: 17 r = float(input()) n = int(input()) 17 Try running these commands in Python If you execute this program, you will notice that no messages are written to the screen telling the user what to enter. You can write a message using either print() before the input() command or by sending the text as input to the input() function: print( Enter the radius in cm: ) r = float(input()) n = int(input( How many terms do you want to calculate? ))

6 engr 102-213 The only difference is that the input() function does not start a new line before the user types their data; whereas, a new line is created before the input command using print. The console output of this code might have looked like this: Enter the radius in cm: 3.54 How many terms do you want to calculate? 7 Process finished with exit code 0 Later, we will learn to get input from files. In the Lab this week, we will practice using Python types to write short programs, format strings, and to get data from the user during execution of these programs.