1. Input, output, variables, types, conditionals

Input => Process => Output

  1. Identify the problem inputs (requirements)
  2. Identify the problem outputs (results)
  3. Write an algorithm to transform inputs to outputs.
  4. If you don’t know how to do a step… research it!

Python input and output

print() does output
input() does input, returns input so you must assign it to a variable

x = input("Enter something: ")
print(x)
CautionCode Challenge 2.1.1

Write a program to input your first name and last name then output your last name, first name.

first = input("Enter your first name: ")
last = input("Enter your last name: ")
print(last, ",", first)
# could also do (see next section):
print(f"{last}, {first}")

F-Strings

  • F-Strings are Python’s answer to string interpolation.
  • This replaces the variable name with its value within a string.
  • Called an F-string because the f tells Python to interpolate the string.
name = 'George'
print("{name} was curious.")
print(f"{name} was curious.")
{name} was curious.
George was curious.
NoteCheck Yourself 1

Which is an example of a properly used string literal?

A. print(welcome)

B. print("welcome")

C. print "welcome"

D. print welcome

B

Note: In Python 2.7 and earlier the correct answer would be C. The syntax for the print function was changed in Python 3. Python 2 is no longer supported.

Variables

  • Variables are named areas of computer memory for storing data.
  • The name can be anything but should make symbolic sense to the programmer.
  • We write to the variable’s memory location with the assignment statement (=)
  • We read from the variable by calling its name.
  • Variable names must begin with a letter or _ and must only contain letters, numbers or _.

Variables are of a Specific Type

Type Purpose Examples
int Numeric type for integers only 45, -10
float Numeric type floating point numbers 45, -10
bool True or False values True, False
str Characters and text “A”, ‘Mike’

Type Detection and Conversion

Python Function What It Does Example of Use
type(n) Returns the current type of n type(13) == int
int(n) Converts n to type int int(“45”) == 45
float(n) Converts n to type float float(45) == 45.0
str(n) Converts n to type str str(4.0) == ‘4.0’

Programmatic Expressions

Programmatic Expressions contain operators and operands. They evaluate to a value, preserving type:

print(2 + 2)
print(2.0 + 2)
print("sh" + 'ip')
print('hi' + 2) # error
4
4.0
ship
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 4
      2 print(2.0 + 2)
      3 print("sh" + 'ip')
----> 4 print('hi' + 2) # error

TypeError: can only concatenate str (not "int") to str

Arithmetic Operators

Operator What it Does Example of Use
+ Addition or string concenation 3 + 4 == 7
- Subtraction 4 - 3 == 1
* Multiplication 3 * 4 == 12
/ Division 4 / 3 == 1.33333
// Intger division (quotent) 13 // 3 == 4
% Modulo (remainder) 13 % 3 == 1
( ) Force an order of operations 2 * (3 + 4) == 14
CautionCode Challenge 2.1.2: Program to divide up the check among diners in a party

Write a program that takes as input the amount of a restaurant check, tip %, and number of diners.

The program should output the total amount with tip, and the amount each diner owes.

bill = float(input("Enter the total amount of the bill $"))
tip = int(input("What % would you like to tip, eg. 20 == 20%? "))
tip_pct = tip/100
diners = int(input("How many diners? "))
total = bill + bill*tip_pct
share = total / diners
print("Total Bill, with Tip: ", total)
print(f"Even share among {diners} diners is {share:.2f}")
NoteCheck Yourself 2

What is the value of str(314) ?

A. 314

B. "314"

C. int

D. '34.0'

B

NoteCheck Yourself 3

What is the value of type(314.0) ?

A. 314

B. float

C. int

D. '314.0'

B

NoteCheck Yourself 4

What is the output of the following python code?

a = 10
b = 2
c = 1 + (a/b)
print(c)

A. 6

B. 5.5

C. 6.0

D. 5

C

Program Flow Control with IF

  • The IF statement is used to branch your code based on a Boolean expression.
if boolean-expression:
    statements-when-true
else:
    statemrnts-when-false

Python’s Relational Operators

Operator What it does Examples
> Greater than 4>2 (True)
< Less than 4<2 (False)
== Equal To 4==2 (False)
!= Not Equal To 4!=2 (True)
>= Greater Than or Equal To 4>=2 (True)
<= Less Than or Equal To 4<=2 (True)

Expressions consisting of relational operators evaluate to a Boolean value

CautionCode Challenge 2.1.3: Presssure sensor that determines whether to open a door

Write code that simulates a pressure sensor that opens a door when the pressure is larger than 10; otherwise, it closes the door.

reading = float(input("Sensor Reading: "))

if reading > 10:
    status = "Opening"
else:
    status = "Closing"

print(f"{status} the door")
NoteCheck Yourself 5: Relational operators

On Which line number is the Boolean expression True?

x = 15      # 1
y = 20      # 2
z = 2       # 3
x > y       # 4
z*x <= y    # 5
y >= x-z    # 6
z*10 == x   # 7

A. 4

B. 5

C. 6

D. 7

C

Python’s Logical Operators

Operator What it does Examples
and True only when both are True 4>2 and 4<5 (True)
or False only when both are False 4<2 or 4==4 (True)
not Negation(Opposite) not 4==2 (True)
in Set operator 4 in [2,4,7] (True)
NoteCheck Yourself 6: Logical Operators

In the following code, which line evaluates to True?

raining = False              # 1
snowing = True               # 2
age = 45                     # 3
age < 18 and raining         # 4
age >= 18 and not snowing    # 5
not snowing or not raining   # 6
age == 45 and not snowing    # 7

A. 4

B. 5

C. 6

D. 7

C

Multiple Decisions: IF ladder

Use elif to make more than one decision in your if statement. Only one code block within the ladder is executed.

if boolean-expression1:
    statements-when-exp1-true
elif boolean-expression2:
    statements-when-exp2-true
elif boolean-expression3:
    statements-when-exp3-true
else:
    statements-none-are-true

#Elif versus multiple ifs...
# One decision or multiple decisions. 

x = int(input("enter an integer"))

# one decision
if x>10:
    print("A:bigger than 10")
elif x>20:
    print("A:bigger than 20")    

    # Multiple decisions
if x>10:
    print("B:bigger than 10")
if x>20:
    print("B:bigger than 20")
NoteCheck Yourself 7: IF statement

Assuming values x = 25 and y = 6, what will be printed when the following code is run?

if x > 20:
    if y == 4:
        print("One")
    elif y > 4:
        print("Two")
    else:
        print("Three")
else:
    print("Four")

A. One

B. Two

C. Three

D. Four

B

CautionCode Challenge 2.1.4: Number to letter grade
  • Letter grades in a college class are computed as follows:

    • 95 and above is an A
    • 75 and above, but below 95 is a B
    • 50 and above, but below 75 is a C
    • below 50 is F
  • Write a program to input the number grade and calculate the letter grade

  • The program should also print an error message if the provided number grade is out of range (i.e., > 120 or < 0).

number_grade = int(input("Enter your numerical grade: 0 - 120"))
letter_grade = "unknown"

if number_grade >= 0 and number_grade <= 120:

    if number_grade >= 95:
        letter_grade = "A"
    elif number_grade >= 75:
        letter_grade = "B"
    elif number_grade >= 50:
        letter_grade = "C"
    else:
        letter_grade = "F"

    print(f"For {number_grade} points the letter grade is {letter_grade}")

else:
    print(f"Number grade of {number_grade} is out of range!")