0% found this document useful (0 votes)
120 views41 pages

Lecture1 Cis4930

Python was developed in the 1980s and has grown in popularity in recent decades. It is an interpreted, high-level programming language that supports multiple programming paradigms including object-oriented, functional, and procedural. Python has a comprehensive standard library and is useful for a wide variety of applications. The Zen of Python outlines principles like readable, explicit, and sparse code. Python code is run through an interpreter which can operate in normal or interactive mode.

Uploaded by

Jeetendra Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views41 pages

Lecture1 Cis4930

Python was developed in the 1980s and has grown in popularity in recent decades. It is an interpreted, high-level programming language that supports multiple programming paradigms including object-oriented, functional, and procedural. Python has a comprehensive standard library and is useful for a wide variety of applications. The Zen of Python outlines principles like readable, explicit, and sparse code. Python code is run through an interpreter which can operate in normal or interactive mode.

Uploaded by

Jeetendra Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

LECTURE 1 Getting Started with

Python
ABOUT PYTHON
• Development started in the 1980’s by Guido van Rossum.
• Only became popular in the last decade or so.

• Python 2.x currently dominates, but Python 3.x is the future of


Python.
• Interpreted, very-high-level programming language.
• Supports a multitude of programming paradigms.
• OOP, functional, procedural, logic, structured, etc.

