WEEK01: intro to python, unix, cs21
-----------------------------------
W: data types, functions, variables, input/output
Announcements:
- Lab 0 (due this Saturday)
- everyone should be able to log in and run update21
- ninja session tonight (our Ninjas = Mallory, Alexis)
- need to know vim for Friday's class
Things I forgot last time:
- my office is 238A (other end of the CS hall)
- you can also use the main lab (240) and the overflow lab (238)
- we are using piazza for this class
PYTHON SHELL vs UNIX SHELL:
$ <-- unix prompt
>>> <-- python prompt
- today we will type python code in the interactive python shell
- on Friday we will type python code into a file (using vim), then run the file
DATA TYPES: string, integer, floating point (decimal)
- what they are:
strings: "hello" "jeff" "This is FUN!!"
integers: 5 360 -21
floating point numbers: 3.14159 -6.2 800.0
- things you can do with them (+, -, *, etc)
Functions: grouping of code with a name; allows modularity, code reuse
- python has lots of built-in functions
- call a function by giving name and parens
- may or may not need to supply values to the function (inside the parens)
- simple python functions:
type('hello')
int(5.0)
int('5')
float(5)
str(5)
int(3.141)
raw_input()
- many functions return something to the caller (see raw_input() below)
- we can create our own function with def:
def hello(name):
print "Hello, " + name
VARIABLES: place to store a value, also give it a name
- rules for names: no spaces, no odd characters, can't start with number
- why do we use them?
- examples:
x = 5
y = "hello"
name = "Jeff Knerr"
z = 3.141 * x
- the equals sign here is the ASSIGNMENT operator
RAWINPUT
- raw_input(string)
- displays string to terminal, waits for user input
- returns what the user typed as a string
- usually you want to assign what it returns to a variable
name = raw_input("please enter your name: ")
PRINTING/OUTPUT:
- convert everything to a string and use + operator
name = "Jeff"
age = 29
print name + " is " + str(age) + " years old"
SAMPLE PROGRAM:
- ask user for age in years
- convert to days, display the result
stryears = raw_input("Age? ")
years = float(stryears)
days = years * 365
print "That's " + str(days) + " days!"
YOUR TURN: write a program to do this...
- given a yearly salary, estimate the monthly take-home pay
- assume the government takes 30% for taxes
$ python takehomepay.py
Salary: 12000
Approx monthly take-home-pay = $700.0
- think first!!! (don't just start typing)
- write it out on paper first!! (don't just start typing)
- say hello to your neighbor first!! (don't just start typing)
- talk it over with your neighbor first!! (don't just start typing)
IF YOU HAVE TIME:
- what happens when you enter nonsense values for your
salary (ex: enter "hello" for the salary)
- try using vim to enter your program in a takehomepay.py file
IF YOU DON'T HAVE TIME:
- don't worry! I will make these programs available via update21