Today's Topics

Designing a full program

Suppose we are given the following problem: Have the user enter the current year as a number and the year he or she plans to graduate and print how many more college years he/she has left. We want to design an algorithm that can solve this problem (this one is a bit easy) and then implement and test our solution in python.

Here are some steps a computer scientist might use to solve the problem:

  1. First think about how you would solve the problem. no keyboards, mice, or even writing utensils. Just think.
  2. Write or sketch a solution on paper. Discuss you solution with a friend or neighbor. This solution does not have to be in python. pseudocode is fine.
  3. Write your solution in python using your editor (atom).
  4. save, run, and test your solution. Go back and make changes if needed
cd cs21/inclass/w01-intro
atom ./
Enter the current year: 2019
Enter your graduation year: 2022
You have 3 year(s) until graduation

When you do write python code, it's good practice to comment. You've seen large Python comment blocks enclosed in triple-quotes. You can also provide a single-line of comment by using the # symbol.

Programming Style

You will soon see in Python and other programming languages how to combine simple statements to create complex powerful code. This takes practice and experience. For example, consider the following snippet of code from last week:

# store user input in yearText as a string
yearText = input("Enter the current year: ")
# convert user input to int, save in year
year = int(yearText)

The first line calls input to ask the user of your program (i.e., the person who is running the python program you wrote) for a number. This gets returned by the input function as a string and stored in yearText. input always returns a string, even if it is supposed to represent a number. The second line converts the string value contained in yearText, converts it to an int, and saves the value in a variable called year.

It's possible to combine the code into a single line of python code

get int from user, store in num
don't forget to convert from str to int
year = int(input("Enter the current year: "))

Both snippets of code are legal Python. Which is better or preferable is a matter of taste. Our general advice to use the former style until you're very comfortable with Python syntax. Beginning students tend to over-complicate code, which makes code harder to read and more likely to have errors. Try to keep your code simple.

Python math operators

Mathematical calculations are one of the most common uses of computer programming. Below is a quick summary of python3 math syntax and semantics. I encourage you to try examples in the python interpreter and ask questions about strange cases.

You can also combine many operators in one statement e.g. 2*x+10, but note you must explicitly include the * to multiply. The algebra form 2x+3 is a syntax error.

Quick practice

Take a minute or two, open up a python interpreter window, and play around with math operators. Do they do anything unexpected? Try to combine them in larger expressions. What happens?

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 5+2
>>> 5-2
>>> 5*2
>>> 5/2
>>> 5//2
>>> 2**5
>>> 2**32
>>> 19/5
>>> 19//5
>>> 19%5
>>> 3*5 + 4
>>> quit()

String Operators

Some math operators can be used with strings:

>>> hw = "hello" + "world!"
>>> print(hw)

Some other math operators can also be used with strings, but in somewhat more complicated ways. We will explore these operators a little later in the semester. Stay tuned!

Expressions, operator precedence

An expression is a combination of values, variables, operators, outputs of Python commands like int or input, and even other expressions! The evaluation of an expression produces a value. e.g. the evaluation of 2*19+3 is 41. This is why expressions can appear on the right-hand side of assignment statements. Large mathematical expressions are common in Python.

Order of Operations

When more than one operator appears in an expression, which gets executed first depends on the rules of precedence. Python follows the following rules

  1. Parentheses have the highest precedence and can be used to force the expression to evaluate in the order you want. Since expressions are evaluated first, 2*(3-1) is 4, and (5-2)**(2+2) is 81.
  2. Exponents have the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
  3. Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2//3-1 is -1, not 1 (remember that in integer division, 2//3=0).
  4. Operators with the same precedence are evaluated from left to right. So in the expression minute*100//60, the multiplication happens first. If minute=59, this would yield 5900//60, which in turn yields 98. If the operations had been evaluated from right to left, the result would have been 59*1, which is 59, which is wrong.

Remember to be specific with your Python code: 2x+3 is a SyntaxError. 2*x+3 multiplies x by 2 and then adds 3.

A good rule of thumb when using expressions with lots of operators is to keep things simple. Use parentheses rather than relying on operator precedence rules. Better yet, if you have large math expressions, divide your Python statement into multiple lines of code.

import math library

Python supports many other useful mathematical functions, but these are stored in separate library. A library is a separate collection of functionality not part of the main Python language.

Programming Exercise

With the remaining time, write a program to compute the area of a circle. First, ask the user for a radius. Then, print out the area using the formula A = πr2 (area = pi * r^2)

Extra challenge: write a program that computes the radius of a circle, given the area.

$ python3
Enter the radius of a circle: 3
The area of a circle of radius 3 equals: 28.274333882308138