Expressions and Variables

Similar documents
Topic 2: Introduction to Programming

ENGR 102 Engineering Lab I - Computation

CHAPTER 3: CORE PROGRAMMING ELEMENTS

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

Lecture 3. Input, Output and Data Types

ENGR 101 Engineering Design Workshop

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

1/11/2010 Topic 2: Introduction to Programming 1 1

Chapter 2 Getting Started with Python

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

Our Strategy for Learning Fortran 90

Variables and Constants

Python Programming Exercises 1

Simple Functions. Definition: def function_name():... code goes here... Calling: function_name()

Python Input, output and variables

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

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

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Elementary Programming

A First Program - Greeting.cpp

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Introduction to programming with Python

CSEN 102 Introduction to Computer Science

CS102: Variables and Expressions

Hello, World and Variables

BASIC ELEMENTS OF A COMPUTER PROGRAM

CSCE 120: Learning To Code

Algorithms and Programming I. Lecture#12 Spring 2015

Python Unit

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

2 nd Week Lecture Notes

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CITS2401 Computer Analysis & Visualisation

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

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

Introduction to Python (All the Basic Stuff)

Programming with Python

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

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MIT AITI Python Software Development

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

VBScript: Math Functions

CCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the

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

Introduction to Python

Introduction to the C++ Programming Language

Introduction to TURING

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

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

Text Input and Conditionals

My First Python Program

Introduction to Java Applications

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Building Java Programs

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

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

Introduction to Programming in Turing. Input, Output, and Variables

At full speed with Python

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

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER. Chapter 2

CS 102 Lab 3 Fall 2012

An Introduction to Python for KS4!

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

Expressions, Statements, Variables, Assignments, Types

Fundamentals: Expressions and Assignment

Built-in Types of Data

Decimals. Chapter Five

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

Getting started with Java

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

Variables and Literals

Datatypes, Variables, and Operations

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

Outline. Data and Operations. Data Types. Integral Types

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

PYTHON. Values and Variables

CS 106 Introduction to Computer Science I

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Module 01: Introduction to Programming in Python

3. Java - Language Constructs I

Computing with Numbers Zelle - Chapter 3

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

Data types Expressions Variables Assignment. COMP1400 Week 2

Chapter 2: Data and Expressions

Objectives. In this chapter, you will:

Topic 4 Expressions and variables

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

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

3. Types of Algorithmic and Program Instructions

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

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

Reserved Words and Identifiers

Ch.2: Loops and lists

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Building Java Programs

Transcription:

Expressions and Variables

Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5

Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0, 3.14159 Strings Hello World!, Learn to Code, 100 Booleans True / False

Numeric Expressions We shall treat integers and floating points interchangeably for now. Remember, we can output expressions using print. Numbers on their own are expressions: print(42) We can do calculations: print(2+2)

Mathematical Operations + 2 + 2 = 4-4 - 2 = 2 * 6 * 7 = 42 / 42 / 7 = 6.0 ( Note the floating point answer) ** 2 ** 4 = 16 % 18 % 5 = 3 (Modulo - gives remainder) () (2 + 3) * 5 = 25

Operation Precedence 2 * 4 + 3 * 3 = 8 + 9 = 17 2 * (4 + 3) * 3 = 2 * 7 * 3 = 42

Exercise: Calculations Write a program that calculates and outputs the following: Hint: Square root is the same as raising to the power of 0.5.

Exercise: Calculations Write a program that calculates and outputs the following: Hint: Square root is the same as raising to the power of 0.5. (-6 + (6*6-4*3*-15) ** 0.5) / (2*3) (-6 + (6**2-4*3*-15) ** 0.5) / (2*3) 1.449489742783178

String Expressions Text is represented using strings. (a string of characters ) Hello World! Learn to Code Hello World Learn to Code Watch out if copying from word-processor to text editor...

Simple String Operations Concatenation is attaching strings together: Hello + + World! = Hello World! We can make strings repeat: badger * 3 = badgerbadgerbadger Note that we can t use every operation! Subtracting / dividing strings doesn t really make sense!

String Formatting Remember that Strings and Numbers (Integers / Floats) are different data types! The following will not work, because we cannot mix data types. + has different meanings for Strings and Numbers. I am + (10 + 3) + years old. Expressions inside quotes will not be evaluated - they will be treated as strings. So this does not give the desired result: I am + (10 + 3) + years old. The solution is string formatting.

String Formatting I am %d years old. % (10 + 3) %d is a format specifier - in this case, it represents an integer. When the string expression is evaluated, format specifiers are replaced with the values listed after the %. In the above example: - 10 + 3 is evaluated to 13. - Since %d represents integer formatting, the integer 13 is converted to the string 13. - %d is replaced with 13 in the string.

