320 likes | 507 Views
Intro to Python. Python is an interpreted language Can be used interactively Identifiers are case-sensitive Operators : + - * / * * Arbitrarily large integer. Python Reserved Words. and assert break class continue def del elif else except exec finally for from global
E N D
Python is an interpreted language • Can be used interactively • Identifiers are case-sensitive • Operators: + - * / ** • Arbitrarily large integer
Python Reserved Words and assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while yield
Output Statements • print • print <expr> • print <expr>, <expr>, ..., <expr> • print <expr>, <expr>, ..., <expr>,
print 3+4 print 3, 4, 3 + 4 print print 3, 4, print “The answer is”, 3+4
Assignment Statements <var> = <expr> <var> = input(<prompt>) <var> = raw_input(<prompt>) <var>, <var>, ... <var> = <expr>, <expr>, ..., <expr>
x = 5y = 3.9 * x * (1 - x)age = input(“Yourage?”)name = raw_input(“Yourname?”) x, y = y, x
Decisions if <condition>: <body> elif<condition>: <body> else: <body> < <= == >= > !=
if x > 5: print “greater than five” elifx < 5: print “less than five” else: print “five”
Definite Loops for <var> in <list>: <body>
Sequences/Lists • [0, 1, 2, 3] • [1, 3, 5, 7, 9] • range(10) • range(<expr>)
for i in [0, 1, 2, 3]: printi for i in range(11): printi
Indefinite Loops while <condition>: <body>
i=0while i <= 10: print i i = i + 1
Strings greet = “Hello Bob” str2 = ‘spam’ print greet, str2 greet[0] greet[-1] greet[-3] greet[5:9] greet[:5] greet[5:]
More with Strings greet = “Hello Bob” str2 = ‘spam’ greet + str2 3 * str2 (3 * str2) + (greet * 2) len(greet) for ch in greet: print ch,
String and List Operations • + Concatenation • * Repetition • <string>[] Indexing • <string>[:] Slicing • len(<string>) Length • for <var> in <string> Iteration
[1, 2] + [3, 4] [1, 2] * 3 grades= [‘A’,’B’,’C’,’D’,’F’] grades[0] grades[2:4] len(grades)
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)
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>)
Math Library pie sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) log(x) log10(x) exp(x) ceil(x) floor(x)
Functions def <function>(<params>): <body>
def main(): celsius= input("What is the Celsius temperature? ") fahrenheit= (9.0 / 5.0) * celsius + 32 print "The temperature is ", fahrenheit, " degrees Fahrenheit." main()
def happy(): print “Happy birthday to you!” defsing(person): happy() happy() print “Happy birthday, dear”, person + “.” happy() defmain(): sing(“Fred”) print sing(“Lucy”) print sing(“Elmer”) main()
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) print print “The solutions are:”, root1, root2 main()
defmain(): # 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()
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 result print “The month abbreviation is”, month[n-1] + “.” main()
File Basics <filevar> = open(<name>, <mode>) <filevar>.read() <filevar>.readline() <filevar>.readlines() <filevar>.write(<string>)
import string defmain(): 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()
Dictionaries <dictionary>[<key>] passwd= {} for line in open(‘passwords’, ‘r’): user, pass = string.split(line) passwd[user] = pass
Dictionaries <dict>.has_key(<key>) <key> in <dict> <dict>.keys() <dict>.values() <dict>.items() <dict>.get(<key>, <default>) del <dict>[<key>] <dict>.clear()