Example: air traffic controller

Python Practice Book - Read the Docs

Python Practice BookRelease 2014-08-10 Anand ChitipothuFebruary 25, 2017 Contents1 About this Book32 Table of Started .. with Data .. Oriented Programming .. & Generators .. Programming ..483 License55iiiPython Practice Book, Release 2014-08-10 Welcome toPython Practice Practice Book, Release 2014-08-102 ContentsCHAPTER1 About this BookThis book is prepared from the training notes of Anand conducts Python training classes on a semi-regular basis in Bangalore, India. Checkout out the upcomingtrainings if you are Practice Book, Release 2014-08-104 Chapter 1. About this BookCHAPTER2 Table of ContentsGetting StartedRunning Python InterpreterPython comes with an interactive interpreter. When you typepythonin your shell or command prompt, thepython interpreter becomes active with a>>>prompt and waits for your commands.$ pythonPython (r271:86832, Mar 17 2011, 07:02:35)[GCC (Apple Inc. build 5664)] on darwinType "help", "copyright", "credits" or "license" for more information.

Python Practice Book, Release 2014-08-10 The operators can be combined. >>> 7+2+5-3 11 >>> 2 * 3+4 10 It is important to understand how these compound expressions are evaluated. The operators have precedence, a kind of priority that determines which operator is applied first. Among the numerical operators, the precedence of

Tags:

  Python, Numerical

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Python Practice Book - Read the Docs

1 Python Practice BookRelease 2014-08-10 Anand ChitipothuFebruary 25, 2017 Contents1 About this Book32 Table of Started .. with Data .. Oriented Programming .. & Generators .. Programming ..483 License55iiiPython Practice Book, Release 2014-08-10 Welcome toPython Practice Practice Book, Release 2014-08-102 ContentsCHAPTER1 About this BookThis book is prepared from the training notes of Anand conducts Python training classes on a semi-regular basis in Bangalore, India. Checkout out the upcomingtrainings if you are Practice Book, Release 2014-08-104 Chapter 1. About this BookCHAPTER2 Table of ContentsGetting StartedRunning Python InterpreterPython comes with an interactive interpreter. When you typepythonin your shell or command prompt, thepython interpreter becomes active with a>>>prompt and waits for your commands.$ pythonPython (r271:86832, Mar 17 2011, 07:02:35)[GCC (Apple Inc. build 5664)] on darwinType "help", "copyright", "credits" or "license" for more information.

2 >>>Now you can type any valid Python expression at the prompt. Python reads the typed expression, evaluates it andprints the result.>>>4242>>>4 + 26 Problem 1:Open a new Python interpreter and use it to find the value of2 + Python ScriptsOpen your text editor, type the following text and save it "hello, world!"And run this program by callingpython Make sure you change to the directory where you savedthe file before doing @bodhi ~$ Python , world!anand@bodhi ~$Text after#character in any line is considered as comment.# This is helloworld program# run this as:# Python "hello, world!"Problem 2:Create a Python script to printhello, world!four 3:Create a Python script with the following text and see the Practice Book, Release 2014-08-101 + 2If it doesn t print anything, what changes can you make to the program to print the value?AssignmentsOne of the building blocks of programming is associating a name to a value.

3 This is called assignment. Theassociated name is usually called avariable.>>>x = 4>>>x*x16In this examplexis a variable and it s value you try to use a name that is not associated with any value, Python gives an error message.>>>fooTraceback (most recent call last):File "<stdin>", line 1, in ?NameError: name 'foo' is not defined>>>foo = 4>>>foo4If you re-assign a different value to an existing variable, the new value overwrites the old value.>>>x = 4>>>x4>>>x = 'hello'>>>x'hello'It is possible to do multiple assignments at once.>>>a, b = 1, 2>>>a1>>>b2>>>a + b3 Swapping values of 2 variables in Python is very simple.>>>a, b = 1, 2>>>a, b = b, a>>>a2>>>b1 When executing assignments, Python evaluates the right hand side first and then assigns those values to the vari-ables specified in the left hand 4:What will be output of the following = 4y = x + 1x = 2printx, yProblem 5:What will be the output of the following 2.

4 Table of ContentsPython Practice Book, Release 2014-08-10x, y = 2, 6x, y = y, x + 2printx, yProblem 6:What will be the output of the following , b = 2, 3c, b = a, c + 1printa, b, cNumbersWe already know how to work with numbers.>>>4242>>>4 + 26 Python also supports decimal numbers.>>> >>> + supports the following operators on numbers. +addition -subtraction *multiplication /division **exponent %remainderLet s try them on integers.>>>7 + 29>>>7 - 25>>>7*214>>>7 / 23>>>7**249>>>7 % 21If you notice, the result7 / It is because the/operator when working on integers, producesonly an integer. Lets see what happens when we try it with decimal numbers:>>> / >>> / >>>7 / Getting Started7 Python Practice Book, Release 2014-08-10 The operators can be combined.>>>7 + 2 + 5 - 311>>>2*3 + 410It is important to understand how these compound expressions are evaluated. The operators have precedence, akind of priority that determines which operator is applied first.

5 Among the numerical operators, the precedence ofoperators is as follows, from low precedence to high. +,- *,/,% **When we compute2 + 3*4,3*4is computed first as the precedence of*is higher than+and then theresult is added to 2.>>>2 + 3*414We can use parenthesis to specify the explicit groups.>>>(2 + 3)*420 All the operators except**are left-associcate, that means that the application of the operators starts from left + 2 + 3*4 + 5 3 + 3*4 + 5 3 + 12 + 5 15 + 5 20 StringsStrings what you use to represent are a sequence of characters, enclosed in single quotes or double quotes.>>>x = "hello">>>y = 'world'>>> printx, yhello worldThere is difference between single quotes and double quotes, they can used strings can be written using three single quotes or three double = """This is a multi-line stringwritten inthree lines."""printxy = '''multi-line strings can be writtenusing three single quote characters as string can contain 'single quotes' or "double quotes"in side it.

6 '''printy8 Chapter 2. Table of ContentsPython Practice Book, Release 2014-08-10 FunctionsJust like a value can be associated with a name, a piece of logic can also be associated with a name by defining afunction.>>> defsquare(x):.. returnx* >>>square(5)25 The body of the function is indented. Indentation is the Python s way of grouping the secondary prompt, which the Python interpreter uses to denote that it is expecting some functions can be used in any expressions.>>>square(2) + square(3)13>>>square(square(3))81 Existing functions can be used in creating new functions.>>> defsum_of_squares(x, y):.. returnsquare(x) + square(y)..>>>sum_of_squares(2, 3)13 Functions are just like other values, they can assigned, passed as arguments to other functions etc.>>>f = square>>>f(4)16>>> deffxy(f, x, y):.. returnf(x) + f(y)..>>>fxy(square, 2, 3)13It is important to understand, the scope of the variables used in look at an = 0y = 0defincr(x):y = x + 1returnyincr(5)printx, yVariables assigned in a function, including the arguments are called the local variables to the function.

7 Thevariables defined in the top-level are called global the values ofxandyinside the functionincrwon t effect the values of , we can use the values of the global = (r):returnpi*r* Getting Started9 Python Practice Book, Release 2014-08-10 When Python sees use of a variable not defined locally, it tries to find a global variable with that , you have to explicitly declare a variable asglobalto modify = 0defsquare(x):globalnumcallsnumcalls = numcalls + 1returnx*xProblem 7:How many multiplications are performed when each of the following lines of code is executed?printsquare(5)printsquare(2*5)P roblem 8:What will be the output of the following program?x = 1deff():returnxprintxprintf()Problem 9:What will be the output of the following program?x = 1deff():x = 2returnxprintxprintf()printxProblem 10:What will be the output of the following program?x = 1deff():y = xx = 2returnx + yprintxprintf()printxProblem 11:What will be the output of the following program?

8 X = 2deff(a):x = a*areturnxy = f(3)printx, yFunctions can be called with keyword arguments.>>> defdifference(x, y):.. returnx - >>>difference(5, 2)3>>>difference(x=5, y=2)3>>>difference(5, y=2)3>>>difference(y=2, x=5)310 Chapter 2. Table of ContentsPython Practice Book, Release 2014-08-10 And some arguments can have default values.>>> defincrement(x, amount=1):.. returnx + >>>increment(10)11>>>increment(10, 5)15>>>increment(10, amount=2)12 There is another way of creating functions, using thelambdaoperator.>>>cube =lambdax: x**3>>>fxy(cube, 2, 3)35>>>fxy(lambdax: x**3, 2, 3)35 Notice that unlike function defination, lambda doesn t need areturn. The body of thelambdais a becomes handy when writing small functions to be passed as arguments etc. We ll seemore of it as we get into solving more serious FunctionsPython provides some useful built-in functions.>>>min(2, 3)2>>>max(3, 4)4 The built-in functionlencomputes length of a string.

9 >>>len("helloworld")10 The built-in functionintconverts string to ingeter and built-in functionstrconverts integers and other type ofobjects to strings.>>>int("50")50>>>str(123)"123"Pr oblem 12:Write a functioncount_digitsto find number of digits in the given number.>>>count_digits(5)1>>>count_digit s(12345)5 MethodsMethods are special kind of functions that work on an example,upperis a method available on string objects.>>>x = "hello">>> () Getting Started11 Python Practice Book, Release 2014-08-10As already mentioned, methods are also functions. They can be assigned to other variables can be called separately.>>>f = >>> printf()HELLOP roblem 13:Write a functionistrcmpto compare two strings, ignoring the case.>>>istrcmp(' Python ', ' Python ')True>>>istrcmp('LaTeX', 'Latex')True>>>istrcmp('a', 'b')FalseConditional ExpressionsPython provides various operators for comparing values. The result of a comparison is a boolean value, eitherTrueorFalse.

10 >>>2 < 3 False>>>2 > 3 TrueHere is the list of available conditional operators. ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal toIt is even possible to combine these operators.>>>x = 5>>>2 < x < 10 True>>>2 < 3 < 4 < 5 < 6 TrueThe conditional operators work even on strings - the ordering being the lexical order.>>>" Python " > "perl"True>>>" Python " > "java"TrueThere are few logical operators to combine boolean values. a and bisTrueonly if bothaandbare True. a or bis True if eitheraorbis True. not ais True only ifais False.>>>TrueandTrueTrue>>>TrueandFalseF alse>>>2 < 3and5 < 412 Chapter 2. Table of ContentsPython Practice Book, Release 2014-08-10 False>>>2 < 3or5 < 4 TrueProblem 14:What will be output of the following program?print2 < 3and3 > 1print2 < 3or3 > 1print2 < 3or not3 > 1print2 < 3and not3 > 1 Problem 15:What will be output of the following program?x = 4y = 5p = x < yorx < zprintpProblem 16:What will be output of the following program?


Related search queries