SmithLogo

CSC 111

Introduction to Computer Science Through Programming

Smith Computer Science



Lecture Notes 04: Python Basics





Python Expressions

Expressions are combinations of variables and values that must be "resolved" and turned into a combined value before the statement is completely executed.

12 + 6
x = 5
y = 2
z = x + y
w = x + 1 + y + 123 + z
print(x)
print(y)
print(z)
print(w)


Examples of expressions in Python are:
  1. 12 + 6     : this expression resolves to an 18 but is not saved in a variable;
  2. x = 5      : the right-hand-side of the "=" sign (value 6) is a 'trivial' expression, since it is already a value);
  3. y = 2      : same as above;
  4. z = x + y      : here, the expression that needs resolving is x + y; it will resolve to the value 7
  5. w = x + 1 + y + 123 + z     : again, the expression is on the right-hand side of the "=" sign; this one combines numbers and variables.


Activity 1 [1 minute]:
try it out, step by step, here.




Basic Operations

An operator is a symbol that indicates a transformation on one or more entities called operands.

There are unary operators that apply to a single element, and binary operators that require two such entities to operate on.

The following are the basic arithmetic operations you might find in an expression:

  1. Addition: y = x + 7    it may contain constants (7) or variables.
  2. Subtraction: z = y - 2   it may contain constants (2) or variables
  3. Multiplication: m = x * 5    it may contain constants (5) or variables
  4. Division: n = m / 5    it may contain constants (5) or variables
  5. Integer Division: n = n // 2    it may contain constants (2) or variables; same as floor(n/2)
  6. Exponentiation(Power): p = n ** 2    it may contain constants (2) or variables; same as \(n^2\)
  7. Modular arithmetic (Modulo): q = 9 % 3    it may contain constants (3) or variables
    This is the same as: integer remainder of 9/3
