Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CMT Programming Software Applications
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
 2002 Prentice Hall. All rights reserved. 1 Intro: Java/Python Differences JavaPython Compiled: javac MyClass.java java MyClass Interpreted: python MyProgram.py.
Data types and variables
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
Chapter 2: Introduction to C++.
JavaScript, Third Edition
Introduction to C Programming
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
COMPSCI 101 Principles of Programming
Computer Science 101 Introduction to Programming.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Objectives You should be able to describe: Data Types
A First Book of ANSI C Fourth Edition
Introduction to Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introduction to Computational Linguistics Programming I.
Computer Science 101 Introduction to Programming.
The Java Programming Language
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Variables and Expressions CMSC 201 Chang (rev )
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Course Title: Object Oriented Programming with C++ instructor ADEEL ANJUM Chapter No: 03 Conditional statement 1 BY ADEEL ANJUM (MSc-cs, CCNA,WEB DEVELOPER)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
CSC 107 – Programming For Science. The Week’s Goal.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 2 Variables.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
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.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Data And Variables Chapter Names vs. Values Michael Jordan name (the letter sequence used to refer to something) value (the thing itself)
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.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
Variables and Strings. Variables  When we are writing programs, we will frequently have to remember a value for later use  We will want to give this.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
ITM © Port, KazmanVariables - 1 ITM 352 Data types, Variables Class #4.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter Topics The Basics of a C++ Program Data Types
Topics Designing a Program Input, Processing, and Output
Chapter 6 JavaScript: Introduction to Scripting
Basic Elements of C++.
Revision Lecture
Variables, Expressions, and IO
Basic Elements of C++ Chapter 2.
IDENTIFIERS CSC 111.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2: Introduction to C++.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Primitive Types and Expressions
Unit 3: Variables in Java
Presentation transcript:

Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming

Class Rep  If you would like to apply for this position, please me with your name and a short paragraph to describe yourself.  Please send your to me before 10pm today. CompSci 1012

Change of assignment due dates  Assignment 2 now due on Thursday April 2  Assignment 3 now due on Friday April 30 CompSci 1013

Review  To pass this course, you need to pass both the ___________component and the ________ component.  __________ component:  Labs ______%  Assignments _________%  Code Runner Exercises ______%  __________ component:  Term Test ______%  Exam _________%  Where can you check your lab marks each week? CompSci 1014

Learning outcomes  At the end of this lecture, students should be able to:  perform calculations using standard arithmetic operators  use variables to store values  describe differences between int and float types  print numbers and strings to standard output CompSci 1015

Installing Python 3  Go to the resources page of the CompSci 101 website.  You will see the link to python.org where you will be able to download the python installer. Make sure you install Python 3. CompSci 1016

Notepad++ - an editor to use  Go to the resources page of the CompSci 101 website.  You will see the link to a document which tells you about downloading and setting up Notepad++. CompSci 1017

Setting Up Notepad++  We would like to add a command to run Python programs  Choose Macro -> Run Python  Common Problem:  Error message when running a program  Check your command: (Plugins -> NppExec -> Execute… ) CompSci 1018 Before After cd "$(CURRENT_DIRECTORY)" C:\Python33\Python "$(FILE_NAME)" cd "$(CURRENT_DIRECTORY)" C:\Python33\Python "$(FILE_NAME)" a space in between

Setting Up Notepad++  Common problem:  Could not run your program using ctrl-1 shortcut key  Choose Settings -> Shortcut Mapper...  Ctrl-1 has been assigned to another command. CompSci 1019 Modify to something else

Sequence of Instructions  A program is a sequence of instructions to perform a specific task  Instructions are specified in a sequence  Computers execute the instructions one after the other  Instructions are specified using a formal language  Natural languages are the languages spoken by people  Formal languages are designed by people for a specific purpose, e.g., mathmatical notation, chemical structure of molecules, programming languages  We shall be writing our programs in the Python 3 programming language CompSci 10110

The Python interpreter  Source code (programs) is written in a programming language such as Python.  The Python interpreter translates and executes source code  One instruction at a time is converted into machine code and executed by the interpreter INTERPR ETER CompSci 10111

Programs are deterministic  Programs are deterministic  the result of the program instructions is well defined  Rules govern the results of instructions. Once we learn the rules, we can govern what the computer does,  then the output is completely predictable CompSci 10112

