#!/usr/bin/python """ basics.py -- examples of some of the simplest language constructs Jeff Ondich, 24 October 2006 Read through the code and predict its output. Keep an eye out for weird stuff (e.g. "what is that // operator for?"). Also, there's one line that crashes this program--read the resulting error message, fix the program, and move on. """ print '=============== Arithmetic ==============' a = 7 b = 3 c = 3.0 print 'a =', a print 'b =', b print 'c =', c print 'a + b =', a + b print 'a * b =', a * b print 'a / b =', a / b print 'a / c =', a / c print 'float(a) / float(b) =', float(a) / float(b) print 'float(a) // float(b) =', float(a) // float(b) print 'a % b =', a % b print print '=============== Literal strings ==============' print 'this string is surrounded by single quotes and has "double quotes" in it' print "this string is surrounded by double quotes, and won't squawk at an apostrophe" print 'this string includes some\n\nnewline characters' print print '=============== Formatted strings ==============' number = 23 animal = 'goat' print 'this string has an interpolated integer (%d)' % number print 'this string has an interpolated string (%s)' % animal print 'this string has both (%d and %s)' % (number, animal) print 'format specifiers (%d, %s, etc.) are like printf in C' print 'e.g. %%.2f restricts a float to two decimal places: %.2f' % (7.0/3.0) print print '(when should you use %% when you mean %, and when will % do the job?)' print print '=============== Simple input ==============' name = raw_input('Who are you? ') print 'Hi', name, '. Nice to meet you.' print a = raw_input('Number, please: ') print 'This next output line is going to crash. Why? How can you fix it?' print a, 'squared = ', a*a print print '=============== if-elif-else ==============' animal = raw_input('Animal, please: ') if animal == 'goat': print 'billy or nanny?' elif animal == 'octopus': print 'the plural is octopi' print 'but octopuses is becoming more accepted' print '(did you notice that indentation is relevant in Python, and braces are absent?)' else: print 'I like %ss' % animal print "(don't forget the colon after the else)" print '(why did I use double quotes on that last string?)' print print '=============== while loops ==============' n = 10 while n > 0: print n n = n - 1 print 'Note the absence of the -- and ++ operators!' print print '=============== boolean operators ==============' n = int(raw_input('Number, please: ')) if n < -1000 or n > 1000: print "That's a large-magnitude number" elif n >= 0 and n < 700: print 'Positive, but not huge' elif not (n == 729): print 'Boring number' else: print 'I like 729'