CSE 142 Python Slides - GitHub Pages

CSE 142 Python Slides - GitHub Pages

Unit 1: Primitive Types Variables and Datatypes Adapted from: 1) Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp 2) Runestone CSAwesome Curriculum https://longbaonguyen.github.io Data Types A type is a set of values (e.g. integers, floats, etc..) and a set of operations (e.g. +, -, *, /, etc..) on them. Data types can be categorized as either primitive or reference. The primitive data types used in this course define the set of operations for numbers and Boolean(true or false) values. Reference variables or object variables hold a

reference(or address) to an object of a class(more on this later). 2 Primitive types The primitive types on the Advanced Placement Computer Science A exam are: int - which store integers (whole numbers like 3, -76, 20393) double - which store floating point numbers (decimal numbers like 6.3, -0.9, and 60293.93032) boolean - which store Boolean values (either true or false). 3 Receipt example What's bad about the following code?

public class Receipt { public static void main(String[] args) { // Calculate total owed, assuming 8% tax / 15% tip System.out.println("Subtotal:"); System.out.println(38 + 40 + 30); System.out.println("Tax:"); System.out.println((38 + 40 + 30) * .08); System.out.println("Tip:"); System.out.println((38 + 40 + 30) * .15); System.out.println("Total:"); System.out.println(38 + 40 + 30 + (38 + 40 + 30) * .08 + (38 + 40 + 30) * .15); } } The subtotal expression (38 + 40 + 30) is repeated So many println statements

We will use variables to solve the above problems. 4 Variables variable: A piece of the computer's memory that is given a name and type, and can store a value. Like preset stations on a car stereo, or cell phone speed dial: Steps for using a variable: Declare it - state its name and type Initialize it - store a value into it

Use it - print it or use it as part of an expression 5 Declaration variable declaration: Sets aside memory for storing a value. Variables must be declared before they can be used. Syntax: type name; The name is an identifier. x int x; myGPA

double myGPA; 6 Assignment assignment: Stores a value into a variable. The value can be an expression; the variable stores its result. Syntax: name = expression; int x; x = 3; double myGPA; myGPA = 1.0 + 2.25; x

3 myGPA 3.25 7 Using variables Once given a value, a variable can be used in string concatenation: expressions: string + number = concatenated string (more on this later) int x; x = 3; System.out.println("x is " + x); // x is 3

System.out.println(5 * x - 1); // 14 You can assign a value more than once: int x; x = 3; System.out.println(x + " here"); x 3 11 // 3 here x = 4 + 7;

System.out.println("now x is " + x); // now x is 11 8 Declaration/initialization A variable can be declared/initialized in one statement. Syntax: type name = value; double myGPA = 3.95; int x = (12 - 3) * 2; myGPA 3.95 x 18

9 Assignment and algebra Assignment uses = , but it is not an algebraic equation. = left" means, "store the value at right in variable at The right side expression is evaluated first, and then its result is stored in the variable at left. What happens here? int x = 3; x = x + 2; // no solutions // mathematically // not an equation!

x 3 5 10 Multiple Variables Multiple variables of the same type can be declared and initialized at the same time. Syntax: type name1, name 2, name3; type name1 = value1, name2 = value2, name3 = value3; int x, y, z; // declare three integers. int a = 1, b = 2, c = 3;// declare and initialize // three integers.

11 Assignment and types A variable can only store a value of its own type. int x = 2.5; // ERROR: incompatible types An int value can be stored in a double variable. The value is converted into the equivalent real number. double myGPA = 4; myGPA 4.0 12 Compiler errors Order matters.

int x; 7 = x; // ERROR: should be x = 7; A variable can't be used until it is assigned a value. int x; System.out.println(x); // ERROR: x has no value You may not declare the same variable twice. int x; int x; // ERROR: x already exists int x = 3; int x = 5; // ERROR: x already exists

How can this code be fixed? 13 Printing a variable's value Use + to print a string and a variable's value on one line. double grade = (95.1 + 71.9 + 82.6) / 3.0; System.out.println("Your grade was " + grade); int students = 11 + 17 + 4 + 19 + 14; System.out.println("There are " + students + " students in the course."); Output: Your grade was 83.2 There are 65 students in the course. 14

Receipt question Improve the receipt program using variables. public class Receipt { public static void main(String[] args) { // Calculate total owed, assuming 8% tax / 15% tip System.out.println("Subtotal:"); System.out.println(38 + 40 + 30); System.out.println("Tax:"); System.out.println((38 + 40 + 30) * .08); System.out.println("Tip:"); System.out.println((38 + 40 + 30) * .15); } } System.out.println("Total:");

System.out.println(38 + 40 + 30 + (38 + 40 + 30) * .15 + (38 + 40 + 30) * .08); 15 Receipt answer public class Receipt { public static void main(String[] args) { // Calculate total owed, assuming 8% tax / 15% tip int subtotal = 38 + 40 + 30; double tax = subtotal * .08; double tip = subtotal * .15; double total = subtotal + tax + tip; } }

System.out.println("Subtotal: " + subtotal); System.out.println("Tax: " + tax); System.out.println("Tip: " + tip); System.out.println("Total: " + total); 16 Type boolean boolean: A logical type whose values are true and false. int age = 22; boolean minor = (age < 21); boolean lovesAPCS = true; System.out.println(minor); // false System.out.println(lovesAPCS); // true

17 final The keyword final can be used in front of a variable declaration to make it a constant that cannot be changed. Constants are traditionally capitalized. public class TestFinal { public static void main(String[] args) { final double PI = 3.14; System.out.println(PI); PI = 4.2; // This will cause a syntax error } } 18 Naming variables

The name of the variable should describe the data it holds. A name like score helps make your code easier to read. A name like x is not a good variable name in programming, because it gives no clues as to what kind of data it holds. Do not name your variables crazy things like thisIsAReallyLongName, especially on the AP exam. You want to make your code easy to understand, not harder. 19 Naming variables The convention in Java and many programming languages is to always start a variable name with a lower case letter and then uppercase the first letter of each additional word. Variable names can not include spaces so uppercasing the first letter of each additional word makes it easier to read the name. Uppercasing the first letter of each additional word is called camel case. int numOfLives = 3; // camel case to highlight words

Another option is to use underscore symbol _ to separate words, but you cannot have spaces in a variable name. Java is case sensitive so playerScore and playerscore are not the same. int num_of_lives = 3; // use _ to highlight words. 20 Keywords keyword: An identifier that you cannot use to name a variable because it already has a reserved meaning in Java. abstract boolean break byte case catch

char class const continue default do double else extends final finally float for goto if implements

import instanceof int interface long native new package private protected public return short static strictfp super switch

synchronized this throw throws transient try void volatile while 21 repl.it assignments The following labs are repl.it assignments. Log on to your account to complete them. They are included here for your reference. Lab 1: Create Variables and Printing:

22 repl.it assignments The following labs are repl.it assignments. Log on to your account to complete them. They are included here for your reference. Lab 2: Create Variables and Printing 2: 23 repl.it assignments The following labs are repl.it assignments. Log on to your account to complete them. They are included here for your reference. Lab 3: Create Variables and Printing them: 24

References 1) Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp 2) Runestone CSAwesome Curriculum: https://runestone.academy/runestone/books/published/csawesome/index.html For more tutorials/lecture notes in Java, Python, game programming, artificial intelligence with neural networks: https://longbaonguyen.github.io 25

Recently Viewed Presentations

  • Goals - PC&#92;|MAC

    Goals - PC\|MAC

    The perimeter of this rectangle is 18 feet. Many elementary students confuse area and perimeter. Many students would select the correct answer for the wrong reason. In addition to this shortcoming, the distractors in this item are also unbalanced. Three...
  • Presente Progresivo - !El mundo de la Sra. Martinez!

    Presente Progresivo - !El mundo de la Sra. Martinez!

    El Imperfecto Progresivo hoy pasado futuro The imperfect progressive describes an action that was taking place over a period of time in the past., ¿Cómo lo formamos? + Compound verb form 2 parts Imperfect tense forms of ESTAR Present Participle...
  • Cognitive Neuroscience - raphe.kaist.ac.kr

    Cognitive Neuroscience - raphe.kaist.ac.kr

    Franz Joseph Gall (1758-1828) was a founder of phrenology, which stated that contours of the skull provided information about the cognitive capacities and personalities of individuals. His method involved correlating variations in character with variations in craniological signs.
  • DEPOSIT AND Investment disclosures

    DEPOSIT AND Investment disclosures

    Weighted average maturity measure expresses investment time horizons, the time when investments when become due & payable, in years or months, weighted to reflect the dollar size of an individual investments within an investment type. Duration is a measure of...
  • The Means of Implementation in Support of the

    The Means of Implementation in Support of the

    Role of regions in multi-layered accountability. Accountability for progress towards sustainable development goes beyond the mere monitoring of results. A strong accountability framework that identifies responsibilities and holds actors accountable will be crucial to make the post-2015 agenda work.
  • Diffusion, Microscope & Cell Lab 02 Activity 1

    Diffusion, Microscope & Cell Lab 02 Activity 1

    Clean oil immersion lens with chemicals provided by your instructor Cleaning the Microscope Parts of the Microscope Fine adjustment knob Stage Stage clips Aperture Diaphragm Light Base Ocular Body tube Nosepiece Objective lenses (10, 40, 100x) Arm Course adjustment knob...
  • AOSS 321, Fall 2006 Earth Systems Dynamics 10/9/2006 ...

    AOSS 321, Fall 2006 Earth Systems Dynamics 10/9/2006 ...

    Alternative form of the thermal wind Recall: Hypsometric equation Thickness Similarity of the equations Thickness and thermal wind AOSS 321, Winter 2009 Earth Systems Dynamics Lecture 12 2/17/2009 Christiane Jablonowski Eric Hetland [email protected] [email protected] 734-763-6238 734-615-3177 ...
  • Introduction to the USC Human Subjects Protection Program

    Introduction to the USC Human Subjects Protection Program

    Institutional Review Board (IRB) Submissions. Minimal risk means that the probability and magnitude of harm or discomfort anticipated in the research are not greater in and of themselves than those ordinarily encountered in daily life or during the performance of...