Lecture 3

Variables, assignments, input

MCS 260 Fall 2020
David Dumas

Reminders

  • Complete worksheet 1 this week
    • Not collected; solution recently posted
  • Quiz 1 due Monday 6pm Central
    • Contact staff about install problems
    • Can request to be excused once per calendar month by writing to TA (see syllabus)
    • Upload separate images or single PDF with BIG screenshot

Comments

In a line of Python code, anything appearing after a $\texttt{#}$ character is ignored by the interpreter.

        print("Hello world!")   # TODO: Choose a new greeting
    

The ignored text is a comment.

Comments should be added where they will make code easier to understand (for others, or for you in the future). They can also be reminders about known problems or future plans, if these are not recorded systematically elsewhere.

Variables and assignments

Variables allow you to give names to values, and to later change the value associated with a name. We do so with assignment statements. The basic syntax is

$\texttt{name} = \texttt{value}$

Example:

>>> side_length = 5
>>> side_length
5
>>> side_length**2
25
>>> side_length = 6
>>> side_length**2
36
A common mistake for beginners is to put quotation marks around variable names, or to omit them when a string is needed.

"foo" = 50    # FAILS: can't assign to string
foo = 50      # Works
foo = thing   # FAILS: thing is seen as variable name
foo = "thing" # Works
bar = "foo"   # Works, bar is now "foo"
bar = foo     # Works, bar is now "thing"

print(Hello world) # FAILS: Hello and world are unknown names
                   # and space between var names not allowed

How to think about assignment

The code

        x = 15
    
asks Python to remember three things:
  • the value 15
  • the name $x$ (i.e. create a new name if needed)
  • that $x$ currently refers to 15

A diagram is often used to summarize this situation:

$ \boxed{x} \longrightarrow \boxed{15} $

The right hand side of an assignment can be an expression combining variables, literals, function calls, and operators. These are evaluated before assignment.

>>> old_semester_tuition = 4763
>>> semester_tuition = old_semester_tuition * (1 + 11.1/100)
>>> semester_tuition
5291.693
Spaces around $\texttt{=}$ are optional.

Variable name prohibitions:

  • Must not start with a number
  • Must not contain spaces
  • Must not be a Python keyword ($\texttt{if}$, $\texttt{while}$, $\ldots$)
The Python 3.8 keywords are:

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    
Variable name recommendations:
  • Use only $\texttt{A}$-$\texttt{Z}$, $\texttt{a}$-$\texttt{z}$, $\texttt{0}$-$\texttt{9}$, and $\texttt{_}$ (underscore)
  • Use $\texttt{_}$ as a word separator

    class_avg = 93.8    # Works
    260avg = 93.8       # FAILS: starts with a number
    secret code = 12345 # FAILS: spaces prohibited
    secret_code = 12345 # Works
    SecretCode = 12345  # Works, atypical style
    测试成绩 = "great"    # Works, not recommended

(The exact rules are complicated and refer to a number of other documents and standards. Ultimately, there are about 120,000 characters allowed.)

Input

The $\texttt{input}()$ function waits for the user to type a line of text in the terminal, optionally showing a prompt.

It then returns the text that was read, meaning that the code behaves as though that instance of $\texttt{input()}$ has been replaced by the string the user typed.


>>> s = input("Enter some text: ")
Enter some text: organizing heliotrope
>>> print("You entered:",s)
Your entered: organizing heliotrope
>>> input()
programming exercises
'programming exercises'
>>>

Greeting the user

The script greeting.py will greet you by name.


# Greet the user by name
# MCS 260 Fall 2020 Lecture 3 - David Dumas
name = input("Enter your name: ")
print("Nice to meet you,", name)

Usage:


$ python greeting.py
Enter your name: David Dumas
Nice to meet you, David Dumas
$ 

Arithmetic on input?

We can't do arithmetic on input directly, because the input is always a string.


>>> 5 + input("Enter a number: ")
Enter a number: 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Instead we need to convert input to a numeric type, using $\texttt{int()}$, $\texttt{float()}$ or $\texttt{complex()}$.


>>> 5 + int(input("Enter a number: "))
Input: 10
15
The conversion functions $\texttt{int()}$, $\texttt{float()}$, $\texttt{complex()}$ can convert from strings to numeric types, and between numeric types, e.g.

>>> float(42)
42.0
>>> int(12.9)
12

Supported conversions:

input type → str int float complex
int() integer part
float()
complex() picky
What "picky" means: $\texttt{complex()}$ requires the format $x+y\texttt{j}$ or $\texttt{(}x+y\texttt{j}\texttt{)}$.

complex("1+2j")   # Works
complex("(1+2j)") # Works
complex("2j+1")  # Fails

Warning: Conversion from int to float or int to complex may be destructive; ints are exact, but float and complex may replace input with an approximation.


>>> float(9_007_199_254_740_992)
9007199254740992.0
>>> float(9_007_199_254_740_993)
9007199254740992.0
    

Sum and product script

Here is a script sumprod.py that reads two floats from the user and prints their sum and product.


# Read two floats and print their sum and product
# MCS 260 Fall 2020 Lecture 3 - David Dumas
x = float(input("First number: "))
y = float(input("Second number: "))
print("Sum:    ",x,"+",y,"=",x+y)
print("Product:",x,"*",y,"=",x*y)

Usage:


$ python sumprod.py
First number: 1.2
Second number: -3.45
Sum:     1.2 + -3.45 = -2.25
Product: 1.2 * -3.45 = -4.14

References

Acknowledgements

  • Some of today's lecture was based on teaching materials developed for MCS 260 by Jan Verschelde.

Revision history

  • 2020-08-28 Code formatting correction
  • 2020-08-27 Initial publication