Self-paced introduction, part 2
Goals
- Run python scripts from a file
- Meet the Boolean data type
- Use flow control (if/elif/else)
- Write your first functions
Steps
Python scripts
python nobel.py
Booleans
Truetype(True)Falsetype(False)0 == 00 == 1"a" != "a""a" != "A"1 > 02 >= 3-1 < 0.5 <= 1"H" in "Hello""h" in "Hello""X" in "Hello"Programmer joke here. Perl is a programming language that was hugely popular in the 1990s, and there's still a ton of perl code being written, including in libraryland. It's very different stylistically from Python, though. As many people who've programmed in more than one language have strong favorites (and unfavorites), some Pythonistas might be known to diss Perl. We here take no position on the merits of different languages. Except that Python is awesome."a" not in "abcde""Perl" not in "ALA Python Preconference"
Flow control
if
statementsif 6 > 5: print "Six is greater than five!">>> if 6 > 5: ... print "Six is greater than five!" ... Six is greater than five!if 0 > 2: print "Zero is greater than two!"if "banana" in "bananarama": print "I miss the 80s."More choices:
if
andelse
sister_age = 15 brother_age = 12 if sister_age > brother_age: print "sister is older" else: print "brother is older"compound conditionals:
and
andor
1 > 0 and 1 < 21 < 2 and "x" in "abc""a" in "hello" or "e" in "hello"1 <= 0 or "a" not in "abc"temperature = 32 if temperature > 60 and temperature < 75: print "It's nice and cozy in here!" else: print "Too extreme for me."hour = 11 if hour < 7 or hour > 23: print "Go away!" print "I'm sleeping!" else: print "Welcome to the yarn shop!" print "Can I interest you in some nice merino?"even more choices:
elif
temperature = 32 if temperature > 60 and temperature < 75: print "It's nice and cozy in here!" elif temperature > 75: print "Too extreme for me." else: print "Brrr! Fetch me my cardigan."color = "orange" if color == "green" or color == "red": print "Christmas color!" elif color == "black" or color == "orange": print "Halloween color!" elif color == "pink": print "Valentine's Day color!"In summary: the structure of
if
/elif
/else
Writing functions
length = len("Mississippi")Step 1: Write a function signature
Step 2: do useful work inside the function
def add(x, y): result = x + yStep 3: return something
def add(x, y): result = x + y return resultdef add(x, y): return x + ydef absoluteValue(number): if number < 0: return number * -1 return numberdef absoluteValue(number): if number < 0: return number * -1 else: return numberStep 4: use the function
def add(x, y): return x + y result = add(1234, 5678) print result result = add(-1.5, .5) print resultWhat is the difference between print and return?
def add(x, y): print x + ydef add(x, y): return x + yresult = add(5, 6) print result
End of part 2
Next Step:
On to Checkoff
Back to Self-paced introduction, part 1