Chapter 2: Variables, Operations, and Strings CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Data types and variables
Introduction to Python
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Basic Elements of C++ Chapter 2.
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Programming.
Introduction to Python
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
Chapter 2: Using Data.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Variables and Expressions CMSC 201 Chang (rev )
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Bill Tucker Austin Community College COSC 1315
Chapter Topics The Basics of a C++ Program Data Types
Topics Designing a Program Input, Processing, and Output
Chapter 6 JavaScript: Introduction to Scripting
2.5 Another Java Application: Adding Integers
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Multiple variables can be created in one declaration
Variables, Expressions, and IO
Introduction to C++ Programming
A First Book of ANSI C Fourth Edition
Building Java Programs Chapter 2
elementary programming
Topics Designing a Program Input, Processing, and Output
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Topics Designing a Program Input, Processing, and Output
Primitive Types and Expressions
Building Java Programs Chapter 2
Data Types and Maths Programming Guides.
Introduction to Python
Presentation transcript:

Chapter 2: Variables, Operations, and Strings CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp

Agenda Our First Program Variables Expressions Assignment Datatypes Type Casting Operators Console I/O

Our First Program greeting = “Hello there” first_name = “Joel” middle_name = “Edward” last_name = “Kemp” print(greeting, first_name, middle_name, last_name) The output: Hello there Joel Edward Kemp What does this program do? But what are greeting, first_name, middle_name, and last_name ? Refer to: first.py

Variables Definition: name/identifier given to some unknown data value stored in a computer’s memory. Format Rules: – Start with any letter (or an underscore) but no numbers! e.g., g, guess, var, avg1, ycoord, point2, name – No spaces or other punctuation allowed! Use an underscore instead! e.g., first_name, celsius_temp, wind_speed – No reserved words! Reserved word: an identifier that is part of the Python language. – Identifiers should be descriptive.

Variables cont. What can you do with a variable? – Assign a value (write) x_coord = -3 price = 5.50 is_hungry = True name = “Joel Kemp” – Retrieve a value (read) tip = 0.15 * bill_amount last_name = first_name # It can happen! print(tip) What’s going on with this statement? tip = 0.15 * bill_amount Hmm, there are a few strange concepts that need clarification. Refer to: variables.py

Expressions What are they? – Statements that contain any number of variables, constants, and operators. Statement: a line of Python code delimited by a carriage return or semicolon. – Semicolon is used to put more than one statement on a line. – Used as a statement delimiter in other languages. Examples: tip_amount = 0.15 * bill_amount num_squared = x * x firstName = “Joel” print(firstName) tip_percent = 0.15

Assignment Statements The most common type of programming statement! How do we read/evaluate an assignment? tip_percent = 0.15# Initialization bill_amount = 100 tip = tip_percent * bill_amount – The right hand side is evaluated and the result is stored in the left hand side! – The = sign is known as the assignment operator. Note: variables on the RHS need to be initialized! Python also lets you do multiple initialization! x, y = 5, “Joel”#Equal to x = 5 y = “Joel”

Datatypes We can store different types of data in variables! – Integers: whole numbers like 0, -2, 100 – Floats: fractional numbers like , 0.5, 3.5, – Booleans: truth values True or False – Strings: groups of characters “Joel”, “Kemp”, “Joel Kemp” More advanced types: – Objects: custom datatypes composed of simpler types – Collections: allow a variable to hold more than one value at a time. – File Handles: allow variables to manipulate text files. Refer to: datatypes.py

Conversions What if I need to convert an integer to a float? – Also known as type casting from integers to floats. Python does some conversions automatically! tip = 0.15 * 100 – 0.15 is a float, but 100 is an integer – What’s the datatype of tip ? – Integers are automatically converted to floats! 100 becomes * yields is stored in the variable tip Thus, tip has the float datatype. This is an implicit conversion. Refer to: conversions.py

OPERATORS

Operators Arithmetic Combined

Arithmetic Operators Programming languages let you mix and match arithmetic operations! – Addition: + – Subtraction: - – Multiplication * – Division / and // – Remainder% – Exponentiation ** Precedence: from lowest to highest + - * / // % **