Format Specifiers A few common format specifiers: %d, %i Integers %f Floating points %e Floating points in scientific notation %s Strings Multiple values should be given as a comma-separated list in brackets: My name is %s, I am %d years old, and I have %d %s. % ( Alex, 13, 7, friends )

Exercise: String Formatting My name is %s, I am %d years old, and I have %d %s. % ( Alex, 13, 7, friends ) Adjust the above expression to be about yourself by changing the parameters. Adjust the expression so that years is a parameter, rather than part of the string. Then, adjust the parameters to display the same unit of time in months rather than years.

Exercise: String Formatting My name is %s, I am %d years old, and I have %d %s. % ( Alex, 13, 7, friends ) Adjust the above expression to be about yourself by changing the parameters. Adjust the expression so that years is a parameter, rather than part of the string. Then, adjust the parameters to display the same unit of time in months rather than years. My name is %s, I am %d %s old, and I have %d %s. % ( Alex, 13*12, months, 7, friends )

But why do we need expressions? So far, we have been hard-coding these expressions. We could have calculated the results ahead of time! So why do expressions exist? Variables! We want to be able to store the results of our calculations somewhere for later use. We want to be able to remember information a user has given us. We might want to use these values in later calculations.

Variables A variable is a piece of memory that we can give a label and set aside for storing a value. We can define as many as there is space for! variablename = expression x = 10 * 8 + 5 age = 32 firstname = Alice Valid variables names can contain letters, numbers, and underscores, but cannot start with a number.

Using Variables We must define variables before we use them. print(x) x = 10 # Error! We can change the values of variables after we have defined them using the same syntax. x = 10 print(x) # Outputs 10 x = 4 print(x) # Outputs 4

Using Variables It is possible to reassign a variable with a new data-type, but this is usually bad practice. x = 10 # x is an Integer print(x) # Outputs 10 x = Ten # Reassign x to be a String print(x) # Outputs Ten In some other languages, this is impossible.

Exercise: Variables My name is %s, I am %d years old, and I have %d %s. % ( Alex, 13, 7, friends ) Create appropriately-named variables for each of the four parameters, and print the string using those variables rather than hard-coded parameters. Now add a second print statement that outputs the same information in a different order. e.g. I am a 13 year old with 7 friends, called Alex. Try changing the values in the variables and re-running the program - observe how the output changes.

User Input Inputs need to be stored in variables so they can be accessed later. We do this using input, which acts as follows: - A message is shown to the user, asking for input. - The program waits for the user to enter some input and press enter. - The value that was input is returned. We can treat this as an expression, and therefore assign it to a variable. animal = input( Please enter your favourite animal: )

Exercise: User Input Write a program that asks the user for their name, then outputs a greeting using it.

Exercise: User Input Write a program that asks the user for their name, then outputs a greeting using it. name = input( What is your name? ) print( Hello, %s. % name) name = input( What is your name? ) print( Hello, + name +. ) print( Hello, %s. % input( What is your name? )) Which of these is better?

Exercise: Calculations with User Input Write a program that asks for two numbers, then prints their sum. What could go wrong here?

Exercise: Calculations with User Input Write a program that asks for two numbers, then prints their sum. What could go wrong here? a = input( Enter a number: ) b = input( And another: ) print(a + b) a and b are strings, so they are concatenated! Inputting 2 and 3 will output 23.

Converting Data Types We can convert from one data type to another using the following functions: int() float() str() These will give an error if there is no sensible conversion! int( hello ) # Error!

Exercise: Calculations with User Input Write a program that asks for two numbers, then prints their sum, taking account of type conversion. Broken version: a = input( Enter a number: ) b = input( And another: ) print(a + b)

Exercise: Calculations with User Input # Method 1 a = int(input( Enter a number: )) b = int(input( And another: )) print(a + b) # Method 2 a = input( Enter a number: ) b = input( And another: ) print(int(a) + int(b))

Exercise: Circle Equations Write a program that takes as input the radius of a circle, and outputs both the circumference and the area of that circle. Bonus points for outputting a formated string rather than a list of numbers! Maths! π = 3.14159 circumference = 2πr area = πr 2

Exercise: Circle Equations r = float(input( Radius: )) pi = 3.14159 circ = 2 * pi * r area = pi * r * r print( Circumference: %f % circ) print( Area: %f % area)

Summary Output to terminal Expressions - calculations and string building Variables - and their use in expressions User input from terminal How do we make decisions based on those variables?