COSC 2P91 Introduction to Python Week 7a Brock University Brock University (Week 7a) Introduction to Python 1 / 20
Python Pythoff. Python. Pythoff. Python is a somewhat more modern language than C. It isn’t quite as constrained by its past. It’s an interpreted language It’s dynamically typed It has basic support for object orientation, functional programming, etc. But, more often than not, it’s simply used as a basic procedural language. Brock University (Week 7a) Introduction to Python 2 / 20
Python Which Python? When using Python, you have more choices than you might guess There are different actual implementations of the language There are three major branches of Python: 2, 3, and 4 ◮ Python 4 isn’t really officially released yet, so no worries there ◮ sandcastle has 2.6.6, but what matters is that it isn’t 3 ◮ Quite a few things changed with Python 3 ⋆ Python 3 is... not backwards-compatible with Python 2 ⋆ A migration tool is recommended to transition Python 2 code to 3 ⋆ Would you feel like rewriting all of your code (especially for a larger system) just to make it more ‘pythonic’? ... yeah. Most companies feel the same way ⋆ Python 3 has a remarkably small market share, particularly on web backends ◮ For this course, we’ll be using Python 2 ⋆ Specifically, 2.6.6, but if you use a different version of Python 2 on your own computers, it isn’t likely to cause a problem Brock University (Week 7a) Introduction to Python 3 / 20
How to run Python code There are two basic ways to run the Python interpreter: ‘Normal’ mode ◮ You have a python script ◮ You tell Python to run that script ◮ Python runs that script ◮ You rejoice in the having-run-script-ness Interactive mode ◮ If you run Python without specifying a script, you get an interactive interpreter ◮ Compare to the REPL for Lisp Obviously ‘real’ programs are run in scripts, but it’s often handy to just load up the interpreter for tinkering. Brock University (Week 7a) Introduction to Python 4 / 20
The Basics As mentioned, Python is a dynamic language. That means that values (returned from expressions) do have types, but variables can have arbitrary types assigned to them (and may be reassigned as necessary) ◮ (Or that variables are effectively directly bound to values, but let’s not get bogged down in semantics) Basically, we can just start using variables, and reusing them as necessary, without worrying about things like declarations and such. Brock University (Week 7a) Introduction to Python 5 / 20
The Basics Types Python has a somewhat simplified assortment of types. To match the Python philosophy, the emphasis is more on categories than specific representations. bool — booleans ( True or False ) int , and long , but no shorts or bytes float , but no doubles str — strings, but no separate character type The type function is your friend. (By the way, our null is called None ) Brock University (Week 7a) Introduction to Python 6 / 20
The Basics Strings Let’s take a closer look at strings. When you want a reminder on what you can do with a type, you can use python’s help function. A string can be defined via single-quotes (apostrophes), double-quotes, or a set of three quotes. Though legal, this isn’t really the most common way to define strings Triple-quoted strings do have the advantage of being able to be used across multiple lines ◮ For this reason, they’re sometimes used as a multi-line comment ◮ Be careful doing this, because it’s normally for a specific purpose Brock University (Week 7a) Introduction to Python 7 / 20
The Basics Slices Besides the built-in functions, we can take slices of strings. Slices are just python’s version of substrings, except they’ll also apply to lists (more on that in just a moment) After a string (or a variable containing a string), use a single number in square brackets to retrieve the corresponding character (with zero-based indexing) Use two numbers (separated by a colon) to indicate the starting (inclusive) and ending (exclusive) indices for the slice Include a single number and a colon for either “everything after this index” or “everything up to this index” You can also use negative index values, but... please don’t Try using no numbers (but still a colon). What happened? Even when accessing a single character, a slice of a string is still a string. Brock University (Week 7a) Introduction to Python 8 / 20
The Basics String operations An obvious string operation is concatenation. For the most part, it’s simply in Python. The + sign is used for concatenation ◮ The only thing to really look out for is that it expects strings for both operands ⋆ Consider the implications of this ⋆ Explicit conversion may be necessary at times We also have in , which is handy Brock University (Week 7a) Introduction to Python 9 / 20
The Basics Lists Very closely related to strings are lists. Python lists are our primary data structure to take the place of both arrays and linked lists in other languages Indexing is handled the same way as with strings ◮ Perhaps we should look at lists of lists for a moment? It’s worth noting that lists do not have to be of a homogeneous type. We’ll be revisiting lists eventually, once we have something to actually do with them. Brock University (Week 7a) Introduction to Python 10 / 20
The Basics Tuples Tuples are very similar in concept (and usage) to lists, with a few distinctions: They’re defined via parentheses instead of square brackets They’re immutable They can be hashed Tuples are particularly good for return-values from functions, and to help with dictionaries. The list function creates a list from a tuple; the tuple function creates a tuple from a list. Brock University (Week 7a) Introduction to Python 11 / 20
The Basics Dictionaries Python dictionaries are closely related to PHP’s associative arrays or Java’s hashmaps. Each entry has both a key and a value The key must be hashable (integers, floats, strings, tuples, and some sets) Dictionaries are defined via curly braces If the components of entries are to come from multiple lists, the zip function may be useful for matching them up. Brock University (Week 7a) Introduction to Python 12 / 20
Operators Assignment is done via = < , > — less-than, greater-than == is used to test values for equality is tests identity (whether or not two references are the same object ◮ Compare [1,2]==[1,2] vs [1,2] is [1,2] not , and , or — not, and, and or, respectively Use ∗∗ for exponents Brock University (Week 7a) Introduction to Python 13 / 20
Simple input and output Basic text IO is pretty simple: Use print to print ◮ You can write it as a function, or treat it like a prefix operator ◮ print assumes one-line-per-print. Append a comma if you don’t want that Do not use the input function in python 2! ◮ Use raw input instead! Brock University (Week 7a) Introduction to Python 14 / 20
Code blocks Of course, we’re going to need to be able to define blocks of code for several reasons — conditionals, loops, functions, etc. Instead of using curly braces (like in C/Java/etc.), python uses whitespace . The level of indentation indicates the block level So, you know, be careful with your indentation? For conditionals, Python uses if , else , and elif . while loops are as expected (except for not requiring parentheses for the conditional expression). When you don’t want to enter a block of code, you can use pass . Use continue to jump to the beginning of the next iteration. Use break to break. Brock University (Week 7a) Introduction to Python 15 / 20
For loops For loops are somewhat special in Python. Treat Python as effectively only having for-each loops (or loops over iterables) e.g. for i in range(0,10): The range function can also receive a third argument, for step size Neat tidbit: both while and for loops can have else blocks! They’re used to run code only if the loop terminated normally — i.e. not from a break Brock University (Week 7a) Introduction to Python 16 / 20
Functions Because we aren’t explicitly declaring types in general, functions also aren’t declared with types. e.g.: def doStuff(): print ’hi’, print ’class!’ return 2,3 Of course, for a dynamic language like Python, function pointers are now trivial. e.g.: dealie=doStuff dealie() We might get into lambda expressions and closures later. Brock University (Week 7a) Introduction to Python 17 / 20
Code blocks One last thought You can define blocks within blocks where appropriate. You can define a function within a function if you wish ◮ Do we want to look at an example? Brock University (Week 7a) Introduction to Python 18 / 20
Next time! Next lecture, we’ll actually look at writing scripts and executing them Brock University (Week 7a) Introduction to Python 19 / 20
Questions? Comments? Favourite videogame soundtrack? Brock University (Week 7a) Introduction to Python 20 / 20
Recommend
More recommend