Python: Part 1

[Pages:11]1

Introduction

Python: Part 1

Created by Rigel Mahmood

-Python supports multiple programming paradigms imperative, object-oriented and functional

-It's a dynamic language the type of variables is decided at runtime (as opposed to statically typed languages such as Java)

-Python uses indentation to declare to declare blocks or functions (instead of using { } )

Basic Constructs

If statement

if expression : Statement(s)

else statement(s)

Ex: if a == 5: c = c + 3 d = d ? 1 else: b =b+7 c = c ? 4

For loop -Recall that for loops in Python do not have { } Ex:

# sum of n numbers sum = 0 for i in range(0, 4):

sum += i print sum Functions -Functions are written using the def keyword Ex: def computeAvg(a,b,c) :

return (a + b + c)/3.0;

2

Running Python

-The latest Python interpreter needs to be installed in Visual Studio before you can run Python programs -From the view menu, choose other windows and then Python Environments.

-Click on a link to "Go Online and help me find other environments". Then click on "latest bit CPython" link as shown below and follow the installation dialogs.

3 Creating a First Project -Create a new Python Project called First. Choose project type to be Python Application as shown below.

From the solution explorer, double click on First.py and type the following code in it.

from math import pi import sys #print ("Hello World") def computeAvg(a,b,c) :

return (a + b + c)/3.0; def main():

print("Result = ",computeAvg(5,8,9)) if __name__ == "__main__":

sys.exit(int(main() or 0))

4

Note: when you are typing the main method- after you type main, hit the tab key and it will complete the skeleton code for it.

-Run the program by Debug->Start Without Debugging. You should see the following output. Note: Python will do decimal division even if both numerator and denominator are integers i.e., we type 7/3, the result will be 2.5. If we wanted it to produce integer division, use //

Numeric Operations in Python

-Same operators as Java - ** is available for exponent calculations - % operator (mod) is also available - As mentioned above, / is decimal division and // is integer division -Data types for numeric operations include int, float, decimal, fraction, and complex - j suffix is used to indicate a complex number, e.g., 3 + 4j

To test the above complex data types, modify the program to appear as: from math import pi import sys #print ("Hello World") def computeAvg(a,b,c) :

return (a + b + c)/3; # use // for integer division

def doComplexMath() : num1 = 3 + 4j num2 = 6 + 3.5j res = num1 * num2 return res;

def main(): print("result = ",computeAvg(5,9,23)) print("result complex = ", doComplexMath())

if __name__ == "__main__": sys.exit(int(main() or 0))

5

String processing in Python -Strings can be declared using either single or double quotes - \ character is used as an escape character similar to Java - + can be used to catenate strings - * can be used to repeat strings i.e. y = 3 * `hello' hellohellohello will be stored in y -Two or more string literals become catenated i.e. z = `hello' `hi' hellohi will be stored in z -Triple quotes break a string constant into multiple lines. Ex: msg = """ Hello there.

How are you?""" -You can also use three single quotes

-Upper and lowercase functions are available on a string Ex: s1 = "hello" s2 = s1.upper()

-To search for a string in a bigger string, use the index or find method Ex: s1 = "hello there how are you" pos = s1.find('how') # will produce 12, Python-indexing is 0-based

6

-To create a substring, use index range Ex: s1 = 'helllo' s2 = s1[0:3] # will produce hel

Converting strings to numbers snum = "25" num1 = int(snum) print(num1 + 1)

snum2 = "25.5" num2 = float(snum2) print(num2 + 1)

Lists and Tuples in Python -Lists are declared using [ ] and can grow in size -Tuples are declared using ( ) and are fixed size

fruits = ['apples', 'oranges', 'bananas', 'plums', 'pineapples'] print(fruits) pfruits = fruits[2:4] print(pfruits) for fr in pfruits :

print(fr) del fruits[2] fruits.remove('oranges') fruits.append('kiwi') print(fruits + pfruits)

-We can use the del statement and remove methods on a list -del deletes entries at a particular index or range of indices -remove searches for an object and removes it if found -We can use + or catenate two lists -Use append to append an object to a list

-Tuples are enclosed in parenthesis and cannot be modified Ex:

s1 = ('john','starkey',12341,3.5) # firstname, lastname, id, gpa print(s1[1])

7

Map function in Python -Python supports lambda expressions -The map function allows us to apply a lambda expression to each element of the list Ex:

def mapTest(mylist) : ys = map(lambda x: x * 2, mylist) #ys is a map object, so we need to convert it to a list result = [] for elem in ys: result.append(elem) return result

def main(): ys = mapTest([5,7,2,6]) print(ys)

Quick Sort

#------------------quick sort------------------------#reference for following code: # 8a44ddcc289c0afdf&pq=quicksort+in+python&PC=DCTE def quicksort(arr, i, j):

if i < j: pos = partition(arr, i, j) quicksort(arr, i, pos - 1) # quicksort left list quicksort(arr, pos + 1, j) # quick sort right list

def partition(arr, i, j): pivot = arr[j] small = i - 1 for k in range(i, j): if arr[k] ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download