SmithLogo

CSC 111

Introduction to Computer Science Through Programming

Smith Computer Science



Lecture Notes 03: Intro to Python





How do we get from 0s and 1s to Python?






The instruction Cycle: in detail



1: FETCH




2: DECODE




3: READ




4: EXECUTE






And now, let's look at high-level programming.




Why do we need a "Programming Language"?

Activity 1 [1 minute]:
First Question: Why not just use English?

Activity 2 [1 minute]:
Explain how any of these might be unclear:
  • "Call me a taxi, please."
  • "I saw someone on the hill with a telescope."
  • "Look at the dog with one eye."


A computer can't know what you "really" meant! so
  • it will do what you said, not what you meant
Solution: Use an unambiguous form of the language, even if it is a little less expressive.


In this case, we will be using the high-level programming language called Python.




User Programs Vs Operating System

There are two main types of programs: applications, and the programs related to the operating system.



In this class, we will focus on simple applications




Line-by-Line Vs Full-Program Execution

To execute a high-level language in a machine, we need to get the human-readable statements into machine-readable form and then execute it.

There are two main ways to do this:

Python is an interpreted language.


(From Jordan Crouser's course)

One thing we can do with an interpreted language is to run it line by line.

An interactive python interpreter can be used, where the user enters and executes python statements line by line. The interactive interpreter then waits for the user to enter the next statement.

However, most of the work we'll do in this class will involve using the interpreter on whole programs without it expecting interaction from the user (except to enter inputs).



From High-Level Python to Execution

The idea is that we write in Python, and then we process it so that the computer can execute.

Python does this in two steps:




Statements

Python is written in a series of statements, each of which demand some action from the computer.

Each statement is a block of code (very commonly a single line of code). Statements can be expressions, assignments, comments, or control structures.




Our first program: Hello World

We will use an online visualizer to show how the code works. This is interpreting the code and showing how it works with simple visualizations.

go to this link

Activity 3 [1 minute]:

  1. Press "Visualize Execution":


  2. Locate the Output area (on the right) and press "Next" to see what gets "printed"


Our second program: Ascii art

Activity 4 [1 minute]:
  1. Locate the link to "Edit this code" and press it:


  2. Make the appropriate changes to cause the following image to print:





Functions

You will notice that we used the construction:
print ( <something> )
to get the program to display output in the console. Above, we're asking Python to display a string literal;
A string literal is text to be displayed literally (not executed). It's the stuff between quotes (or double quotes);

A function is a procedure / routine that takes in some input and does something with it (just like in math)

Some get converted to a value; some cause something to be displayed in the console; some get information from the keyboard; some do stranger and cooler things.

We will be using some functions that are called built-in because they come with Python.

Later, we'll make our own!

In general, functions have a special name (print in this case), and parentheses after the name.
IF the function needs input to "do its thing", it should be placed between the parentheses:

\[ \texttt{print ( "this is the input that print uses" )} \] It can also print the content of variables : \[\texttt{print ( x )} \]
Or the result of an expression: \[ \texttt{ print ( (x + 17)/2 )} \]




Variables and Assignments



Variables are like boxes that can store different objects.

In Python, the "things" you store inside variables are called values.

This is similar to the concept of variables used in algebra: \[ x = 5x - 24\]

However, in Python, instead of "solving for x", we actually want to be able to store values in a known location (and under a known name).

So, in Python, we read the statement: \[ x = 5\] as "we assign the value 5 into the variable called 'x'"
(we sometimes say "x is equal to 5" but in Python, we mean "x is assigned the value 5").

This means that we need to be able to assign a value to a variable. In python, we do this in the following way:

x = 5
y = 2
z = x + y
print(z)


Here, we have three different assignments:

Check the way this is executed, line-by-line, in this link.

Variables can be assigned numbers, text, and other things; we'll talk about that later.

Also, note that assignment can overwrite an existing value!
For example:

Activity 5 [1 minute]:
What would this print?
x = 5
x = 3
print(x)


A useful shortcut is to use simultaneous assignments:
Instead of doing this:
x = 5
y = 5
z = 5
w = 11
num = w + x + y + z
print(num)


One can do this:
x, y, z = 5
w = 11
num = w + x + y + z
print(num)





Quick Lookahead: Identifiers

Identifiers refer to the names used to create a variable.

Valid identifiers are those that follow three rules:

  1. it must contain letters(a-z, A-Z), digits (0–9), or underscores (_)
  2. it must start with a letter or an underscore
  3. It cannot contain spaces


Activity 6 [1 minute]:
Which are valid? (or what is wrong with them?)
  1. 2good2BTru
  2. IsThIsOK?
  3. HowAbout-thisOne
  4. th1sHa5ToBe_0K
  5. _don'tBeSoSure
  6. _IamSure
  7. finally






Quick Lookahead: Reserved Words (keywords)

Some words are reserved in Python. That means they can't be used as Identifiers.

These are reserved because they are either the names of built-in functions, or keywords in the construction of a special block of code that helps you do more powerful programs (code constructs).

We'll look at these later, but the following are the reserved words in Python:

FALSE await else import pass
None break except in raise
TRUE class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield




A note on Naming Conventions

A convention is not a strict rule, it is a "way of doing things" that a majority is comfortable with.

In python, there are some coding conventions that we should know:

  1. the name of the variable should tell you something about what the variable contains
    Example: \( \texttt{height} \) is better than \( \texttt{ht} \)
  2. If you want to use multiple words, separate them with an underscore,
    Example: \( \texttt{first_name} \)
  3. if the value isn’t going to change (i.e. the variable is a constant), use ALL CAPS
    Example: \( \texttt{PI = 3.141592} \)






Comments

Comments are parts of a program that are human readable and that the computer skips when interpreting.

They are placed there to add context or clarify the functionality of a program.

Adding clear and informative comments is crucial to good programming.

These are ways of commenting:

# This is a comment
print("This will run.")  # This won't run

# print("This print is 'commented out'.") # this is a commented comment

# If you want multiline comments
#   you have to add the hash mark
#   in each line

'''
Sometimes  people use
tripple quotes
But that's technically Wrong
(more on that later)
'''

print("This is the second statement to run.")


Activity 7 [1 minute]:
Try out this link

When to comment

Common practice is to: The following is a basic example:
#        Name: Example Header
#     Authors: Pablo Frank & Yak DaRippa
#      Course: CSC111
#        Date: 2021/09/10
# Description: My First Project Program.

print("The amount Yak helped was: ")

# We'll see modulo and int-div next class
print((2**5//6)%5)






Before next class (Monday)

[Due for everyone] Read Section "3.8 Comments and Docstrings" (3.81 up to 3.86) in Docstrings in Python (Google Style)
As well as these examples
(Note that we will keep our DocStrings very short and concise...the examples are extensive)