1 / 45

Introduction to Programming with Python

Introduction to Programming with Python. By Ass. Noor Thamer. Tutorial Outline. interactive "shell" basic types: numbers, strings container types: lists, dictionaries, tuples variables control structures functions & procedures. Python. Python is newer. It is loosely typed language.

duncani
Download Presentation

Introduction to Programming with Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programmingwith Python By Ass. Noor Thamer

  2. Tutorial Outline • interactive "shell" • basic types: numbers, strings • container types: lists, dictionaries, tuples • variables • control structures • functions & procedures

  3. Python • Python is newer. • It is loosely typed language. • It's runtime is slow. • It's code are faster to write. • It is really fun to write with its easier, and its rich features. • As python is gaining levels really fast. • Python is an easy to learn and powerful programming language as it is known in common parlance, there is nevertheless need of a good introduction and tutorial on the Python language.

  4. Programming basics • code or source code: The sequence of instructions in a program. • syntax: The set of legal structures and commands that can be used in a particular programming language. • output: The messages printed to the user by a program. • console: The text box onto which output is printed. • Some source code editors pop up the console as an external window, and others contain their own console window.

  5. compile execute source code Hello.java byte code Hello.class output interpret source code Hello.py output Compiling and interpreting • Many languages require you to compile (translate) your program into a form that the machine understands. • Python is instead directly interpreted into machine instructions.

  6. Expressions • expression: A data value or set of operations to compute a value. Examples: 1 + 4 * 3 13 • Arithmetic operators we will use: • + - * / addition, subtraction/negation, multiplication, division • % modulus, a.k.a. remainder • ** exponentiation • precedence: Order in which operations are computed. • * / % ** have a higher precedence than + -1 + 3 * 4 is 13 • Parentheses can be used to force a certain order of evaluation.(1 + 3) * 4 is 16

  7. print • print : Produces text output on the console. • Syntax: print ("Message“) print Expression • Prints the given text message or expression value on the console, and moves the cursor down to the next line. print Item1, Item2, ..., ItemN • Prints several messages and/or expressions on the same line. • Examples: print ("Hello, world!“) age = 45 print "You have", 65 - age, "years until retirement" Output: Hello, world! You have 20 years until retirement

  8. input • input : Reads a number from user input. • You can assign (store) the result of input into a variable. • Example: age = input("How old are you? ") print ("Your age is", age) print ("You have", 65 - age, "years until retirement“) Output: How old are you? 53 Your age is 53 You have 12 years until retirement

  9. Math commands • Python has useful commands for performing calculations. • To use many of these commands, you must write the following at the top of your Python program: from math import *

  10. Interactive “Shell” • Great for learning the language • Great for experimenting with the library • Great for testing your own modules • Two variations: IDLE (GUI),python (command line) • Type statements or expressions at prompt: >>> print ("Hello, world“) Hello, world >>> x = 12**2 >>> x/2 72 >>> # this is a comment

  11. Numbers • The usual suspects • 12, 3.14, 0xFF, 0377, (-1+2)*3/4**5, abs(x), 0<x<=5 • C-style shifting & masking • 1<<16, x&0xff, x|1, ~x, x^y • Integer division truncates :-( • 1/2 -> 0 # 1./2. -> 0.5, float(1)/2 -> 0.5 • Will be fixed in the future • Long (arbitrary precision), complex • 2L**100 -> 1267650600228229401496703205376L • In Python 2.2 and beyond, 2**100 does the same thing • 1j**2 -> (-1+0j)

  12. Strings • "hello"+"world" "helloworld" # concatenation • "hello"*3 "hellohellohello" # repetition • "hello"[0] "h" # indexing • "hello"[-1] "o" # (from end) • "hello"[1:4] "ell" # slicing • len("hello") 5 # size • "hello" < "jello" 1 # comparison • "e" in "hello" 1 # search • "escapes: \n etc, \033 etc, \if etc" • 'single quotes' """triple quotes""" r"raw strings"

  13. Lists • Flexible arrays, not Lisp-like linked lists • a = [99, "bottles of beer", ["on", "the", "wall"]] • Same operators as for strings • a+b, a*3, a[0], a[-1], a[1:], len(a) • Item and slice assignment • a[0] = 98 • a[1:2] = ["bottles", "of", "beer"] -> [98, "bottles", "of", "beer", ["on", "the", "wall"]] • del a[-1] # -> [98, "bottles", "of", "beer"]

  14. More List Operations >>> a = range(5) # [0,1,2,3,4] >>> a.append(5) # [0,1,2,3,4,5] >>> a.pop() # [0,1,2,3,4] >>> a.insert(0, 42) # [42,0,1,2,3,4] >>> a.pop(0) # [0,1,2,3,4] >>> a.reverse() # [4,3,2,1,0] >>> a.sort() # [0,1,2,3,4]

  15. Tuples • key = (lastname, firstname) • point = x, y, z # parentheses optional • x, y, z = point # unpack • lastname = key[0] • singleton = (1,) # trailing comma!!! • empty = () # parentheses! • tuples vs. lists; tuples immutable

  16. Compare between Sequence Types • Tuple: (‘john’, 32, [CMSC]) • A simple immutable ordered sequence of items • Items can be of mixed types, including collection types • Strings: “John Smith” • Immutable • Conceptually very much like a tuple • List: [1, 2, ‘john’, (‘up’, ‘down’)] • Mutable ordered sequence of items of mixed types

  17. Similar Syntax • All three sequence types (tuples, strings, and lists) share much of the same syntax and functionality. • Key difference: • Tuples and strings are immutable • Lists are mutable • The operations shown in this section can be applied to all sequence types • most examples will just show the operation performed on one

  18. Sequence Types 1 • Define tuples using parentheses and commas >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) • Define lists are using square brackets and commas >>> li = [“abc”, 34, 4.34, 23] • Define strings using quotes (“, ‘, or “““). >>> st = “Hello World” >>> st = ‘Hello World’ >>> st = “““This is a multi-line string that uses triple quotes.”””

  19. Sequence Types 2 • Access individual members of a tuple, list, or string using square bracket “array” notation • Note that all are 0 based… >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) >>> tu[1] # Second item in the tuple. ‘abc’ >>> li = [“abc”, 34, 4.34, 23] >>> li[1] # Second item in the list. 34 >>> st = “Hello World” >>> st[1] # Second character in string. ‘e’

  20. Variables • No need to declare • Need to assign (initialize) • use of uninitialized variable raises exception • Not typed if friendly: greeting = "hello world" else: greeting = 12**2 print greeting • Everything is a "variable": • Even functions, classes, modules

  21. Reference Semantics • Assignment manipulates references • x = y does not make a copy of y • x = y makes x reference the object y references • Very useful; but beware! • Example: >>> a = [1, 2, 3] >>> b = a >>> a.append(4) >>> print b [1, 2, 3, 4]

  22. a 1 2 3 1 2 3 a b Changing a Shared List a = [1, 2, 3] b = a a 1 2 3 a.append(4) 4 b

  23. 1 a Changing an Integer a = 1 a 1 b = a b new int object created by add operator (1+1) 2 a a = a+1 old reference deleted by assignment (a=...) 1 b

  24. for… loop • for loop: Repeats a set of statements over a group of values. • Syntax: for variableName in groupOfValues: statements • We indent the statements to be repeated with tabs or spaces. • variableName gives a name to each value, so you can refer to it in the statements. • groupOfValues can be a range of integers, specified with the range function. • Example: for x in range(1, 6): print x, "squared is", x * x Output: 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25

  25. range • The range function specifies a range of integers: • range(start, stop) - the integers between start (inclusive) and stop (exclusive) • It can also accept a third value specifying the change between values. • range(start, stop, step) - the integers between start (inclusive) and stop (exclusive) by step • Example: for x in range(5, 0, -1): print x print "Blastoff!" Output: 5 4 3 2 1 Blastoff! • Exercise: How would we print the "99 Bottles of Beer" song?

  26. Cumulative loops • Some loops incrementally compute a value that is initialized outside the loop. This is sometimes called a cumulative sum. sum = 0 for i in range(1, 11): sum = sum + (i * i) print "sum of first 10 squares is", sum Output: sum of first 10 squares is 385 • Exercise: Write a Python program that computes the factorial of an integer.

  27. if • if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped. • Syntax: if condition: statements • Example: gpa = 3.4 if gpa > 2.0: print "Your application is accepted."

  28. if/else • if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False. • Syntax: if condition: statements else: statements • Example: gpa = 1.4 if gpa > 2.0: print ("Welcome to Mars University!“) else: print ("Your application is denied.“) • Multiple conditions can be chained with elif ("else if"): if condition: statements elifcondition: statements else: statements

  29. while • while loop: Executes a group of statements as long as a condition is True. • good for indefinite loops (repeat an unknown number of times) • Syntax: while condition: statements • Example: number = 1 while number < 200: print (number, number = number * 2) • Output: 1 2 4 8 16 32 64 128

  30. Logic • Many logical expressions use relational operators: • Logical expressions can be combined with logical operators: • Exercise: Write code to display and count the factors of a number.

  31. Strings • string: A sequence of text characters in a program. • Strings start and end with quotation mark " or apostrophe ' characters. • Examples:"hello""This is a string""This, too, is a string. It can be very long!" • A string may not span across multiple lines or contain a " character."This is nota legal String." "This is not a "legal" String either." • A string can represent characters by preceding them with a backslash. • \t tab character • \n new line character • \" quotation mark character • \\ backslash character • Example: "Hello\tthere\nHow are you?"

  32. Indexes • Characters in a string are numbered with indexes starting at 0: • Example: name = "P. Diddy" • Accessing an individual character of a string: variableName[index] • Example: print name, "starts with", name[0] Output: P. Diddy starts with P

  33. String properties • len(string) - number of characters in a string (including spaces) • str.lower(string) - lowercase version of a string • str.upper(string) - uppercase version of a string • Example: name = "Martin Douglas Stepp" length = len(name) big_name = str.upper(name) print big_name, "has", length, "characters" Output: MARTIN DOUGLAS STEPP has 20 characters

  34. input • input : Reads a string of text from user input. • Example: name = input("What’s your name? ") print (name, "... This is my name!“) Output: What’s your name? Ahmed Salah Ahmed Salah ... This is my name!

  35. Text processing • text processing: Examining, editing, formatting text. • often uses loops that examine the characters of a string one by one • A for loop can examine each character in a string in sequence. • Example: for c in "booyah": print (c) Output: b o o y a h

  36. File processing • Many programs handle data, which often comes from files. • Reading the entire contents of a file: variableName = open("filename").read() Example: file_text = open("bankaccount.txt").read()

  37. Line-by-line processing • Reading a file line-by-line: for line in open("filename").readlines(): statements Example: count = 0 for line in open("bankaccount.txt").readlines(): count = count + 1 print "The file contains", count, "lines." • Exercise: Write a program to process a file of DNA text, such as: ATGCAATTGCTCGATTAG • Count the percent of C+G present in the DNA.

  38. Strings and numbers • ord(text) - converts a string into a number. • Example: ord("a") is 97, ord("b") is 98, ... • Characters map to numbers using standardized mappings such as ASCII and Unicode. • chr(number) - converts a number into a string. • Example: chr(99) is "c"

  39. Functions, Procedures def name(arg1, arg2, ...): """documentation""" # optional doc string statements return # from procedure return expression # from function

  40. Example Function defgcd(a, b): "greatest common divisor" while a != 0: a, b = b%a, a # parallel assignment return b >>> gcd.__doc__ 'greatest common divisor' >>> gcd(12, 20) 4

  41. Classes class name: "documentation" statements -or- class name(base1, base2, ...): ... Most, statements are method definitions: defname(self, arg1, arg2, ...): ... May also be class variable assignments

  42. Example Class class Stack: "A well-known data structure…" def __init__(self): # constructor self.items = [] def push(self, x): self.items.append(x) # What is the upper limit def pop(self): x = self.items[-1] # what happens if it’s empty? del self.items[-1] return x def empty(self): return len(self.items) == 0 # Boolean result

  43. Using Classes • To create an instance, simply call the class object: x = Stack() # no 'new' operator! • To use methods of the instance, call using dot notation: x.empty() # -> 1 x.push(1) # [1] x.empty() # -> 0 x.push("hello") # [1, "hello"] x.pop() # -> "hello" # [1] • To inspect instance variables, use dot notation: x.items # -> [1]

  44. URLs • http://www.python.org • official site • http://starship.python.net • Community • http://www.python.org/psa/bookstore/ • (alias for http://www.amk.ca/bookstore/) • Python Bookstore

  45. TIME FOR QUESTIONS

More Related