Lecture 2 Key Concepts Pt. 2

Eric Brauer

What is a program?

A program is a sequence of instructions. Instructions accomplish one of three things:

Output:

  • Text, audio, imagery, sensor, etc.

Input:

  • Text, audio, imagery, sensor, etc.

Processing:

  • Mathematic, logic, conversion, etc.

User Output

You’ve already worked with displaying user output in Lab1:

print(“Hello world.”)

print(variable)

Printing With Non-Strings

To combine two datatypes in one print(), put a plus sign between strings and the variable. You also need to convert other data types to strings:

age = 17  # no quotes, means this is an integer. 
print(“Cannot combine strings and integers like “ + age)  # This will cause error.
print(“Hello, you are “ + str(age) + “ years old.”)  # use str() to convert age.

Datatype Conversion

str()
13 -> ‘13’
int()
‘13’ -> 13
float()
13 -> 13.0

Try these:

int('apple')
int(13.9)

User Input

User input is any data entered by the user running your script. This is in contrast to data you, the programmer, enter into the code or call from elsewhere.

This allows for user interaction. The program can respond to what they enter, and do different things as a result.

Basic in concept, but complex in that it introduces an unknown into your program. It’s up to you to deal with that input properly.

Keep this in mind as you go through this course.

User Input: INPUT()

input()
This function is used to ask the user for data and then store it in an object.

year = input(“Enter your year of birth: ”)

The data in this object can then be used by the script at any point.

print(‘You were born in ’ + str(year) + ‘.’)

User Input: Command Line Arguments

A command line argument is data entered on the command line after the name of the script when it’s first run. You may know these as positional parameters in the Bash scripting world.

Ex:

./awesome.py variable1 variable2

Command line arguments are almost always preferable to using input() because they are easier to automate.

Modules

Before working with command line arguments it’s necessary to import the sys module. Fortunately it’s contained in our Python Standard library.

Python includes an extensive library of modules that are installed alongside Python itself. To work with command line arguments, we need to:

import sys

Modules II

This sys module contains a lot of useful functions for interacting with the computer system at a base level. Always refer to official documentation to learn more.

There are other, third-party modules that are not included in the standard library. You will need to install these using a tool like pip.

We will not be using these in our course.

Back To Command Line Arguments

Assuming you have imported sys, and run your Python program with arguments:

./awesome.py variable1 variable2

This data is then passed into a built-in list called sys.argv.

>>>> print(sys.argv)
[‘awesome.py’, ‘variable1’, variable2’]  # '' indicates that these are strings.
>>>> print(sys.argv[2])
'variable2'

Conditional Statements

Conditional statements allow you to program paths, or reactions to data.

Whether this be in reaction to user input, or data you request from a file, it changes the flow of the program.

At the very least, Conditional Statements need:

  • An if statement (condition to test)
  • An Action to take if the condition is true

IF Statements

If statements allow the program to respond if a specific condition is True. Take the following:

if condition == True:
    print(“Action 1”)
    print(“Action 1 continued”)
print(“everything here runs regardless of the outcome”)

Anything that is indented will only be run if the condition is true. The end of the indent indicates the end of the if statement’s action.

IF/ELSE Statements

year = 2023
dob = input(“Enter your date of birth: “)
if year – int(dob) <  19:  # Note! < only works with integers, so we need to convert
    print(“Sorry, you are too young.”)
else:
    print(“Okay, you are old enough.”)
print(“Have a nice day!”)

Actions after else will run if the condition is False. Only one print statement will be executed.

IF/ELIF/ELSE Statements

We can evaluate multiple conditions for the same value. These are called else/if statements.

if age < 19:
     print(“You may not purchase alcohol.”)
 elif age < 25:
     print(“You may be asked to show your ID.”)
 else:
     print(“You are old. XD”)

The Order Of Conditions

When using if/elif/else, remember that order matters. The first condition that is true will be executed, all other conditions will be skipped.

grade = 82
if grade > 60:
    print("You got a C. Not bad.")
elif grade > 70:
    print("You got a B. That's great!")
elif grade > 80:
    print("You got an A! Congratulations!!")

Combining Conditions: And/Or

You might also choose to make your conditions more specific by using the logical operators and and or. These allow you to test more than condition on the same line.

grade = 82
if grade > 60 and grade <= 69:
    print("You got a C. Not bad.")
elif grade > 70 and grade <= 79:
    print("You got a B. That's great!")
elif grade > 80 and grade <= 89:
    print("You got an A! Congratulations!!")

Combining Conditions: And/Or

and
both conditions must be true for the statement to be considered true
or
if either condition is true, the statement is considered true
not
reverses logic. True becomes False, False becomes True

Loop Statements: WHILE

A loop statement allows us to loop through a section of code a set number of times. In a while loop, the script will continue to loop through the block of code while a condition is still true.

count = 0
while count != 5:
    print(count)
    count = count + 1
print("loop has ended")

In other words, a while loop is very similar to an if condition, except that the while loop will continue to run the action for as long as the condition is True. In this example, we run lines 2, 3, 4 how many times?

Infinite Loops

Remember to avoid Infinite Loops. If the indented code of your while loop doesn’t contain a way to change the condition, you will never escape the loop (at least until you press Ctrl+d to terminate your Python program).

count = 0
result = 0
while count != 5:
    x = int(input("Enter a number to add to result: "))
    result = count + x
print("loop has ended")

Using BREAK

One way to exit a loop is to use break.

while True:  # does true ever equal false? NO!
    x = input("Enter a word. Pressing enter exits.")
    if x == '':
        break  # breaks out of the containing loop immediately.
    print("The word entered was: " + x + ".")
pass  # this does nothing! But a good place to put a break point.

Summary: Comparisons

==
equal to
>
greater than
>=
greater than or equal to
!=
not equal to
<
less than
<=
less than or equal to

Summary: Functions

  • print()
  • input()
  • str()
  • int()
  • float()
  • len() # returns length!

Summary: Keywords

  • if, elif, else
  • import, as, from, in
  • True, False
  • and, or, not
  • pass, break …and more!