Storing information - variables  Variables are names for storage locations  Almost any name will work – but there are some constraints  A variable stores only one value at a time  Assign a value to a variable location using = (the assignment operator)  Refer to the value in a location using the variable name.  Examples: name = "Adriana" height = age = 21 number = 123 name = "Adriana" height = age = 21 number = 123 A variable has a name, stores a value. CompSci 10113

Variable names  The following are valid variable names:  The following are invalid variable names:  What are the rules for naming variables?  _________, __________ and __________  Must start with a _________ or an _____________  Cannot be a __________  Can be any ____________ x age age_of_child box1 box_2 _age age_ x age age_of_child box1 box_2 _age age_ 3 age of child age-child 1st 2_box 3 age of child age-child 1st 2_box CompSci 10114

Variable names conventions  Always choose variables with meaningful names:  The convention when using multiple words, is to join words with an underscore:  The convention is to use lower case letters for variable names.  Python is case sensitive. For example, the variable, "name" is not the same as the variable, "Name". name age course name age course user_input age_allowed age_of_child circle_area user_input age_allowed age_of_child circle_area CompSci 10115

Style guide CompSci 10116

Variable names should not be keywords  Variable names should not be keywords (also called reserved words):  Look on page 11 of the reference book, Think Python – How to think like a computer scientist. andelifimportraise aselseinreturn assertexceptistry breakfinallylambdawhile classfornonlocalwith continuefromnotyield defglobalor delifpass andelifimportraise aselseinreturn assertexceptistry breakfinallylambdawhile classfornonlocalwith continuefromnotyield defglobalor delifpass CompSci 10117

What kind of information can our programs store?  Information in a program is categorised into different types.  integer  floating point  string  boolean, and many more  Integer values are numbers with no decimal point. They can be positive, 0 or negative:  Floating point numbers are numbers with decimal points. They can be positive, 0 or negative: Note that the precision of floating point numbers is limited. CompSci True False "Angela"

result1 = 54 my_age = 21 bank_balance = 2019 result1 = 54 my_age = 21 bank_balance = 2019 Assigning to a variable  The assignment = operator is used to assign a value to a variable, i.e., to store some information in the program memory:  The left hand side of the assignment operator is always a variable. CompSci DEMO

Doing Calculations  The following mathematical operators can be used with integers and with floating point numbers:  Addition +  Subtraction -  Multiplication *  Division /  Exponentiation ** result1 = result2 = 15 * 3 bank_balance = 2019 solution = 4 ** 3 result1 = result2 = 15 * 3 bank_balance = 2019 solution = 4 ** 3 CompSci = 64

Expressions  An expression always evaluates to a single value, e.g.,   6 *  52 – 3 * 2.3  4.6  The right hand side of an assignment statement is always an expression.  Firstly the expression on the right hand side of the assignment operator is evaluated, and, lastly, the resulting value is assigned to the variable on the left hand side of the assignment operator. result1 = result2 = 15 * 3 bank_balance = 2019 solution = 4 ** 3 age = result1 = result2 = 15 * 3 bank_balance = 2019 solution = 4 ** 3 age = CompSci 10121

Expressions  An expression can be used anywhere a single value can be used. A variable can be used anywhere a single value can be used. result1 = result2 = result1 * 10 bank_balance = result2 age = 5 age = age + 4 age = age * 3 result1 = result2 = result1 * 10 bank_balance = result2 age = 5 age = age + 4 age = age * 3 CompSci DEMO result1 result2 bank_balance age

Printing to the standard output  The print() function is used to print values to the standard output.  Examples:  Notice that round brackets (parentheses) are used with functions. After printing whatever is to be printed (whatever is inside the round brackets) a new line is printed. principal = 100 years = 15 print(43) print(principal) print(2 * years + 1) principal = 100 years = 15 print(43) print(principal) print(2 * years + 1) CompSci print(45.67) print(100000) print(44) print(45.67) print(100000) print(44) DEMO Example01.py

Printing a blank line  The print() statement with no arguments simply prints a blank line. principal = 100 years = 15 print(43) print() print(principal) print() print(2 * years + 1) principal = 100 years = 15 print(43) print() print(principal) print() print(2 * years + 1) CompSci DEMO Example02.py