• General purpose.
• Very comprehensive standard library includes numeric modules, crypto services,
OS interfaces, networking modules, GUI support, development tools, etc.
PHILOSOPHY
From The Zen of Python (https://www.python.org/dev/peps/pep-0020/)
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
NOTABLE FEATURES
• Easy to learn.
• Supports quick development.
• Cross-platform.
• Open Source.
• Extensible.
• Embeddable.
• Large standard library and active community.
• Useful for a wide variety of applications.
GETTING STARTED
Before we can begin, we need to actually install Python!

The first thing you should do is download and install our custom
guide to setting up a virtual machine and write your first Python
program.
We will be using an Ubuntu virtual machine in this course. All
instructions and examples will target this environment – this will
make your life much easier.
Do not put this off until your first assignment is due!
GETTING STARTED
• Choose and install an editor.
• For Linux, I prefer SublimeText.
• Windows users will likely use Idle by default.
• Options include vim, emacs, Notepad++, PyCharm, Eclipse, etc.

Throughout this course, I will be using SublimeText in an Ubuntu


environment for all of the demos.
INTERPRETER
• The standard implementation of Python is interpreted.
• You can find info on various implementations here.

• The interpreter translates Python code into bytecode, and this


bytecode is executed by the Python VM (similar to Java).
• Two modes: normal and interactive.
• Normal mode: entire .py files are provided to the interpreter.
• Interactive mode: read-eval-print loop (REPL) executes statements piecewise.
INTERPRETER: NORMAL
MODE
Let’s write our first Python program!
In our favorite editor, let’s create helloworld.py with the following
contents:
print "Hello, World!" Note: In Python 2.x, print is a statement. In
Python 3.x, it is a function. If you want to get
into the 3.x habit, include at the beginning:
from __future__ import print_function
From the terminal:
Now, you can write
$ python helloworld.py print(“Hello, World!”)
Hello, World!
INTERPRETER: NORMAL
MODE
Let’s include a she-bang in the beginning of helloworld.py:

#!/usr/bin/env python
print "Hello, World!"

Now, from the terminal:

$ ./helloworld.py
Hello, World!
INTERPRETER: INTERACTIVE
MODE $ python
>>> print "Hello, World!"
Let’s accomplish the Hello, World!
same task (and more) in >>> hellostring = "Hello, World!"
interactive mode. >>> hellostring
'Hello, World!'
>>> 2*5
10
Some options: >>> 2*hellostring
'Hello, World!Hello, World!'
-c : executes single >>> for i in range(0,3):
command. ...     print "Hello, World!"
-O: use basic ...
optimizations. Hello, World!
Hello, World!
-d: debugging info. Hello, World!
More can be found here. >>> exit()
$
SOME FUNDAMENTALS
• Whitespace is significant in Python. Where other languages may
use {} or (), Python uses indentation to denote code blocks.

# here’s a comment
• Comments for i in range(0,3):
print i
• Single-line comments denoted by #.
def myfunc():
• Multi-line comments begin and end with three “s. """here’s a comment about
• Typically, multi-line comments are meant for documentation.
the myfunc function"""
print "I'm in a function!"
• Comments should express information that cannot be expressed
in code – do not restate code.
PYTHON TYPING
• Python is a strongly, dynamically typed language.
• Strong Typing
• Obviously, Python isn’t performing static type checking, but it does prevent
mixing operations between mismatched types.
• Explicit conversions are required in order to mix types.
• Example: 2 + “four”  not going to fly

• Dynamic Typing
• All type checking is done at runtime.
• No need to declare a variable or give it a type before use.

Let’s start by looking at Python’s built-in data types.


NUMERIC TYPES
The subtypes are int, long, float and complex.
• Their respective constructors are int(), long(), float(), and complex().

• All numeric types, except complex, support the typical numeric


operations you’d expect to find (a list is available here).
• Mixed arithmetic is supported, with the “narrower” type widened
to that of the other. The same rule is used for mixed comparisons.
NUMERIC TYPES
$ python
>>> 3 + 2
• Numeric 5
• int: equivalent to C’s long int in 2.x but >>> 18 % 5
unlimited in 3.x. 3
• float: equivalent to C’s doubles. >>> abs(-7)
• long: unlimited in 2.x and unavailable in 7
3.x. >>> float(9)
• complex: complex numbers. 9.0
>>> int(5.3)
5
• Supported operations include constructors
(i.e. int(3)), arithmetic, negation, modulus, >>> complex(1,2)
absolute value, exponentiation, etc. (1+2j)
>>> 2 ** 8
256
SEQUENCE DATA TYPES
There are seven sequence subtypes: strings, Unicode strings, lists,
tuples, bytearrays, buffers, and xrange objects.
All data types support arrays of objects but with varying limitations.
The most commonly used sequence data types are strings, lists,
and tuples. The xrange data type finds common use in the
construction of enumeration-controlled loops. The others are used
less commonly.
SEQUENCE TYPES: STRINGS
Created by simply enclosing characters in either single- or double-
quotes.
It’s enough to simply assign the string to a variable.
Strings are immutable.
There are a tremendous amount of built-in string methods (listed
here).
mystring = "Hi, I'm a string!"
SEQUENCE TYPES: STRINGS
Python supports a number of escape sequences such as ‘\t’, ‘\n’,
etc.
Placing ‘r’ before a string will yield its raw value.
There is a string formatting operator ‘%’ similar to C. A list of string
formatting symbols is available here.
Two string literals beside one another are automatically
concatenated together.
print "\tHello,\n" $ python ex.py
print r"\tWorld!\n" Hello,
print "Python is " "so cool."
\tWorld!\n
Python is so cool.
SEQUENCE TYPES: UNICODE
STRINGS
myunicodestr1 = u"Hi Class!"
Unicode strings can be used to store and myunicodestr2 = u"Hi\u0020Class!"
manipulate Unicode data. print myunicodestr1, myunicodestr2
As simple as creating a normal string newunicode = u'\xe4\xf6\xfc'
(just put a ‘u’ on it!). print newunicode
newstr = newunicode.encode('utf-8')
Use Unicode-Escape encoding for special print newstr
characters. print unicode(newstr, 'utf-8')
Also has a raw mode, use ‘ur’ as a
prefix. Output:
To translate to a regular string, use Hi Class! Hi Class!
the .encode() method. äöü
äöü
To translate from a regular string to äöü
Unicode, use the unicode() function.
SEQUENCE TYPES: LISTS
mylist = [42, 'apple', u'unicode apple', 5234656]
Lists are an incredibly useful print mylist
compound data type. mylist[2] = 'banana'
print mylist
Lists can be initialized by
the constructor, or with a
mylist[3] = [['item1', 'item2'], ['item3', 'item4']]
bracket structure containing print mylist
0 or more elements. mylist.sort()
print mylist
Lists are mutable – it is print mylist.pop()
possible to change their mynewlist = [x*2 for x in range(0,5)]
contents. They contain the
additional mutable print mynewlist
operations. [42, 'apple', u'unicode apple', 5234656]
[42, 'apple', 'banana', 5234656]
Lists are nestable. Feel free
[42, 'apple', 'banana', [['item1', 'item2'], ['item3',
to create lists of lists of
'item4']]]
lists…
[42, [['item1', 'item2'], ['item3', 'item4']], 'apple',
'banana']
banana
SEQUENCE DATA TYPES
$ python
• Sequence >>> mylist = ["spam", "eggs", "toast"] # List of strings!
• str: string, represented as a >>> "eggs" in mylist
sequence of 8-bit characters True
in Python 2.x. >>> len(mylist)
• unicode: stores an abstract 3
sequence of code points. >>> mynewlist = ["coffee", "tea"]
>>> mylist + mynewlist
• list: a compound, mutable ['spam', 'eggs', 'toast', 'coffee', 'tea']
data type that can hold items >>> mytuple = tuple(mynewlist)
of varying types.
>>> mytuple
• tuple: a compound, ('coffee', 'tea')
immutable data type that can >>> mytuple.index("tea")
hold items of varying types. 1
Comma separated items >>> mylonglist = ['spam', 'eggs', 'toast', 'coffee', 'tea']
surrounded by parentheses. >>> mylonglist[2:4]
• a few more – we’ll cover ['toast', 'coffee']
them later.
COMMON SEQUENCE
OPERATIONS Operation Result
x in s True if an item of s is equal to x, else
All sequence data False.
types support the
x not in s False if an item of s is equal to x, else
following
True.
operations.
s + t The concatenation of s and t.
s * n, n * s n shallow copies of s concatenated.
s[i] ith item of s, origin 0.
s[i:j] Slice of s from i to j.
s[i:j:k] Slice of s from i to j with step k.
len(s) Length of s.
min(s) Smallest item of s.
max(s) Largest item of s.
s.index(x) Index of the first occurrence of x in s.
COMMON SEQUENCE
OPERATIONS
Mutable sequence types
further support the following
operations.

Operation Result
s[i] = x Item i of s is replaced by x.
s[i:j] = t Slice of s from i to j is replaced by the contents
of t.
del s[i:j] Same as s[i:j] = [].
s[i:j:k] = t The elements of s[i:j:k] are replaced by those of
t.
del s[i:j:k] Removes the elements of s[i:j:k] from the list.
s.append(x) Add x to the end of s.
COMMON SEQUENCE
OPERATIONS
Mutable sequence types
further support the following
operations.
s.extend(x) Appends the contents of x to s.
s.count(x) Return number of i’s for which s[i] == x.

s.index(x[, i[, j]]) Return smallest k such that s[k] == x and


i <= k < j.
s.insert(i, x) Insert x at position i.
s.pop([i]) Same as x = s[i]; del s[i]; return x.
s.remove(x) Same as del s[s.index(x)].
s.reverse() Reverses the items of s in place.
s.sort([cmp[, key[, reverse]]]) Sort the items of s in place.
BASIC BUILT-IN DATA TYPES
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange']
• Set >>> fruit = set(basket)
• set: an unordered >>> fruit
set(['orange', 'pear', 'apple'])
collection of unique
>>> 'orange' in fruit
objects. True
• frozenset: an >>> 'crabgrass' in fruit
immutable version of False
set. >>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b
set(['r', 'd', 'b'])
>>> a | b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
BASIC BUILT-IN DATA TYPES
>>> gradebook = dict()
>>> gradebook['Susan Student'] = 87.0
• Mapping
>>> gradebook • dict: hash tables,
{'Susan Student': 87.0} maps a set of keys
>>> gradebook['Peter Pupil'] = 94.0 to arbitrary
>>> gradebook.keys() objects.
['Peter Pupil', 'Susan Student']
>>> gradebook.values()
[94.0, 87.0]
>>> gradebook.has_key('Tina Tenderfoot')
False
>>> gradebook['Tina Tenderfoot'] = 99.9
>>> gradebook
{'Peter Pupil': 94.0, 'Susan Student': 87.0, 'Tina Tenderfoot': 99.9}
>>> gradebook['Tina Tenderfoot'] = [99.9, 95.7]
>>> gradebook
{'Peter Pupil': 94.0, 'Susan Student': 87.0, 'Tina Tenderfoot': [99.9, 95.7]}
PYTHON DATA TYPES
So now we’ve seen some interesting Python data types.
Notably, we’re very familiar with numeric types, strings, and lists.

That’s not enough to create a useful program, so let’s get some


control flow tools under our belt.
CONTROL FLOW TOOLS
i = 1
While loops have the following
general structure. while i < 4:
print i
while expression: i = i + 1
statements flag = True
Here, statements refers to one or while flag and i < 8:
more lines of Python code. The print flag, i
conditional expression may be any i = i + 1
expression, where any non-zero
value is true. The loop iterates 1
while the expression is true.
2
Note: All the statements indented 3
by the same amount after a True 4
programming construct are
considered to be part of a single True 5
block of code. True 6
True 7
CONTROL FLOW TOOLS
a = 1
b = 0
The if statement has the if a:
following general form. print "a is true!“
if expression: if not b:
statements print "b is false!“
if a and b:
print "a and b are true!“
If the boolean expression if a or b:
evaluates to True, the print "a or b is true!"
statements are executed.
Otherwise, they are skipped a is true!
entirely. b is false!
a or b is true!
CONTROL FLOW TOOLS
a = 1
You can also pair an else b = 0
with an if statement. c = 2
if a > b:
if expression: if a > c:
statements print "a is greatest"
else: else:
statements print "c is greatest"
elif b > c:
The elif keyword can be print "b is greatest"
used to specify an else if else:
statement. print "c is greatest"

Furthermore, if statements
may be nested within c is greatest
eachother.
CONTROL FLOW TOOLS for letter in "aeiou":
print "vowel: ", letter
for i in [1,2,3]:
The for loop has the following general form. print i
for i in range(0,3):
for var in sequence: print i
statements
If a sequence contains an expression list, it vowel: a
is evaluated first. Then, the first item in the vowel: e
sequence is assigned to the iterating vowel: i
variable var. Next, the statements are
vowel: o
executed. Each item in the sequence is
assigned to var, and the statements are vowel: u
executed until the entire sequence is 1
exhausted. 2
3
For loops may be nested with other control
flow tools such as while loops and if 0
statements. 1
2
CONTROL FLOW TOOLS for i in xrange(0, 4):
print i
for i in range(0,8,2):
print i
Python has two handy functions for creating a
for i in range(20,14,-2):
range of integers, typically used in for loops.
print i
These functions are range() and xrange().
They both create a sequence of integers, but
range() creates a list while xrange() creates an 0
xrange object. 1
2
Essentially, range() creates the list statically 3
while xrange() will generate items in the list as 0
they are needed. We will explore this concept 2
further in just a week or two. 4
For very large ranges – say one billion values – 6
you should use xrange() instead. For small 20
ranges, it doesn’t matter. 18
16
CONTROL FLOW TOOLS for num in range(10,20):
if num%2 == 0:
continue
for i in range(3,num):
There are four statements provided
if num%i == 0:
for manipulating loop structures.
These are break, continue, pass, break
and else. else:
print num, 'is a prime number'
• break: terminates the current loop.
• continue: immediately begin the 11 is a prime number
next iteration of the loop. 13 is a prime number
17 is a prime number
• pass: do nothing. Use when a 19 is a prime number
statement is required syntactically.
• else: represents a set of
statements that should execute
when a loop terminates.
OUR FIRST REAL PYTHON
PROGRAM
Ok, so we got some basics out of the way. Now, we can try to
create a real program.
I pulled a problem off of Project Euler. Let’s have some fun.

Each new term in the Fibonacci sequence is generated by adding


the previous two terms. By starting with 1 and 2, the first 10 terms
will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values
do not exceed four million, find the sum of the even-valued terms.
A SOLUTION USING BASIC
PYTHON
from __future__ import print_function Notice we’re using the Python 3.x
version of print here.
total = 0
f1, f2 = 1, 2
while f1 < 4000000:
if f1 % 2 == 0: Python supports multiple
total = total + f1 assignment at once.
f1, f2 = f2, f1 + f2 Right hand side is fully
print(total) evaluated
before setting the variables.
Output: 4613732
FUNCTIONS
# Defining the function
def print_greeting():
A function is created with the def print "Hello!"
keyword. The statements in the block print "How are you today?"
of the function must be indented.
print_greeting() # Calling the function
def function_name(args):
statements Hello!
The def keyword is followed by the How are you today?
function name with round brackets
enclosing the arguments and a colon.
The indented statements form a body
of the function.
The return keyword is used to specify
a list of values to be returned.
FUNCTIONS def hello_func(name, somelist):
print "Hello,", name, "!\n“
name = "Caitlin"
All parameters in the Python somelist[0] = 3
language are passed by return 1, 2
reference. myname = "Ben"
mylist = [1,2]
However, only mutable objects a,b = hello_func(myname, mylist)
can be changed in the called print myname, mylist
function. print a, b
We will talk about this in more
detail Hello, Ben !
later.
Ben [3, 2]
12
FUNCTIONS
Hello, Susan !
What is the output of the following code? Hello, Peter !
Hello, William !
def hello_func(names): The names are now [‘Susie’, ‘Pete’, ‘Will’] .
for n in names:
print "Hello,", n, "!"
names[0] = 'Susie’
names[1] = 'Pete’
names[2] = 'Will’
names = ['Susan', 'Peter', 'William']
hello_func(names)
print "The names are now", names, "."
A SOLUTION WITH
FUNCTIONS
from __future__ import print_function

The Python interpreter will set some special def even_fib():


environmental variables when it starts total = 0
executing. f1, f2 = 1, 2
while f1 < 4000000:
If the Python interpreter is running the module if f1 % 2 == 0:
(the source file) as the main program, it sets total = total + f1
the special __name__ variable to have a value f1, f2 = f2, f1 + f2
"__main__". This allows for flexibility is writing return total
your modules.
if __name__ == "__main__":
Note: __name__, as with other built-ins, has two print(even_fib())
underscores on either side!
INPUT
• raw_input()
• Asks the user for a string of input,
and returns the string. >>> print(raw_input('What is your name? '))
• If you provide an argument, it will be
used as a prompt. What is your name? Caitlin
Caitlin
• input()
>>> print(input('Do some math: '))
• Uses raw_input() to grab a string of Do some math: 2+2*5
data, but then tries to evaluate the
12
string as if it were a Python
expression.
• Returns the value of the expression.
• Dangerous – don’t use it.
Note: In Python 3.x, input() is now just an alias for
raw_input()
A SOLUTION WITH INPUT
Enter the max Fibonacci number: 4000000
from __future__ import print_function 4613732
def even_fib(n):
total = 0
f1, f2 = 1, 2
while f1 < n:
if f1 % 2 == 0:
total = total + f1
f1, f2 = f2, f1 + f2
return total

if __name__ == "__main__":
limit = raw_input(“Enter the max Fibonacci number: ")
print(even_fib(int(limit)))
CODING STYLE
So now that we know how to write a Python program, let’s break for
a bit to think about our coding style. Python has a style guide that
is useful to follow, you can read about PEP 8 here.
I encourage you all to check out pylint, a Python source code
analyzer that helps you maintain good coding standards.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy