Lecture 03 Variables Prof. Katherine Gibson Prof. Jeremy Dixon - - PowerPoint PPT Presentation

lecture 03 variables
SMART_READER_LITE
LIVE PREVIEW

Lecture 03 Variables Prof. Katherine Gibson Prof. Jeremy Dixon - - PowerPoint PPT Presentation

CMSC201 Computer Science I for Majors Lecture 03 Variables Prof. Katherine Gibson Prof. Jeremy Dixon Based on slides by Shawn Lupoli and Max Morawski at UMBC www.umbc.edu Last Class We Covered Algorithms Program Development


slide-1
SLIDE 1

www.umbc.edu

CMSC201 Computer Science I for Majors

Lecture 03 – Variables

  • Prof. Katherine Gibson
  • Prof. Jeremy Dixon

Based on slides by Shawn Lupoli and Max Morawski at UMBC

slide-2
SLIDE 2

www.umbc.edu

Last Class We Covered

  • Algorithms
  • Program Development
  • Control Structures

– Sequential – Decision Making – Loops

  • Types of Errors

– Syntax – Logic

2

slide-3
SLIDE 3

www.umbc.edu

Any Questions from Last Time?

slide-4
SLIDE 4

www.umbc.edu

Exercise

  • What will each of the following do?

1.print("Hello') Error – Need to have matching ' and " 2.Print('Hello') Error – Need to have lowercase print 3.print('Hello World') Hello World

4

slide-5
SLIDE 5

www.umbc.edu

Today’s Objectives

  • To start learning Python
  • To learn more about variables

– How to use them – Different types

  • To learn how to use input and output

– To do interesting things with our program

  • To play a party game

5

slide-6
SLIDE 6

www.umbc.edu

“Cowboy Coding”

  • Jumping right in to writing code
  • Disadvantages

–No formal management of project –No standard way of coding –Not planning things out

  • Forgetting to include important things
  • Having to make big changes later

6

slide-7
SLIDE 7

www.umbc.edu

Software Development Process

  • 1. Analyze the problem

– Determine specifications (requirements)

  • 2. Create a design
  • 3. Implement the design
  • 4. Test and debug the program
  • 5. Maintain the program

7

slide-8
SLIDE 8

www.umbc.edu

Example: Temperature Converter

You have been invited to live in Europe during a semester abroad. You aren’t sure how to dress because the temperature is given in Celsius.

  • Problem:

–Temperature is given in Celsius

  • Solution:

–Write a program to convert Celsius to Fahrenheit

8

slide-9
SLIDE 9

www.umbc.edu

Input/Process/Output

  • Input

– What information do you need for your converter?

  • Process

– What formulas do you need for your converter?

  • Output

– What is the output from your converter?

9

slide-10
SLIDE 10

www.umbc.edu

Introduction to Python (Variables)

slide-11
SLIDE 11

www.umbc.edu

Python

  • Python is a widely used language

– General purpose – High-level language

  • Emphasizes code readability

– More streamlined than some other languages

11

slide-12
SLIDE 12

www.umbc.edu

“Hello World!”

  • In Python:

print("Hello World!")

  • In the C++ programming language:

#include <iostream> int main() { std::cout << "Hello, world!\n"; }

12

slide-13
SLIDE 13

www.umbc.edu

Elements of a Program

  • Identifiers

– Variables – Modules (later in the semester) – Functions (later in the semester)

  • Expressions

– Code that manipulates or evaluates identifiers

13

slide-14
SLIDE 14

www.umbc.edu

We Start Python Today!

  • Two ways to use python

–You can write a program as a series of instructions in a file and then execute it –You can also test simple Python commands in the Python interpreter

14

We will write programs

slide-15
SLIDE 15

www.umbc.edu

What Is a Variable?

  • Something that holds a value

– Can change (unlimited number of times)

  • Similar to variables in math
  • In simple terms, a variable is a

“box” that you can put stuff in

15

slide-16
SLIDE 16

www.umbc.edu

Rules for Naming Variables

  • Variables can contain:

– Uppercase letters (A-Z) – Lowercase letters (a-z) – Numbers (0-9) – Underscores (_)

  • Variables can’t contain:

– Special characters like $, #, &, ^, ), (, @

16

slide-17
SLIDE 17

www.umbc.edu

More Rules for Naming Variables

  • Variables can be any length

– x – IsKanyeRunningForPresidentIn2020 – myName

  • Variables cannot start with a digit

– 2cool4school is not a valid variable – cool4school is a valid variable

17

slide-18
SLIDE 18

www.umbc.edu

Variables and Keywords

  • Keywords are the reserved words in Python
  • Variables cannot be keywords

– or is not a valid variable name – orange is an acceptable variable name

18

False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if

  • r

yield assert else import pass break except in raise

slide-19
SLIDE 19

www.umbc.edu

Exercise: Variables

  • Are the following legal or illegal in Python?

19

1spam

No – Illegal!

raise1

Yes – legal!

Spam_And_Eggs

Yes – legal! But it doesn’t follow

  • ur coding standards!

spamAndEggs or spam_and_eggs

slide-20
SLIDE 20

www.umbc.edu

Using Variables in Python

  • Create a variable by declaring it
  • Also need to initialize it

– Use the assignment operator (=)

richFiddy = 50000000 poorFiddy = 0.50 brokeFiddy = 0

20

assignment operator

slide-21
SLIDE 21

www.umbc.edu

Introduction to Python (Expressions)

slide-22
SLIDE 22

www.umbc.edu

Expressions

  • Programs manipulate data

–Allows us to do interesting things

  • Expressions calculate new data values
  • Use assignment operator to set new value

22

slide-23
SLIDE 23

www.umbc.edu

Expressions Example

numCandy = 10 priceCandy = 0.50 totalCandy = numCandy * priceCandy

23

assignment operator variable being set value (a “literal”) expression

slide-24
SLIDE 24

www.umbc.edu

Common Mistake

  • Many new programmers mix up the left and

right hand sides of the assignment operator

  • Variable being set is on the left
  • Expression is on the right

24

numCandy = 10 10 = numCandy 

slide-25
SLIDE 25

www.umbc.edu

Variable Types

  • There are many different kinds of variables!

–Numbers

  • Integers
  • Floats (decimals)

–Booleans (True and False) –Strings (collections of characters)

25

slide-26
SLIDE 26

www.umbc.edu

Variables Types: Examples

aString = "Hello class" float_1 = 1.12 myBool = True anInteger = 7 dogName = "Mrs. Wuffington" classCode = 201

26

slide-27
SLIDE 27

www.umbc.edu

Variable Usage

  • Variables are designed for storing information
  • Any piece of information your program uses
  • r records must be stored in a variable

27

slide-28
SLIDE 28

www.umbc.edu

Introduction to Python (Input and Output)

slide-29
SLIDE 29

www.umbc.edu

Output

  • Output is text printed to the screen

–So the user can see it and respond

  • The command for this is print

– Use the keyword “print” and put what you want to be displayed in parentheses after it

29

slide-30
SLIDE 30

www.umbc.edu

Output Example

print (3 + 4) print (3, 4, 3 + 4) print() print("The answer is", 3 + 4) 7 3 4 7 The answer is 7

30

slide-31
SLIDE 31

www.umbc.edu

Output Exercise 1

  • What will the following code snippet print?

a = 10 b = a * 5 c = "Your result is: " print(c, b) Your result is: 50

31

slide-32
SLIDE 32

www.umbc.edu

Output Exercise 2

  • What will the following code snippet print?

a = 10 b = a a = 3 print(b) 10

32

There are two possible

  • ptions for what this

could do! Any guesses?

slide-33
SLIDE 33

www.umbc.edu

Output Exercise 2 Explanation

  • Why does it print out 10?
  • When you set one variable equal to another,

they don’t become linked!

  • After b is set to 10, it no longer has

anything else to do with a

33

slide-34
SLIDE 34

www.umbc.edu

Output Exercise 2 Explanation

34

a = 10 b = a a = 3 print(b)

10

a b

slide-35
SLIDE 35

www.umbc.edu

Output Exercise 2 Explanation

35

a = 10 b = a a = 3 print(b)

10

a

10

b

slide-36
SLIDE 36

www.umbc.edu

Output Exercise 2 Explanation

36

a = 10 b = a a = 3 print(b)

3

a

10

b

slide-37
SLIDE 37

www.umbc.edu

Output Exercise 2 Explanation

37

a = 10 b = a a = 3 print(b)

3

a

10

b

  • utput: 10
slide-38
SLIDE 38

www.umbc.edu

Input

  • Input is text we get from the user

– We must tell them what we want first

userNum = input("Please enter a number: ") print(userNum)

  • The output will look like this:

Please enter a number: 10

38

10

slide-39
SLIDE 39

www.umbc.edu

How Input Works

userNum = input("Please enter a number: ")

  • Takes the text the user entered and stores it

– In the variable named userNum

  • You can do this as many times as you like!

userNum = input("Enter another number: ") userNum2 = input("Enter a new number: ") userAge = input("Please enter your age: ")

39

slide-40
SLIDE 40

www.umbc.edu

Input as a String

  • Everything that comes through input()

will come in the form of a string

  • There is a difference between "10" and 10

– "10" is a two character long string – 10 is understood by Python as a number

40

slide-41
SLIDE 41

www.umbc.edu

Converting from String

  • To turn an input string into a number,

you can do the following:

aNum = input("Enter a number: ") aNum = int(aNum)

  • int stands for integer (a whole number)
  • You can also do it in one line:

aNum = int(input("Enter a number: "))

41

slide-42
SLIDE 42

www.umbc.edu

Class Exercise: Mad Libs

  • Mad Libs is a phrasal template word game

where one player prompts others for a list

  • f words to substitute for blanks in a story,

before reading the – often comical or nonsensical – story aloud

  • The game is frequently played as a

party game or as a pastime

42

slide-43
SLIDE 43

www.umbc.edu

Exercise: Calculating Averages

  • Write, on paper or on your computer, a

program that asks the user for two numbers and prints out the average.

  • Make sure to use variables, and to get the

input from the user!

  • Does the order of operations come into play

for this exercise?

43

slide-44
SLIDE 44

www.umbc.edu

Exercise: Assignment Weighting

  • Pretend you’re writing a program to compute

someone’s weight grade. You have so far: hwWeight = 0.4 examWeight = 0.5 discussionWeight = 0.1

  • Write a program that then asks the user for their

homework grade, exam grade, and discussion grade and prints out their total grade in the class.

44

slide-45
SLIDE 45

www.umbc.edu

Announcements

  • Your Lab 0 is in class this week!

– Go to your scheduled location and time

  • Homework 1 is out (on Blackboard)

– Due by next Monday (Feb 8th) at 8:59:59 PM – You must have completed the Syllabus Quiz to see it

  • Academic Integrity Quiz on Blackboard

– Must complete to see Homework 2 next week

45

slide-46
SLIDE 46

www.umbc.edu

Practice Problem

  • You recently accepted a new job in Philadelphia, PA

and you are trying to figure out if you should take the train or drive.

– Taking the train costs $4.90 each way – It is 75 miles round trip, your car averages 28 mpg, and gas is $2.03 per gallon plus $0.06 per mile in maintenance. Your new work has free parking, so you don’t need to pay.

  • Write a program that can calculate the total cost to

drive to work, and print out if it is cheaper to drive to work, or to take the train. By how much?

46