Lecture 3. Input, Output and Data Types

Similar documents
ENGR 102 Engineering Lab I - Computation

ENGR 101 Engineering Design Workshop

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

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

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

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

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

Visual C# Instructor s Manual Table of Contents

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

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

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

Full file at

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

Chapter 17. Fundamental Concepts Expressed in JavaScript

Expressions and Variables

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

Lecture 1. Types, Expressions, & Variables

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

Python Input, output and variables

Chapter 2 Getting Started with Python

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

PYTHON. Values and Variables

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

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

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

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

These are notes for the third lecture; if statements and loops.

Basic data types. Building blocks of computation

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

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

Programming for Engineers Introduction to C

Getting Started Values, Expressions, and Statements CS GMU

Variables, expressions and statements

Fundamental of Programming (C)

Fundamentals: Expressions and Assignment

Reserved Words and Identifiers

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

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

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

Chapter 2 Working with Data Types and Operators

Python 2 Conditionals and loops Matthew Egbert CS111

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

The C++ Language. Arizona State University 1

Introduction to Python

Programming with Python

2 nd Week Lecture Notes

Text Input and Conditionals

CMSC 201 Computer Science I for Majors

Real Python: Python 3 Cheat Sheet

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

CSCI 121: Anatomy of a Python Script

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Full file at

Python Day 3 11/28/16

CS 106 Introduction to Computer Science I

Python for Non-programmers

What did we talk about last time? Examples switch statements

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

(I m not printing out these notes! Take your own.)

T H E I N T E R A C T I V E S H E L L

