Python Quick Points About Python Python is an
Python
Quick Points About Python • Python is an interpreted language – Like Perl you don’t have to compile it – It has a command line interpreter if you want to try things out • Python is free – You can download it from: – www. python. org
No semicolons • A new line terminates a statement – No semicolons are needed • If you need to continue a long line, you can use a slash character at the end print "Hello World" a = "Now is the time for all good men" + "to come to the aid of their country" print a
Comments • Comments are denoted with a # • Comments can also be written as strings that are not used # this is a comment """ Now is the time to comment this line is a comment too bla bla """
Indention Matters • A block of code has all the lines indented the same number of spaces – That is the only way a block is indicated – No curly braces {} – A block of code ends when the indent level reverts to the level of an outer block
Example Block of Code i = 0 while i < 5 : print i i = i + 1 print "done"
Assigning to Variables • Variables can hold strings or numbers i = 5 print i i = "hello" print i • Mulitple variables can be assigned at once two, three = 2, 3 x, y = y, x # really swaps
• Python does NOT convert between strings and numbers automatically • You can use the built-in int() function a = 1 b = "2" c = a + int(b)
Strings • You can use single or double quotes State = "Maryland" State = 'TN‘ Sentence = """ This is a long sentence that finishes on the another line """
Indexing Strings >>> name 1 = "Tom" >>> name 2 = "Jones" >>> newname = name 1[0] + name 2[: 3] + "123" >>> print newname TJon 123 >>> print newname[-3] 1 >>> print newname[: 3] TJo
Lists and Tuples mylist = [ “hello”, 7, “green” ] mytuple = ( “hello”, 7, (“red”, 31) ) firstelement = mylist[0] lastelement = mylist[-1] subtuple = mytuple[1: 3] mylist[1] = “newlistvalue” mylist. append( 9 ) mylist. extend( [“new”, “entries”, 50] ) print “List has“, len(mylist), “elements” del mylist[2] del mylist[0: 1]
Dictionaries mydict[0] = “first” mydict[1] = “Second” mydict[“zero”] = “First” mydict[“one”] = “Second”
If c == 12: c=1 for element in mylist: print element
- Slides: 13