A negative value simply has the minus sign before the number : -3 (unary operator "-"").
Note that that is the same as \( -1 * 3\)

When multiple operators and operands, the order of operation follows the PEMDAS rule:
complete in order of greatest importance first:
Activity 2 [1 minute]:
What is the result for: \[ 8-(4 - 3**2)*(4/2)\]



Strange Operator: Integer Division //

(In the following explanation, we use "=" as "equals")

When we divide two numbers, we might have a perfect fit between the numerator and the denominator
For example:    \(x = 8/4\)   (which has a quotient of 2)

OR, we could have a quotient AND a remainder
For example:   \(x = 9/4\)   (which has a quotient of 2 AND a remainder of 1)

IF   \(n / d = q \)   with a remainder of   \(r\)

we can reorder this as:   \( d*q + r = n\)

Example: since   \(17 / 5 = 3 \)   with a remainder of 2, then
\(5*3 + 2 = 17 \)

What integer division does is ignore the remainder.
So, the operation: \(17 // 5 = 3 \)

This is the same as \( \texttt{floor(17/5)} \)
(This is equivalent to rounding down, or in the direction of \(-\infty\))

Activity 3 [2 minutes]:

try it out, step by step, here.

  • Now subtitute the parameter of the print statement for: "17 // -5"; What happens? Why?
  • Now subtitute the parameter of the print statement for: "-17 // 5"; What happens? Why?
  • Now subtitute the parameter of the print statement for: "-17 // -5"; What happens? Why?



Strange Operator: Modulo %

We have the same approach as before:
Example: since   \(17 / 5 = 3 \)   with a remainder of 2, then
\(5*3 + 2 = 17 \)

What modulo does is ignore the quotient and it "returns" the remainder.
So, the operation: \(17 % 5 = 2 \)

Note that Python chooses to return a remainder (modulo result) with the same sign as the denominator!

Another way to think about it is this:

if we want to know \(17 % 5\), we can first obtain \(17 // 5\), which is \(\mathbf{3}\),
and then see what the remainder would be if substitute that as the quotient:
\(17 = \mathbf{3} \cdot 5 + x \)
Whatever \(x\) must be here is the correct remainder. In this case, it is 2 because \(17 = 3 \cdot 5 + \mathbf{2} \)

Activity 4 [1 minute]:

try it out, step by step, here.

  • Now subtitute the parameter of the print statement for: "17 % -5"; What happens? Why?
  • Now subtitute the parameter of the print statement for: "-17 % 5"; What happens? Why?
  • Now subtitute the parameter of the print statement for: "-17 % -5"; What happens? Why?


Modulo is useful for situations in which you are working in a "cyclic" system, like a calendar or the Caesar Cipher!.


Example 1:
You are using a Caesar cipher to encode letters by shifing 5 spots forward, and you want to encode the letter X.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


We would like to add 5 to whatever X's index is and obtain a new one, however, that would be:
\( \text{New_index} = \text{X_index} + 5 = 23 + 5 = 28\)
and there is no letter at index 28.


So, you can use modulo arithmetic like this:

\( \text{New_index} = (\text{X_index} + 5) \% 26 = 28 \% 26 = 2\)
Which corresponds to the letter C.


Example 2:
You are using a Caesar cipher to encode letters by shifing 5 spots back, and you want to encode the letter C.

We would like to subtract 5 from whatever C's index is and obtain a new one, however, that would be:
\( \text{New_index} = \text{C_index} - 5 = 2 - 5 = -3\)
and there is no letter at index -3.


So, you can use modulo arithmetic like this:

\( \text{New_index} = (\text{C_index} - 5) \% 26 = -3 % 26 = 23\)
this is because \( -3/26 \approx -0.12 \) which means that \( -3//26 = -1 \)
So if we subtitute that as the quotient:
\(-3 = \mathbf{-1} \cdot 26 + remainder\),
the remainder value that would make this true is 23
Which corresponds to the letter X.






Integers and Floats

For numeric assignments, you'll see two main types:






Built-In functions for numbers

The following are built-in functions that work with numbers.



Terminology: "return":


return indicates that, when this function is carried out, Python replaces the expression for a value; the value the expression resolves to is called the return value;

Terminology: "parse":


To parse means to "break into parts and interpret". In this context, it means that Python "treats" the input in a specific way.

For example: in the sentence ... "Your son's only surviving grandfather has only one grandchild. That grandchild's only parent is an expert parser.", Who is the expert parser?



Some additional details on some functions:

The int function

The int function \[ \texttt{ int ( $<$ text that can be read as a number $>$ )} \] accepts a string literal or a variable with a string inside (more on this later) and attempts to convert it into an integer.

The following is one way of using it:

Activity 5 [1 minute]:
Run the following program;

Now comment out the middle statement and run it again. What happens?


The float function

The float function \[ \texttt{ float ( $<$ text that can be read as a number $>$ )} \] accepts a string literal or a variable with a string inside (more on this later) and attempts to convert it into a float.

The following is one way of using it:

Activity 6 [1 minute]:
Run the following program;

Now comment out the middle statement and run it again. What happens?


The str function

The str function returns the string version of an object; we'll talk about strings in a future class; for now think of them as the "literal text" version of an object.

The ord function

ord() function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument.
ASCII is a subset of Unicode so, for our purposes, ord returns the ASCII number-value of a character.

The chr function

The chr() function returns a character (a string) whose Unicode code point is the integer.
ASCII is a subset of Unicode so, for our purposes, chr returns the ASCII character for an int (int the right range.






Input

A program may accept input from the keyboard, and print it or use it to make decisions.

In python, the way to tell the program to "read input from the keyboard at this point", is to
use the input() built-in function.

At the point where that statement is executed, the program makes sure to "read characters from input until it detects a 'newline'".

If you want the program to display a prompt for the user that asks for input, you may add a little message inside the parentheses:
input("Please Write your name and then press 'return': ")

The usual way to use input is by assigning what the user inputs into a variable and using that variable later in the code.

Note that, the input function reads input as text!

If we want to have the input interpreted as a number, we need to use the built-in functions (int, float) to get Python to do this.

Activity 6 [3 minutes]:
Fix the program: linked here

You can fix the bugs and add functions or change operators to get it to work.

Hint: the final result should be an integer greater than 0!.




Display: AKA Output (to the console)

We've been working with the print function in order to get something displayed on the console.

Let's see a couple variations on its use:
We will implement these in this template.

You'll see the following output in the console:

Activity 7 [3 minutes]:
  1. Let's first modify the print statement in line 2 so that it does NOT append a newline after the text.
    To do this, modify it like this: \( \texttt{ print("The square of the number is: ", end=" ") } \)
    It should look like this:


  2. Now, let's print more than one thing in a single print; to do this, we can separate entries using a comma;
    Python will automatically separate entries with a space; in the example, comment lines 2 and 3 (you can select both and then press "command+/" (mac) or "Ctrl+/" (PC) );
    then and add the follwing line: \( \texttt{print("The square of ", num, " is: ", num**2)} \)

  3. We can add newlines manually by using a special sequence of symbols: \( \texttt{ \n} \);
    Try Adding a new print stament that looks like this: \( \texttt{print("This line \n And this one, are in the same print ", end=" ")} \)
    Do you notice something odd about the last line? can you explain it?

We'll talk more about these types of sequences next class.




Homework

[Due for everyone] Friday, 02/04 5PM: Homework 01 (Published in Replit).

[Optional]
Read Chapter 2 of Think Python
play around with the input, int, float, and eval functions (using the base code linked above).
This will give you some advantage in the assignment to come.