Intro to Python. Python is an interpreted language Can be used interactively Identifiers are...

31
Intro to Python

Transcript of Intro to Python. Python is an interpreted language Can be used interactively Identifiers are...

Page 1: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Intro to Python

Page 2: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

• Python is an interpreted language • Can be used interactively• Identifiers are case-sensitive • Operators: + - * / ** • Arbitrarily large integer

Page 3: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Python Reserved Words

and assertbreakclasscontinuedefdel

elifelseexceptexecfinallyforfrom

globalifimportinislambdanot

orpassprintraisereturntrywhile

yield

Page 4: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Output Statements

• print ()• print (<expr>)• print (<expr>, <expr>, ..., <expr> )

Page 5: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

print (3+4)print (3, 4, 3 + 4) print ()print (“The answer is”, 3+4)

Page 6: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Assignment Statements

<var> = <expr> <var> = input(<prompt>) <var> = raw_input(<prompt>) <var>, <var>, ... <var> = <expr>, <expr>, ..., <expr>

Page 7: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

x = 5y = 3.9 * x * (1 - x)age = input(“Your age?”)name = raw_input(“Your name?”) x, y = y, x

Page 8: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Decisions

if <condition>: <body>

elif <condition>: <body>

else: <body>

< <= == >= > !=

Page 9: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

if x > 5: print “greater than five”

elif x < 5: print “less than five”

else: print “five”

Page 10: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Definite Loops

for <var> in <list>: <body>

Page 11: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Sequences/Lists

• [0, 1, 2, 3] • [1, 3, 5, 7, 9] • range(10) • range(<expr>)

Page 12: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

for i in [0, 1, 2, 3]: print i

for i in range(11): print i

Page 13: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Indefinite Loops

while <condition>: <body>

Page 14: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

i=0while i <= 10:

print i i = i + 1

Page 15: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Strings

greet = “Hello Bob” str2 = ‘spam’ print greet, str2 greet[0] greet[-1] greet[-3] greet[5:9] greet[:5] greet[5:]

Page 16: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

More with Strings

greet = “Hello Bob” str2 = ‘spam’ greet + str2 3 * str2 (3 * str2) + (greet * 2) len(greet) for ch in greet:

print ch,

Page 17: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

String and List Operations

• + Concatenation• * Repetition• <string>[] Indexing• <string>[:] Slicing• len(<string>) Length• for <var> in <string> Iteration

Page 18: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

[1, 2] + [3, 4] [1, 2] * 3 grades = [‘A’,’B’,’C’,’D’,’F’] grades[0] grades[2:4] len(grades)

Page 19: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

More with Lists

• <list>.append(x) • <list>.sort()• <list>.reverse() • <list>.index(x) • <list>.insert(i, x) • <list>.count(x) • <list>.remove(x) • <list>.pop(i)

Page 20: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Other String Operations

import string string.capitalize(<string>) string.capwords(<string>) string.lower(<string>) string.upper(<string>) string.replace(<string>, <string>, <string>) string.center(<string>, <int>) string.count(<string>, <string>) string.find(<string>, <string>) string.join(<list>) string.split(<string>)

Page 21: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Math Library

piesin(x) cos(x) tan(x) asin(x) acos(x) atan(x)

log(x) log10(x) exp(x) ceil(x) floor(x)

Page 22: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Functions

def <function>(<params>): <body>

Page 23: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

def main(): celsius = input("What is the Celsius temperature? ") fahrenheit = (9.0 / 5.0) * celsius + 32 print "The temperature is ", fahrenheit, " degrees

Fahrenheit."

main()

Page 24: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

def happy(): print “Happy birthday to you!”

def sing(person): happy() happy() print “Happy birthday, dear”, person + “.” happy()

def main(): sing(“Fred”) print sing(“Lucy”)print sing(“Elmer”)

main()

Page 25: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

import math def main():

print “This program finds the real solutions to a quadratic” print

a, b, c = input(“Please enter the coefficients (a, b, c): “) discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) printprint “The solutions are:”, root1, root2

main()

Page 26: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

def main(): # months is used as a lookup table months = “JanFebMarAprMayJunJulAugSepOctNovDec” n = input(“Enter a month number (1-12): “) # compute starting position of month n in months

pos = (n-1) * 3 # grab the appropriate slice from the month monthAbbrev = months[pos:pos+3] # print the result print “The month abbreviation is”, monthAbbrev + “.”

main()

Page 27: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

def main(): # months is a list used as a lookup table months = [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”,

“Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”] n = input(“Enter a month number (1-12): “) # print the resultprint “The month abbreviation is”, month[n-1] + “.”

main()

Page 28: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

File Basics

<filevar> = open(<name>, <mode>) <filevar>.read() <filevar>.readline() <filevar>.readlines() <filevar>.write(<string>)

Page 29: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

import string def main():

fname = raw_input(“Enter a filename: “)infile = open(fname, ‘r’) data = infile.read() DATA = string.upper(data); outfile = open(fname + “_CAP”, ‘w’) outfile.write(DATA)

main()

Page 30: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Dictionaries

<dictionary>[<key>]

passwd = {} for line in open(‘passwords’, ‘r’):

user, pass = string.split(line) passwd[user] = pass

Page 31: Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators: + - * / ** Arbitrarily large integer.

Dictionaries

<dict>.has_key(<key>) <key> in <dict> <dict>.keys() <dict>.values() <dict>.items()<dict>.get(<key>, <default>) del <dict>[<key>] <dict>.clear()