CS 141, Lecture 3. Please login to the Math/Programming profile, and look for IDLE (3.4 or the unnumbered. <-- fine <-- fine <-- broken

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

CS102: Variables and Expressions

Python Class-Lesson1 Instructor: Yao

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

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

CSCA20 Worksheet Strings

EXPRESSIONS AND ASSIGNMENT CITS1001

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Chapter 2: Using Data

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

AP Computer Science A

Programming Lecture 3

CPS122 Lecture: From Python to Java

Fundamentals of Programming CS-110. Lecture 2

ENGR (Socolofsky) Week 02 Python scripts

Maciej Sobieraj. Lecture 1

Control Structures 1 / 17

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Lecture Set 2: Starting Java

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Lecture Set 2: Starting Java

Expressions and Casting

Transcription:

Lecture 3 Input, Output and Data Types

Goals for today Variable Types Integers, Floating-Point, Strings, Booleans Conversion between types Operations on types Input/Output Some ways of getting input, and formatting output

Variable Types Computer memory consists of a bunch of 1s and 0s Remember that a variable describes some area of memory That memory contains only 1s and 0s. How do we know how to interpret a set of 1s and 0s? 11010011100011101001111010011001

Variable Types Computer memory consists of a bunch of 1s and 0s Remember that a variable describes some area of memory That memory contains only 1s and 0s. How do we know how to interpret a set of 1s and 0s? 11010011100011101001111010011001 The variable type says how we should interpret that data

Types of Variables There are some standard types that are built in to the language or commonly used. Some of these include: Integers Floating-Point Numbers Booleans Strings We ll encounter other types later There are also ways to create our own types, but we won t be discussing these.

Integers Integers are just that integers Can be positive or negative Examples: 1 2 100 0-20 Probably the most commonly used variable type

Floating-Point Numbers Can represent numbers with a decimal point Examples: 1.01 2.0 100.0-20.05 0.004 May be best to think of these as in Scientific Notation A Mantissa (the values, assumed to have 1 digit before the decimal point) An Exponent (the power of 10 that the Mantissa is multiplied by) 1234.567 = 1.234567 * 10 3

Booleans Booleans will have the value True or False That s it! We ll see a lot more use of Booleans next week

String A string is a way of describing text Strings are made up of characters strung together. When we want to define a string, we usually must specify it within quotation marks, otherwise it might look like a variable name(s). You can use either single quotes or double quotes "This is a string" 'So is this'

Side note: Strings If we specify a string with single or double quotes, how do we include a quotation mark in the string itself? If we want an apostrophe, use double quotes for the string: "It's" If we want quotation marks, use single quotes for the string 'He said, "What?" to her' But what if we want both?

What if we want both and in a string? Two choices 1. Use triple quotes to begin/end string (single or double): '''He said "I'm tired." ''' """He said "I'm tired." """ 2. Use the backslash (\) as an escape character Put the \ before the character you want to specify 'He said "I\'m tired." ' "He said \"I'm tired.\" "

Knowing a Variable Type In Python, the type of a variable is implied based on how it was created or last assigned. In many other languages, we must explicitly define what the type of a variable will be. In this case, variable a will be an integer: a = 5 In this case, variable a will be a floating-point number: a = 5.0 In this case, variable a will be a Boolean: a = True In this case, variable a will be a string: a = Five It is important to know the type of a variable, or you can get strange effects!

What type is it? For the following, what is the type of the variable x? x = 2 x = 2.0 x = "True" x = 2 + 3 x = 2.0 + 3.0 x = 2 / 3 x = 2 / 2 x = 2 // 2 Integer Floating-Point String (x=true would be Boolean) Integer Floating-Point Floating-Point Floating-Point (dividing integers yields floating-point) Integer (this is integer division no remainder)

A reminder of output Basic output is to the console a window or the screen that shows the output of the program. To show the value of a variable, we print it Command is: print(x) where x is the thing you want to be printed. The x can be: a constant value (called a literal ), a variable, or an expression

Type and behavior Operations on variables/values can vary depending on the type of the operands. Let s look at the basic addition operator: + What is output by the following? x=1+2 print(x)

Type and behavior Operations on variables/values can vary depending on the type of the operands. Let s look at the basic addition operator: + What is output by the following? Output: x=1+2 print(x) 3

Type and behavior Operations on variables/values can vary depending on the type of the operands. Let s look at the basic addition operator: + What is output by the following? x=1.0+2.0 print(x)

Type and behavior Operations on variables/values can vary depending on the type of the operands. Let s look at the basic addition operator: + What is output by the following? Output: x=1.0+2.0 print(x) 3.0 Printing a floating-point value will include the decimal point

Type and behavior Operations on variables/values can vary depending on the type of the operands. Let s look at the basic addition operator: + What is output by the following? x="1"+"2" print(x)

Type and behavior Operations on variables/values can vary depending on the type of the operands. Let s look at the basic addition operator: + What is output by the following? Output: x="1"+"2" print(x) 12

Why did that happen? For numerical types, the + operator means addition For strings, the + operator means concatenation Remember, 1 is a string (the text representation), not the integer 1 So, 1 + 2 is the string 1 joined to the string 2, giving the result, a string 12. Notice that when the string is printed, the quotation marks don t appear.

Other operations Strings have + defined (concatenation) Needs to be between two strings string + string gives a new string string + int gives an error, though How is the operation - defined for strings? It s not! Trying to subtract two strings will give an error Not every operation is defined for every type (in fact, most won t be) For strings, - and / are not defined at all, + is defined between two strings, and * is defined for a string and an int What do you think 3*"Howdy" will be?

Other operations Strings have + defined (concatenation) Needs to be between two strings string + string gives a new string string + int gives an error, though How is the operation - defined for strings? It s not! Trying to subtract two strings will give an error Not every operation is defined for every type (in fact, most won t be) For strings, - and / are not defined at all, + is defined between two strings, and * is defined for a string and an int What do you think 3*"Howdy" will be? "HowdyHowdyHowdy"

Converting between types It is possible to convert values of one type into a value of another type. Not for every type combination, though General format: new_type(value) value is a variable, expression, or literal of some type new_type is the type to convert into Example: converting int to a float: float(3) - this becomes the value 3.0 x = 2 - x has the integer value 2 y = float(x) - y has the float value 2.0, x still has the int value 2

Converting floats to ints When converting a floating-point number to an integer, the value is truncated Any fractional portion is dropped off, only the whole portion remains int(2.0) - has the value 2 int(3.14) - has the value 3 int(4.9) - has the value 4 int(0.01) - has the value 0 int(-1.3) - has the value -1 int(-1234.56) - has the value -1234

Converting from strings to ints/floats Strings, if they clearly define an int/float, can be converted to one of those. int('3') - this has the integer value 3 float('3.14') - this has the floating-point value 3.14 float('2') - this has the floating-point value 2.0 int('2.5') - this is an error (notice, it does NOT convert to a float, then to an int)

Converting from a number to a string The conversion is done with the command str Does a direct conversion into a string. Floating-point values always have at least one digit before and after the decimal point. str(1) - has the value '1' str(2.5) - has the value '2.5' str(1/2) - has the value '0.5' str(10*1.0) - has the value '10.0' Note: There is also a repr alternative to str For most types, repr and str work the same, but repr lets you convert a string to a string that is printed as shown (with quotation marks, new lines, etc.)

Boolean conversions Remember, Booleans have the value True or False When converting FROM a Boolean value True is assumed to have the value 1 False is assumed to have the value 0 When converting TO a Boolean value The numeric value 0 has the value False Anything else has the value True

Boolean conversion int(true) - has the value 1 float(true) - has the value 1.0 float(false) - has the value 0.0 bool(0) - has the value False bool(3) - has the value True bool('0') - has the value True (is not numeric 0) bool('0.0') - has the value True (is not numeric 0) bool('false') - has the value True (is not numeric 0)

Type conversion example What do you think the value of this expression is? str(float(str(3/2)+str(int(3/2))))*int(int(str(2)+str(7))/int(10.3))

Type conversion example What do you think the value of this expression is? str(float(str(3/2)+str(int(3/2))))*int(int(str(2)+str(7))/int(10.3)) str(float(str(1.5)+str(int(1.5))))*int(int('2'+'7')/int(10.3)) str(float(str(1.5)+str(1)))*int(int('27')/10) str(float('1.5'+'1'))*int(27/10) str(float('1.51'))*int(2.7) str(1.51)*2 '1.51'*2 '1.511.51'

Basics of Output with print() As we saw earlier, the basic command for output is the print command. The print command formats the output in a readable way By default, it also ends the line it prints on, so the next thing printed will be on the next line More than one value can be specified in the parentheses, separated by commas Each thing is printed, separated by a space print(2.0,'is',2) outputs: 2.0 is 2

Printing strings Often, to get the format we want, it s easiest to create a string ourselves, and print the string. e.g. if we don t want spaces separating elements. For example, say we had values stored in variables x and y, and we wanted to print out: <xvalue>:<yvalue> (the values, separated by a colon) x=3 OUTPUT y=4 print(x, :,y) 3 : 4 print(str(x) + : + str(y)) 3:4 Notice lack of spaces in second option

Formatting Strings There are a lot of options for formatting strings in different ways Often helps to line up data or get exact formatting We ll see some of these in labs throughout the course For example, we can pad a string with extra spaces to the left and/or right, using the.ljust(),.rjust(), and.center() commands immediately after a string "2.3".ljust(10) - has value: '2.3 ' "2.3".rjust(10) - has value: ' 2.3' "2.3".center(10) - has value: ' 2.3 '

Modifying the print() command By default, the print command, when printing Separates all the items (listed separated by commas) with a space Ends the line after printing (so next thing appears on next line) We can actually change how the print command handles both of those things! To change how items are separated, write: print(, sep="<something>") To change what is done after printing, write: print(, end="<something>") Note that <something> could be an empty string, if you want nothing printed between items or at the end of a print statement

Example: changing print() What would this output? print("test",3,5) print("test",3,5,sep=',') print("test",3,5,sep=',',end=':') print(15)

Example: changing print() What would this output? print("test",3,5) print("test",3,5,sep=',') print("test",3,5,sep=',',end=':') print(15) Console Test 3 5 The normal print output

Example: changing print() What would this output? print("test",3,5) print("test",3,5,sep=',') print("test",3,5,sep=',',end=':') print(15) Console Test 3 5 Test,3,5 The space separators were replaced by commas

Example: changing print() What would this output? print("test",3,5) print("test",3,5,sep=',') print("test",3,5,sep=',',end=':') print(15) Console Test 3 5 Test,3,5 Test,3,5: The space separators were replaced by commas, and the end-of-line by a colon

Example: changing print() What would this output? print("test",3,5) print("test",3,5,sep=',') print("test",3,5,sep=',',end=':') print(15) Console Test 3 5 Test,3,5 Test,3,5:15 There was no end-of-line, so the next print statement came immediately after the previous one.

Formatting numbers Often, we want to output numbers with varying degrees of precision This turns out to be a bit more complicated we will come back to this after seeing some more material

Getting input We ve seen lots of examples of output the print statement but what about input? We will assume here that our input is coming from a person typing on the keyboard into the main window. This is as opposed to input from a file, or a device, etc. This input source is referred to in different ways: standard input or input from the console are two of the more common ones.

The input() command We have a command, input(), available to get input We have to assign input() to a variable. e.g. thing_i_typed = input() Important: All input comes in as a string. That is, all input from the input() command comes in as a string. If we want to input a number, we have to convert the string to a number. e.g. age = int(input()) will read in what is typed, convert it to an integer, and save it in the variable age. Input is read until the end of the line is entered

Example: a program to compute area of a circle from math import * r = float(input()) print(pi*r**2) When run, the user will type a number, and the program will output the area of a circle with that radius. Try it out! Note: we have to have the from math import * line to have pi defined.

Example: a program to compute area of a circle from math import * r = float(input()) print(pi*r**2) Console 1 3.141592653589793 The user typed this in

What if we want to output something more descriptive? How would you change the program, so that it printed a description of the answer? from math import * r = float(input()) print(pi*r**2)

What if we want to output something more descriptive? How would you change the program, so that it printed a description of the answer? from math import * r = float(input()) print("the area of the circle is "+str(pi*r**2)) Console The user typed this in 1 The area of the circle is 3.141592653589793

What if we want to ask the user for input? How would you change the program, so that it asks the user to input a radius? from math import * r = float(input()) print("the area of the circle is "+str(pi*r**2))

What if we want to ask the user for input? How would you change the program, so that it asks the user to input a radius? from math import * print("enter the radius of a circle:") r = float(input()) print("the area of the circle is "+str(pi*r**2)) Console Enter the radius of a circle: The user typed this in 1 The area of the circle is 3.141592653589793

Input with a prompt The input() command can also print out the text to prompt the user itself. Writing input(x), where x is a literal, variable, or expression, will print out x before getting the user s input. Note: there is NOT a new line printed after that prompt is printed Example: user_name = input("enter your name: ") Console Enter your name: The user will type here

What if we want to ask the user for input? Another alternative, then, would have been: from math import * r = float(input ("Enter the radius of a circle: ")) print("the area of the circle is "+str(pi*r**2)) Console Enter the radius of a circle: 1 The area of the circle is 3.141592653589793 The user typed the 1 in