Exercise 1  The formula for working out the final amount when a sum is invested at compound interest is: M = P( 1 + i ) n where:  M is the final amount including the principal.  P is the principal amount.  i is the rate of interest (a whole number indicating the % interest) per year.  n is the number of years invested..  Complete the code which calculates the final amount when $100 is invested for 15 years at 10% interest.  The output prints the principal on one line followed by the final amount on the next line: principal = 100 years = 15 rate = principal = 100 years = 15 rate = CompSci 10125

Algorithm Get the principal amountGet the rate of interest / 100Get the number of yearsSet the formulaPrint the result CompSci principal = 100 years = 15 rate = 10 final_amount = principal = 100 years = 15 rate = 10 final_amount = M = P( 1 + i ) n

Strings – Another Python Built-in Type  A string consists of a collection of characters delimited by single quotes (' … ') or by double quotes (" … "), e.g.,  Examples:  The program from the previous slide could be written with more information in the output:... final_amount = principal * (1 + rate /100) ** years print("Initial amount") print(principal) print("Final amount") print(final_amount)... final_amount = principal * (1 + rate /100) ** years print("Initial amount") print(principal) print("Final amount") print(final_amount) Initial amount 100 Final amount CompSci "Meravigioso" 'The final result is:' "5 + 2 * 5" "" "Meravigioso" 'The final result is:' "5 + 2 * 5" "" DEMO Example03.py name = "Angela"

Exercise  What will be displayed by the following code? CompSci age = 21 name = "Angela" print(age) print("age") print(name) print("name") age = 21 name = "Angela" print(age) print("age") print(name) print("name")

Printing more than one value on a single line  The print() statement can be used to print more than one variable (or value) on a single line. Each value to be printed is separated by a comma.  The default separator between the items to be printed is a single blank space.  Examples:... final_amount = principal * (1 + rate /100) ** years print("Initial amount", principal) print("Final amount", final_amount)... final_amount = principal * (1 + rate /100) ** years print("Initial amount", principal) print("Final amount", final_amount) Initial amount 100 Final amount CompSci DEMO Example03.py

Printing more than one value on a single line  Note: we can change this by including an optional last argument to the print() statement,  sep = "…"  Examples:... final_amount = principal * (1 + rate / 100) ** years print("Initial amount $", principal, sep = "") print("Final amount $", final_amount, sep = "")... final_amount = principal * (1 + rate / 100) ** years print("Initial amount $", principal, sep = "") print("Final amount $", final_amount, sep = "") Initial amount $100 Final amount $ *Meravigioso*Fabulous The final results are:56and44 print(1, "Meravigioso", "Fabulous", sep = "*") print('The final results are:', 56, "and", 44, sep = "") print(1, "Meravigioso", "Fabulous", sep = "*") print('The final results are:', 56, "and", 44, sep = "") CompSci DEMO Example03.py Default separator = a space

Printing more than one value on a single line  Note: you can also use another optional last argument to the print() statement:  end = "…"  Examples: CompSci *Meravigioso*Fabulous print(1, end="*") print("Meravigioso", end="*") print("Fabulous", end="*") print(1, end="*") print("Meravigioso", end="*") print("Fabulous", end="*") DEMO Default line terminator = a newline

Exercise 2  $1 NZ = $0.95 AUS. Write a program which converts $500 New Zealand to Australian dollars and converts $500 AUS to NZ dollars using the above exchange rate. The output of the program should be: nz_to_aus_rate = 0.95 nz_dollars = nz_to_aus_rate = 0.95 nz_dollars = NZ $500 = AUS $475.0 AUS $500 = NZ $ CompSci 10132

Algorithm (1: NZ to AUS) CompSci Get nz to aus rate: 0.95Get the amount (NZ Dollars)Calculate the AUS dollarsPrint the result nz_to_aus_rate = 0.95 nz_dollars = 500 nz_to_aus_dollars = nz_to_aus_rate = 0.95 nz_dollars = 500 nz_to_aus_dollars = NZ $500 = AUS $475.0

Algorithm (2: AUS to NZ) CompSci Get aus to nz rate: 1/0.95Get the amount (AUS Dollars)Calculate the NZ dollarsPrint the result aus_to_nz_rate = 1 / nz_to_aus_rate aus_dollars = 500 aus_to_nz_dollars = aus_to_nz_rate = 1 / nz_to_aus_rate aus_dollars = 500 aus_to_nz_dollars = AUS $500 = NZ $

Summary  In a Python program we can:  use variables to store values, using valid variable names  perform calculations using standard arithmetic operators  describe differences between int and float types  print numbers and strings to standard output CompSci 10135