Sunteți pe pagina 1din 4

CSC220 Data Structures Fall 2014

Python I - Introduction
If you're mostly familiar with so-called curly-brace languages, Python might seem a little different at first, but actually it has
quite a bit in common with those languages. Most of the constructs you learned for those languages have analogs in
Python.
Remember, we don't have to become Python experts right off the bat. We'll start out with the basics and add things as the
class progresses. This lecture in the next are intended to just get everyone enough background information so we can start
programming with Python.

The Interpreter
Python comes with an interpreter. If you execute the command python at the command line (or in Windows go to the start
menu and launch the Python (Command Line)), you'll end up with the Python interpreter. It should look something like:

Python 3.5.2 (v3.5.2 : 4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>>

(What it says exactly will depend on which version you installed and what OS you have. You can usually ignore
that information). The Python interpreter interprets Python statements.

Calculator

You can directly enter arithematical statements:

>>> 4 + 5 # addition ('#' starts a comment, similar to '//' in Java and C++)
9
>>> 3 * 1.5 # multiplication
4.5
>>> 5 - 10 # subtraction
-5
>>> 1 // 7 # integer-division
0
>>> 1 / 7 # floating point divison
0.14285714285714285
>>> 2 ** 4 # raising to a power
16

Note that one of Python's peculiarities is that white-space is siginficant. If you happen to insert a space or a tab before the
expression, the interpreter will get confused.

>>> 15 + 22 # an extra space before '15'

SyntaxError: unexpected indent


>>>

While this can sometimes be annoying, especially when first starting out with Python, it soon becomes second nature. We'll
see more about expected indentation when we cover loops and branches. On the plus side, notice how nice the error
message is compared to the typical C++ error. Python shows you exactly where the error occurs and the error message
gives a pretty good indication of what went wrong.

Variables and assignment

Python uses the same assignment operator as most other common languages:

>>> a = 4
>>>

Notice there's no output. To see the value of a variable, we can just type the variable name and hit enter, the interpreter will
evaluate the variable and return its value.

>>> a
4

Identifiers, or variable names, are case-sensitive, can be alphanumeric and contain underscores, but they can not start with
a numeral nor can they be one of the reserved words, such as 'if', 'while', etc. (For a full list of reserved words in Python, see
the Python documenation linked below.)

Have you noticed that we haven't had to specify any types? No int, float, double, char, long, etc. Python is a dynamically
typed language. That is, it figures out on the fly what type a variable should be. Most of the time it will do what you want it to,
however, as in the case of integer-division above, occaisionally you must be explicit.

Classes and objects

Python's main programming paradigm is Object-Oriented Programming. It's actually more so than Java or C++, that is,
everything in Python is an object. Even numbers, e.g.,

>>> a = 4 # this assignment is actually shorthand for calling a constructor


>>> b = int(5)
Instead of primitive datatypes like int, float, char in C, Python provides a few default classes, such as int, float, bool, str, etc.
For a full list, see the Python documentation linked below.

Sequence classes

Python provides some linear data structure classes collectively known as sequences: list, tuple, and str. list is similar
to a std::vector. A tuple is like a frozen list. str is a string or sequence of characters.

>>> mylist = [1, 3, 5, 7] # lists use '[' and ']'


>>> mylist
[1, 3, 5, 7]
>>> mylist = mylist + [9, 11] # can concatenate lists
>>> mylist
[1, 3, 5, 7, 9, 11]

And since lists are objects, you can also call the constructor directly.

>>> odds = list([1, 3, 5, 7]) # seems redundant


>>> letters = list('what?') # more interesting
>>> letters
['w', 'h', 'a', 't', '?']

Lists are mutable, that means changes you make to the list happen in-place.

>>> mylist[4] = 88 # Python uses 0-based indexing


>>> mylist
[1, 3, 5, 7, 88, 11]

Tuples, on the other hand, are immutable, which means you can't directly change them.

>>> mytuple = (2, 4, 6, 8) # tuples use '(' and ')' when creating
>>> mytuple
(2, 4, 6, 8)
>>> mytuple[2] # however use '[', ']' for element access
6
>>> mytuple[2] = 5 # try this, see if the error message makes sense

Strings are also immutable sequences. They can be inclosed in single or double quotes. This way you can do things like:

>>> motto = "Don't worry" # don't have to worry about escaping single quote

Sequences can be sliced and can use reverse indexing, which can really be convenient. Slices are subsets of the sequence.

>>> mylist[0:2] # similar to for(i = 0; i < 2; i++)


[1, 3]
>>> mylist[:3] # implied starting from zero
[1, 3, 5]
>>> mylist[3:5] # don't have to start at zero
[7, 8]
>>> mylist[4:] # walk to the end
[8, 11]
>>> mylist[:] # Try this
>>> mylist[:5:2] # third number is step, like loop with i+=2
[1, 5, 8]
>>> mylist[-1] # access from the other side
11
These element accesses will also work on tuples and strs, try them out.

Conditionals

Python has the standard if-then-else control flow of other languages. This will be the first instance where we see where
Python expects white-space. Note that in Python interpreter when we start a multi-line section of code the '>>>' will change to
'...' &endash; this is a visual cue that it's expecting more code input before it tries to evaluate.

>>> a = 5
>>> if a > 6: # Not required to place condition in parentheses, must end line with colon
... a = a + 2 # be sure to insert a TAB character
... else: # else is at same indentation level as if
... a = a - 3
... # enter a blank line to finish
>>> a
2

In languages like Java, C, C++, JavaScript, etc., blocks are indicated by being enclosed in curly-braces. In Python, blocks
are indicated by being on the same level of indentation. This can be annoying at first, but is surprisingly easy to get used
to.

Python indicates else-if with elif.

>>> color = 'red'


>>> if color == 'blue':
... what = 'sky'
... elif color == 'green':
... what = 'grass'
... elif color == 'red':
... what = 'balloon'
... else:
... what = 'nothing'
...
>>> what
'balloon'

Looping

Loops in Python are pretty much like loops in other languages. Theres are while loop and for loop. Just like conditional
branching, the loop statement must end with a colon and the loop body must be indented.
>>> i = 0
>>> while i < 10:
... print i
... i += 1 # don't forget to increment i!
...

For loops are more like Java's for-each loops than C for loops. They're very handy for iterating over sequences.

>>> for val in mylist: # val is an iterator for the list


... if val % 2 == 0: # mod operator
... print val # second level of indentation required
...

(Okay, those aren't very exciting...)

Functions

The last thing we'll cover here are functions. Function definitions in Python are a lot cleaner than other languages
because we don't have to specify any parameter or return types.
>>> input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> def odds(data): # all functions are defined with 'def'
... output = [] # create an empty list to hold output
... for item in data:
... if item % 2 == 1:
... output += [item] # see below note
... return output
...
>>> odds(input)
[1, 3, 5, 7, 9]

You can only concatenate a list with another list. 'item' in this case happens to be an integer element of input. To turn it into
a list we can simply enclose it in brackets and the list constructor will be called.
Lastly
If it seems like I left a lot out, that's because I did. Python is huge. Any modern language, once you add in all of the
supporting libraries is, you must get used to using the documentation.

Documentation and other links


Python homepage with tons of information
Official beginner's guide
Official Python 2 tutorial
Official beginner's guide for non-programmers

Editing
Normally, you probably won't do much editing in the python interpreter itself. You have many options for editing python code.
All I will ever want from you is the Python source code, so use the one that you're most comfortable with. Some options are:
A text editor such as vim, emacs, gedit, jot, etc.
IDLE, which comes with Python
An IDE (such as eclipse)

Here's a introduction to using the basic IDE that comes with python, IDLE.

I save my file as "somefile.py" and then run it from IDLE.

input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def odds(data):
# the following is a documentation string, it starts and ends with
# triple single- or double-quotes.
"""Given a list, returns a list of any odd
numbers contained within"""
output = list()
for item in data:
if item % 2 == 1:
output += [item]
return output
# scripts won't automatically print results, unlike the interpreter
print( odds(input) )

Parkland College | CSIT

S-ar putea să vă placă și