The odd one! Integer division vs. Float Division – Float Division ( / ) yields the sometimes fractional results that you’d expect: 1 / 2 = / 2 = 1.5 – Integer division drops the fractional part! 1 // 2 = 0 #0 instead of // 2 = 1 #1 instead of 1.5

Another Odd One! We can compute the remainder of a division using the modulus operator % 1 % 2 = 1 2 % 4 = 2 4 % 2 = 0 10 % 200 = 10 – When do we use it? Computing prime numbers Binary arithmetic Random number generation

Combined Operators We know how to do simple arithmetic operations. We can combine operations acting on a variable: – If we have these types of statements: x = x + 10 //Add 10 to x and store the result back in x y = y - 5 x = x / 2 y = y * 2 z = z + x + y – We can rewrite these statements using combined operators: x += 10 y -= 5 x /= 2 y *= 2 z += x + y

CONSOLE I/O Material found at the start of Chapter 3 in Visual Quickstart Guide

Console Input / Output The “console” is the IDLE shell – Could be your terminal or command prompt. We can print (output) to the shell using the print() function. We can read (input) data in from the shell using the input() function. What’s a function? – Function: a group of code with an identifier that performs a certain task.

print() What does it do? – print is a built-in Python function that prints information to the console. How do you use it? print( something ) – You pass in data (“arguments”) – Something could be: variable constant/literal expression function call Refer to: print.py

input() What does it do? – input is a built-in Python function that grabs entered text from the console. It captures input and returns it to your program. How do we use it? input( prompt ) – Prompt could be any message that you’d like to show to your users. What happens next? – The user enters some data and hits enter – The information is returned to your program as a string. – You store that string in a variable and do whatever is necessary! Example: name = input(“Please enter your name: “) So name now has a string containing what the user gave us.

Explicit Conversions What if I wanted to convert a string to a number? – Implicit conversions were nice, but a bit limited. When would you want to do that? – Well input() only gives us strings… – If the user supplied a number, input() would return it to the program as a string. – What if I wanted to use that input in a formula? No can do  Unless, we have some way of converting a string to a number! There are explicit conversions that can be used for certain type casts.

Explicit Conversions (cont.) Functions can be used to handle explicit conversions: – float() – int() – str() – bool() These functions take in a single argument of any type and return the proper representation of that input. Refer to: explicitConversions.py

STRINGS

Agenda Declaring Strings The len() function Concatenation

String What is it? – A group of one or more characters. How do we use them? – Three ways to create strings: Single, double, and triple quotes – Triple quotes are used for multi-line strings – Single quotes work well until you want to output single quotes  – Double quotes are the preferred method for creating strings. Note: Strings are immutable! – Immutable: not able to be changed. Refer to: stringCreation.py

len() The length function, len(), computes the length of a string. – You pass the string as an argument and len() returns an integer count of the characters. – You can use the returned value wherever an integer could be used. Example: name = input(“Please enter your name: ”) print(“Your name contains “, len(name), “ letters!”) # OR num_chars = len(name) print(“Your name contains “, num_chars, “ letters!”)

Concatenation You can use the addition operator on strings! Huh, how do you add words? We’re not adding words, we’re combining them! Example: name = “Joel” + “Kemp”#What does name contain? print(name) #Output is JoelKemp A variation: name = “Joel” name += “Kemp”# But strings are immutable – You might think we’re modifying the string “Joel” but we’re simply creating a new string “JoelKemp” and storing it in name. When would we use this? – Combining string inputs from the user. – Combining string portions into longer strings. Refer to: concatenation.py

Exercises 1.Calculate the area and perimeter of a rectangular room, 12.5 meters by 16.7 meters. 2.Write a program to convert temperatures from Fahrenheit to Celsius. The formula for that is: C = 5 / 9 * (F - 32) – Accept the Fahrenheit temperature from the user. – Print out the converted temperature! 3.Write a program that figures out how long it will take to get somewhere in a car! – The formula (in words) is “travel time equals distance divided by speed.” – Make a program to calculate the time it will take to drive a distance (specified by the user) at a speed (also specified by the user) and display the answer.