UNIVERSITY OF TECHNOLOGY SYDNEY FACULTY OF ENGINEERING AND IT Let's code with! DOCUMENTATION, MATERIAL, RESOURCES (version 2) For UTS FEIT Outreach and UTS Women in Engineering and IT Written by Albert Ong
Purpose FEIT Outreach and Women in Engineering have prioritized running engineering and IT events in high schools. Although Engineering activities have been largely successful in both student satisfaction and promoting collaboration between students, eisting IT activities have been poor in the latter. Activity Summary Let s code with Python teaches students about programming with the python language and introduces fundamental concepts in cryptography. It is targeted at high school students with little eperience in programming. Activity Layout This activity is epected to run for roughly 1 hour, and takes around 30 minutes to set up. It can be run in one of two ways, depending on the student skill level with computers: Option 1: Presentation + Eercise + Competition (Good for students with some programming background.) Duration (min) Task Description 25 Introduction to coding What is programming, and why it s important What is python? Datatypes, structures, operations. 5 Try Code Number guessing game Build eperience with the IDE 15 Cryptography Competition Problem solving race with programming using Caesar s cipher. First to decipher the code wins a prize. 3 Closure The power of IT, projects and future at UTS. Other resources to learn programming. TOTAL = 53 Minutes Option 2: Walkthrough + Competition (Good for students with little programming background, but good typing speed. This does rely on students being closer to the projector.) Duration (min) Task Description 40 Walkthrough to coding Guide through programming concepts, and do eamples in presentation slides 10 Cryptography Competition Problem solving race with programming using Caesar s cipher. First to decipher the code wins a prize. 3 Closure The power of IT, projects and future at UTS. Other resources to learn programming. TOTAL = 53 Minutes
Let's code with! Python is a general purpose programming language that uses coding synta which makes it easy to read. Today, we re going to show you two very important areas in IT, programming, and cryptography (the science of writing secret codes). 1. Get an IDE (coding environment) Either: Open http://repl.it/languages/python, or Open IEP v3.4 You should see two sections on the screen: Write code on left Click play to run code Program output on right 2. Let s try coding (It may take a minute to load the random library.) import random guesses_made = 0 number = random.randint(1, 20) name = raw_input('hello! What is your name?\n') print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name) while guesses_made < 6: guess = int(raw_input('take a guess: ')) guesses_made += 1 if guess < number: print 'Your guess is too low.' if guess > number: print 'Your guess is too high.' if guess == number: break if guess == number: print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made) else: print 'Nope. The number I was thinking of was {0}'.format(number)
3. Cracking Caesar s Cipher! (Work in pairs) The Caesar Cipher was one of the earliest cryptography ciphers ever invented. It s a substitution cipher that works by shifting the alphabet a specific number of letters and replaces each character. Crack this code: CDIWXCV XH IGJT TKTGNIWXCV XH ETGBXIITS Decoding steps (a brute-force cipher): 1. *Optional* Get encoded string (encoded message) from user, 2. Convert the string into an array of ASCII integers, 3. Add a number (between 0 to 25) to each ASCII number. (In order to keep the characters in the capital letter range, if the ASCII number eceeds 90, subtract 26 (so Z becomes A ), 4. Reconvert ASCII numbers back into a string. Print the string. Repeat with a different integer. ASCII Table (ASCII is shaded grey): 32 (space) 42 * 52 4 62 > 72 H 82 R 92 \ 102 f 112 p 122 z 33! 43 + 53 5 63? 73 I 83 S 93 ] 103 g 113 q 123 { 34 " 44, 54 6 64 @ 74 J 84 T 94 ^ 104 h 114 r 124 35 # 45-55 7 65 A 75 K 85 U 95 _ 105 i 115 s 125 } 36 $ 46. 56 8 66 B 76 L 86 V 96 ` 106 j 116 t 126 ~ 37 % 47 / 57 9 67 C 77 M 87 W 97 a 107 k 117 u 38 & 48 0 58 : 68 D 78 N 88 X 98 b 108 l 118 v 39 ' 49 1 59 ; 69 E 79 O 89 Y 99 c 109 m 119 w 40 ( 50 2 60 < 70 F 80 P 90 Z 100 d 110 n 120 41 ) 51 3 61 = 71 G 81 Q 91 [ 101 e 111 o 121 y
Python Reference (from http://cscircles.cemc.uwaterloo.ca/cheatsheet/): 3 * 4, 3 + 4, 3-4, 3 / 4 #==> 12, 7, -1, 0.75 3 ** 4, 3 // 4, 3 % 4 #==> 81, 0, 3 4 > 3, 4 >= 3, 3 == 3.0, 3!= 4, 3 <= 4 #==> True, True, True, True, True # order of operations: brackets, **, {* / // %}, {+ -}, {==!= <= < > >=} min(3, 4), ma(3, 4), abs(-10) #==> 3, 4, 10 sum([1, 2, 3]) # [1, 2, 3] is a list #==> 6 type(3), type(3.0), type("myvariable") int("4"+"0"), float(3), str(1 / 2) "double quotes: ', escaped \" \\ \'" 'it\'s "similar" in single quotes ' #==> class 'int', class 'float', # class 'str' #==> 40, 3.0, '0.5' #==> double quotes: ', escaped " \ ' #==> it's "similar" in single quotes ord("a"), chr(66) #==> 65, 'B' string = "hello" # the following statements work for lists too len(string) #==> 5 string[0], string[4] # get characters #==> "h", "o" string[1:3] # get a substring #==> "el" string[:2], string[2:] # l/r substrings #==> "he", "llo" string[-1], string[-2:] # negative indices#==> "o", "lo" "con" + "cat" + "enation " + str(123) #==> "concatenation 123" "boo" * 2 #==> "booboo" getlineofinputasstring = input() #==> read input (or EOF error) print("takes", 0, "or more arguments") #==> takes 0 or more arguments print("using", "custom", "sep", sep=".") #==> using.custom.sep print("no", "newline", end="bye") #==> no newlinebye not True, False or True, False and True #==> False, True, False # order of operations: brackets, {==!=}, not, and, or if booleancondition: elif anothercondition: else: while booleancondition: break continue # indent the body block # every line by the same amount # can do zero, one, or several elif blocks # multi-line block # optional # multi-line block # the body block # jump out (optional) # restart from top of net iteration (optional) for indevariable in range(low, highplus): print(indevariable) #==> low, low+1,..., highplus-1 # "for item in listorstring:" forall/foreach loops # break, continue can be used in for loops def nameofnewfunction(argument1, argument2): # the body block return y # (optional; if you don't return, it returns None) def remember(bar): # writing to global variables global savebar # after calling foo(3), savebar = 3 savebar = bar # even outside of the function's scope (CONTINUED ON NEXT PAGE)
# these 'slice' commands have analogues for lists and range() "0123456789"[::2] # slices #==> "02468" "0123456789"[::-1] # descending #==> "9876543210" "0123456789"[6:3:-1] #==> "654" += 1 # also -=, /=, *=, %=, **=, //=. Python has no C++-style "++", y = y, # multiple assignment 3 < < 5 # same as "(3 < ) and ( < 5)". can chain {< <= > >= ==!= is} import math # import, to get everything with period print(math.sqrt(2)) from math import sqrt # import, to get one thing without period print(sqrt(2)) # also in math module: pi, ep, log, sin, cos, tan, ceil, floor, and more list = ['zero', 'one', 'two'] list.inde('one') #==> 1 list.inde('three') #==> causes an error 'three' in list, 'zero' in list #==> False, True list.count('two') #==> 1 del list[1] # list becomes ['zero', 'two'] "string" in "superstring" #==> True "superstring".inde("string") #==> 5 # more list methods: append(item), insert(item, inde), etend(list), # remove(value), pop(), pop(inde), reverse(), sort(), and more # some string methods: capitalize(), lower/upper(), islower/isupper(), # isalpha/isdigit(), center/ljust/rjust(width, fillchar), strip(), split(), # splitlines(), endswith/startswith(string), find(string), replace(old, new), # and more mylist = [11, 99] actuallythesamelist = mylist # not a true copy! just copies the reference mylist is actuallythesamelist #==> True realcopy = mylist[:] # or list(mylist), copy.copy(mylist), deepcopy realcopy is mylist #==> False There are a bunch of resources available for learning software development and IT: codeavengers.com Learnpython.org csedweek.org/learn codeacademy.com groklearning.com/hoc ed.org hello.processing.org robomindacademy.com dreamspark.com code.org