Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Pythons notes for whoes students those study python very well, Lecture notes of Programming Languages

Python quick learning this type file also a student student very well and learn some python language

Typology: Lecture notes

2022/2023

Uploaded on 05/22/2023

aayush-tiwari-3
aayush-tiwari-3 🇮🇳

2 documents

1 / 89

Toggle sidebar

Related documents


Partial preview of the text

Download Pythons notes for whoes students those study python very well and more Lecture notes Programming Languages in PDF only on Docsity! 1 Introduction to Programming with Python Python Review. Modified slides from Marty Stepp and Moshe Goldstein 2  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. Programming basics 5 Expressions  expression: A data value or set of operations to compute a value. Examples: 1 + 4 * 3 42  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 6 Integer division  When we divide integers with / , the quotient is also an integer. 3 52 4 ) 14 27 ) 1425 12 135 2 75 54 21  More examples:  35 / 5 is 7  84 / 10 is 8  156 / 100 is 1  The % operator computes the remainder from a division of integers. 3 43 4 ) 14 5 ) 218 12 20 2 18 15 3 7 Real numbers  Python can also manipulate real numbers.  Examples: 6.022 -15.9997 42.0 2.143e17  The operators + - * / % ** ( ) all work for real numbers.  The / produces an exact answer: 15.0 / 2.0 is 7.5  The same rules of precedence also apply to real numbers: Evaluate ( ) before * / % before + -  When integers and reals are mixed, the result is a real number.  Example: 1 / 2.0 is 0.5  The conversion occurs on a per-operator basis.  7 / 3 * 1.2 + 3 / 2  2 * 1.2 + 3 / 2  2.4 + 3 / 2  2.4 + 1  3.4 10 Variables  variable: A named piece of memory that can store a value.  Usage:  Compute an expression's result,  store that result into a variable,  and use that variable later in the program.  assignment statement: Stores a value into a variable.  Syntax: name = value  Examples: x = 5 gpa = 3.14 x 5 gpa 3.14  A variable that has been given a value can be used in expressions. x + 4 is 9  Exercise: Evaluate the quadratic equation for a given a, b, and c. Example >>> x = 7 >>> x 7 >>> x+7 14 >>> x = 'hello' >>> x 'hello' >>> 12  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 print Input: Example print "What's your name?" name = raw_input("> ") print "What year were you born?" birthyear = int(raw_input("> ")) print "Hi “, name, “!”, “You are “, 2016 – birthyear % python input.py What's your name? > Michael What year were you born? >1980 Hi Michael! You are 31 ‘ ® python’ Repetition (loops) and Selection (if/else) 17 The 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 20 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." 21 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 elif condition: statements else: statements Example of If Statements import math x = 30 if x <= 15 : y = x + 15 elif x <= 30 : y = x + 30 else : y = x print ‘y = ‘, print math.sin(y) In file ifstatement.py >>> import ifstatement y = 0.999911860107 >>> In interpreter 25 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. Operator Example Result and 9 != 6 and 2 < 3 True or 2 == 3 or -1 < 5 True not not 7 > 0 False Operator Meaning Example Result == equals 1 + 1 == 2 True != does not equal 3.2 != 2.5 True < less than 10 < 5 False > greater than 10 > 5 True <= less than or equal to 126 <= 100 False >= greater than or equal to 5.0 >= 5.0 True Loop Control Statements break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop pass Does nothing, empty statement placeholder More Examples For Loops  Similar to perl for loops, iterating through a list of values %python forloop1.py 1 7 13 2 for x in [1,7,13,2]: print x forloop1.py % python forloop2.py 0 1 2 3 4 for x in range(5) : print x forloop2.py range(N) generates a list of numbers [0,1, …, n-1] Numbers: Integers  Integer – the equivalent of a C long  Long Integer – an unbounded integer value. >>> 132224 132224 >>> 132323 ** 2 17509376329L >>> Numbers: Floating Point  int(x) converts x to an integer  float(x) converts x to a floating point  The interpreter shows a lot of digits >>> 1.23232 1.2323200000000001 >>> print 1.23232 1.23232 >>> 1.3E7 13000000.0 >>> int(2.0) 2 >>> float(2) 2.0 Numbers: Complex  Built into Python  Same operations are supported as integer and float >>> x = 3 + 2j >>> y = -1j >>> x + y (3+1j) >>> x * y (2-3j) Substrings and Methods >>> s = '012345' >>> s[3] '3' >>> s[1:4] '123' >>> s[2:] '2345' >>> s[:4] '0123' >>> s[-2] '4' • len(String) – returns the number of characters in the String • str(Object) – returns a String representation of the Object >>> len(x) 6 >>> str(10.3) '10.3' String Formatting  Similar to C’s printf  <formatted string> % <elements to insert>  Can usually just use %s for everything, it will convert the object to its String representation. >>> "One, %d, three" % 2 'One, 2, three' >>> "%d, two, %s" % (1,3) '1, two, 3' >>> "%s two %s" % (1, 'three') '1 two three' >>> Types for Data Collection List, Set, and Dictionary List Unordered list Ordered Pairs of values Lists: Modifying Content  x[i] = a reassigns the ith element to the value a  Since x and y point to the same list object, both are changed  The method append also modifies the list >>> x = [1,2,3] >>> y = x >>> x[1] = 15 >>> x [1, 15, 3] >>> y [1, 15, 3] >>> x.append(12) >>> y [1, 15, 3, 12] Lists: Modifying Contents  The method append modifies the list and returns None  List addition (+) returns a new list >>> x = [1,2,3] >>> y = x >>> z = x.append(12) >>> z == None True >>> y [1, 2, 3, 12] >>> x = x + [9,10] >>> x [1, 2, 3, 12, 9, 10] >>> y [1, 2, 3, 12] >>> Using Lists as Stacks  You can use a list as a stack >>> a = ["a", "b", "c“,”d”] >>> a ['a', 'b', 'c', 'd'] >>> a.append("e") >>> a ['a', 'b', 'c', 'd', 'e'] >>> a.pop() 'e' >>> a.pop() 'd' >>> a = ["a", "b", "c"] >>> Sets >>> setA - setB {'a', 'b'} >>> setA | setB {'a', 'c', 'b', 'e', 'd', 'f'} >>> setA & setB {'c', 'd'} >>> setA ^ setB {'a', 'b', 'e', 'f'} >>> Dictionaries  A set of key-value pairs  Dictionaries are mutable >>> d= {‘one’ : 1, 'two' : 2, ‘three’ : 3} >>> d[‘three’] 3 Dictionaries: Add/Modify >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['two'] = 99 >>> d {1: 'hello', 'two': 99, 'blah': [1, 2, 3]} >>> d[7] = 'new entry' >>> d {1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]} Entries can be changed by assigning to that entry • Assigning to a key that does not exist adds an entry Copying Dictionaries and Lists  The built-in list function will copy a list  The dictionary has a method called copy >>> l1 = [1] >>> l2 = list(l1) >>> l1[0] = 22 >>> l1 [22] >>> l2 [1] >>> d = {1 : 10} >>> d2 = d.copy() >>> d[1] = 22 >>> d {1: 22} >>> d2 {1: 10} Data Type Summary  Lists, Tuples, and Dictionaries can store any type (including other lists, tuples, and dictionaries!)  Only lists and dictionaries are mutable  All variables are references Integers: 2323, 3234L Floating Point: 32.3, 3.1E2 Complex: 3 + 2j, 1j Lists: l = [ 1,2,3] Tuples: t = (1,2,3) Dictionaries: d = {‘hello’ : ‘there’, 2 : 15} 52 Functions Function names are like any variable  Functions are objects  The same reference rules hold for them as for other objects >>> x = 10 >>> x 10 >>> def x () : ... print 'hello' >>> x <function x at 0x619f0> >>> x() hello >>> x = 'blah' >>> x 'blah' Functions as Parameters def foo(f, a) : return f(a) def bar(x) : return x * x >>> from funcasparam import * >>> foo(bar, 3) 9 Note that the function foo takes two parameters and applies the first as a function with the second as its parameter funcasparam.py Higher-Order Functions map(func,seq) – for all i, applies func(seq[i]) and returns the corresponding sequence of the calculated results. def double(x): return 2*x >>> from highorder import * >>> lst = range(10) >>> lst [0,1,2,3,4,5,6,7,8,9] >>> map(double,lst) [0,2,4,6,8,10,12,14,16,18] highorder.py Functions Inside Functions  Since they are like any other object, you can have functions inside functions def foo (x,y) : def bar (z) : return z * 2 return bar(x) + y >>> from funcinfunc import * >>> foo(2,3) 7 funcinfunc.py Functions Returning Functions def foo (x) : def bar(y) : return x + y return bar # main f = foo(3) print f print f(2) % python funcreturnfunc.py <function bar at 0x612b0> 5 funcreturnfunc.py Parameters: Defaults  Parameters can be assigned default values  They are overridden if a parameter is given for them  The type of the default doesn’t limit the type of a parameter >>> def foo(x = 3) : ... print x ... >>> foo() 3 >>> foo(10) 10 >>> foo('hello') hello Modules  The highest level structure of Python  Each file with the py suffix is a module  Each module has its own namespace Modules: Imports import mymodule Brings all elements of mymodule in, but must refer to as mymodule.<elem> from mymodule import x Imports x from mymodule right into this namespace from mymodule import * Imports all elements of mymodule into this namespace ‘ ® python’ Text and File Processing 70 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 71  raw_input : Reads a string of text from user input.  Example: name = raw_input("Howdy, pardner. What's yer name? ") print name, "... what a silly name!" Output: Howdy, pardner. What's yer name? Paris Hilton Paris Hilton ... what a silly name! raw_input 72 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 75 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. ‘ ™) python’ Objects and Classes Defining a Class  Python program may own many objects  An object is an item with fields supported by a set of method functions.  An object can have several fields (or called attribute variables) describing such an object  These fields can be accessed or modified by object methods  A class defines what objects look like and what functions can operate on these object.  Declaring a class: class name: statements  Example: class UCSBstudent: age = 21 schoolname=‘UCSB’ Object Methods def name(self, parameter, ..., parameter): statements  self must be the first parameter to any object method  represents the "implicit parameter" (this in Java)  must access the object's fields through the self reference class Point: def move(self, dx, dy): self.x += dx self.y += dy Exercise Answer point.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from math import * class Point: x = 0 y = 0 def set_location(self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy) Calling Methods  A client can call the methods of an object in two ways:  (the value of self can be an implicit or explicit parameter) 1) object.method(parameters) or 2) Class.method(object, parameters)  Example: p = Point(3, -4) p.move(1, 5) Point.move(p, 1, 5) Complete Point Class point.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from math import * class Point: def __init__(self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy) def move(self, dx, dy): self.x += dx self.y += dy def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" Operator Overloading  operator overloading: You can define functions so that Python's built-in operators can be used with your class.  See also: http://docs.python.org/ref/customization.html Operator Class Method - __neg__(self, other) + __pos__(self, other) * __mul__(self, other) / __truediv__(self, other) Unary Operators - __neg__(self) + __pos__(self) Operator Class Method == __eq__(self, other) != __ne__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) Generating Exceptions raise ExceptionType("message")  useful when the client uses your object improperly  types: ArithmeticError, AssertionError, IndexError, NameError, SyntaxError, TypeError, ValueError  Example: class BankAccount: ... def deposit(self, amount): if amount < 0: raise ValueError("negative amount") ...
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved