Python

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Whitespace indentation

Python requires consistency in whitespace indentation. If previous statements use an indentation of four spaces to group elements, then that must be done consistently throughout the program.

What is a type?

● a type in Python essentially defines two things: --> the internal structure of the type (what it contains) --> the kinds of operations you can perform ● 'abc'.capitalize() is a method you can call on strings, but not integers ● some types have multiple elements (collections),

Best practice for naming variables

Pro-tip: Good identifier naming is very important for producing quality code •100% of the identifiers in a program must be meaningful -Variable names, function names, function arguments, ... Best-practice suggestions: -Don't be cute, don't use abbreviations -Use intention-revealing names -Avoid names that imply something that isn't true -Use pronounceable names -Avoid mental mapping

Refactoring

Pro-tip: Refactor, refactor, refactor, ... •It's common to create code and "just get it working" -But imagine looking at your code in six-months' time! -You will have no idea what it means •A best-practice strategy is called refactoring -Each time you work on your code look for ways to improve its readability -And change it!

Punctuators

Punctuators, a.k.a. delimiters, separate different elements in Python statements and expressions. Examples: ( ) [ ] @ : ; , = \ # etc.

Fractions

Python also provides the type 'fraction' for rational numbers. A fraction consists of the obvious two parts: the numerator and the denominator. Fractions do not suffer from the conversion of a rational to a real number, as discussed previously, and can be operated on without loss of precision using addition, subtraction, multiplication, and division.

Boolean type

A Boolean value has a Python type 'bool'. The Boolean type refers to the values True or False (note the capitalization). If an object is of type Boolean, it can be only one of those two values. In fact, the two Boolean objects are represented as integers: 0 is False and 1 is True. More generally, an object with value 0 is considered to be the equivalent of a False Boolean value and any nonzero value is considered to be the equivalent of a True Boolean value. In addition, any empty object, such as an empty string (' '), is considered to be False.

Dictionary type

A dictionary in Python is of type 'dict'. A dictionary is a map type, a collection though not a sequence. A map type consists of a set of element pairs. The first element in the pair is the key and the second is the value. The key can be used to search for a value, much like a dictionary or phone book. If you want to look up the phone number (the value) or a person (the key), you can efficiently search for the name and find the number. Curly braces, ({ and }) indicate dictionaries; a colon separates the key and value pair. Example: {'Jones':3471124, 'Larson':3472289, 'Smith':3471288}

Literals

A literal is a notation for representing a fixed value—a value that cannot be changed in the program.

Sequence

A sequence is a collection where there is an order associated with the elements. For example, a string is a sequence because the order of the characters is important.

Set type

A set in Python is of type 'set'. A set is a collection of unique elements—similar to a set in mathematics. Sets, like dictionaries, use curly braces, but unlike dictionaries there are no colons. A set supports mathematical set operations such as union and intersection. Example: {1,3,5}

Set

A set is a collection that is not a sequence, as membership, not order, is important for a set.

Three options for importing modules

This affects how you call functions from the module: >>> import math #everything in math is accessible, must use fully-qualified name: math.pi >>> from math import pi #only pi is accessible, don't need module name, just: pi >>> from math import * #everything is accessible, don't need module name, just: pi

Summary of Repetition - 'while' statement

We can put all the variations of 'while' into one generic pattern: while boolean expression1: # statement suite1 if boolean expression2: break # Exit loop now; skip else. if boolean expression3: continue # Go to top of loop now. else: # statement suite2

Testing code

Why? •We (should) have already checked our design, so we know it works -So why do we need to make sure the code works? •We need to check that we implemented our solution correctly How? •Try running it, see what happens •If and when error messages appear READ THEM! -Right now they may seem unhelpful, but we will become familiar with them over time What are we testing? That it runs -Syntax errors •That it gives the correct results -Logic errors •Are there any user inputs which break the program -Runtime errors

package

a collection of modules Example: from kivy.app import App - this gets 'app' from 'kivy' 'kivy' is the package and 'app' is one module within that package App is a 'class'

Non-Printing Characters

carriage return \n tab \t Example: >>> print(" first line \n second line") first line second line

math module

import math >>> print(math.pi) # constant in math module >>> print(math.sin(1.0)) # a function in math >>> help(math.pow) # help info on pow

Explicit type conversion

● A character '1' is not an integer 1. ● You need to convert the value returned by the input command (characters) into an integer ● int("123") yields the integer 123 >>> age = int(input("Age:")) input function creates a string, then the int converts the string to integer type

Assignment

Assignment is one way to create a name for a variable. The purpose of assignment is to associate a name with a value. The symbol of assignment for Python is the equal sign (=). N.B. This is not the same as in maths, where the equal sign (=) denotes equality. In Python, the equal sign (=) represents assignment. Assignment is the operation to associate a value with a variable. The left-hand side represents the variable name and the right-hand side represents the value. Example: my_var = my_var + 1 We interpret the previous statement as follows: - get the value referred to by my_var, add 1 to it, and then associate the resulting sum with the variable my_var. That is, if my_var's value was 4, then after assignment, its value will be updated to be 5.

Assignment statement

Evaluation of an assignment statement is a two-step process: 1. Evaluate the expression on the right-hand side. 2. Take the resulting value from the right-hand expression and associate it with the variable on the left-hand side (create the variable if it doesn't exist; otherwise update it). For example: my_var = 2 + 3 * 5 First evaluate the expression on the right-hand side, resulting in the value 17 (remember, multiplication before addition), then associate 17 with my_var, that is, update the namespace so that my_var is an alias for 17 in the namespace.

'while' structure (refer to pages 122 & 126)

Generic while structure: Set an initial value for loop control variable. (If not, loop will not start). 'while' - Boolean tests the loop control variable: Perform tasks as part of the loop. At the loop's end, update the loop control variable. (If not, an infinite loop results!)

'while' or 'for' loop?

How to decide which to use, for or while? The while loop is more general but the for loop is useful for moving through all the elements of a collection. Fortunately, many objects can be examined using iteration. Think for first!

Multiple assignment

In Python, we can do multiple assignments on the same line by separating corresponding LHS and RHS by commas. Example: a_int, b_int, c_int = 15, 10, 17 is equivalent to a int = 15 b int = 10 c int = 17 The first name on the LHS gets the first value on the RHS, the second name on the LHS gets the second value on the RHS, and so on.

Indentation

Indentation is used by all programmers to make code more readable. - Programmers often indent code to indicate that the indented code is grouped together, meaning those statements have some common purpose. - However, indentation is treated uniquely in Python. - Python requires it for grouping.

Equivalence of 'while' and 'for'

It is possible to write a 'while' loop that behaves exactly like a 'for' loop. However, not every 'while' loop can be expressed as a 'for' loop. Consider this simple for loop using the sequence generated by range(5): for i in range(5): print(i) We can write an equivalent while loop as: i = 0 while i < 5: print(i) i += 1 The 'for' loop is easier to read and understand, but it is useful only for moving through the elements of objects with iterators. Fortunately, in Python you will find so many objects with iterators that you will frequently use a for loop.

'range' function in a 'for' loop

Its operation generates a sequence of integers, in which the size and values in the range are dictated by its arguments. It takes up to three arguments: 1. the start value 2. the end value 3. the step or separation between each value. The range function generates what is termed a 'half open range'. Such a range does not include the 'end value' in the sequence generated. Examples: 1. Only one value specified: >>> for i in range(5): #one value is stop value print(i, end=' ') #first value defaults to zero 0 1 2 3 4 #step value defaults to one 2. Two values specified: >>> for i in range(3,10): #1st value is start value print(i, end=' ') #2nd value is stop value 3 4 5 6 7 8 9 #step value defaults to one 3. Three values specified: >>> for i in range(1,20,4): #1st value is start value print(i, end=' ') #2nd value is stop value 1 5 9 13 17 #3rd value is step value >>> for i in range(1,20,2): # print odd i n t e g e r s print(i, end=' ') 1 3 5 7 9 11 13 15 17 19

Summary of Repetition - 'for' statement

Just like the 'while' statement, the 'for' statement can support a terminal 'else' suite, as well as the control modifiers 'continue' and 'break'. Their roles are: 1. The 'else' suite is executed after the 'for' loop exits normally. 2. The 'break' statement provides an immediate exit of the 'for' loop, skipping the 'else' clause. 3. The 'continue' statement immediately halts the present iteration of the loop, continuing with the rest of the iterations. Its more general form is shown here: for target in object: # statement_suite1 if boolean expression1: break # Exit loop now; skip else. if boolean expression2: continue # Go to top of loop now. else: # statement_suite2

Runtime errors

Often linked to 'types' of data -Eg we read a value from the keyboard into an Integer and then double it •What if the user types in a word? •How do we fix them? -For now - ignore them -Eventually •Limit user inputs with drop-down box

Swap values

Python's multiple assignment lets us perform a swap in one line: >>> a int = 2 >>> b int = 3 >>> a int, b int = b int, a int >>> a int 3 >>> b int 2

'continue' statement

Sometimes we might want to simply skip some portion of the 'while' suite we are executing and have control flow back to the beginning of the 'while loop'. That is, exit early from this iteration of the loop (not the loop itself ), and keep executing the 'while' loop. In this way, the continue statement is less drastic than the break. However, similar to the break, it can make the flow of control harder to follow. Therefore, consider adjusting your algorithm to eliminate it, because you'll often find the resulting code is more readable.

Strings as a Sequence

String objects are defined as a sequence of characters. Therefore, 'Hello World' is a sequence of 11 characters—remember that a space is a character. Because a sequence has an order, we can number the characters by their position in the sequence: characters H e l l o W o r l d index 0 1 2 3 4 5 6 7 8 9 10 ..... -2 -1 This position is called the index of the character within the string. In Python, and other languages as well, the first index (the first position) in a sequence is index 0.

Syntax vs Logic Errors

Syntax errors are usually easy to find -Python IDE will tell you which line (or close) is wrong! •Logic errors can be sneaky -Which is why modern programming environments provide debuggers •Both are corrected by modifying code -Either to fix the syntax, or to use the correct logic

Readability

The benefit of indentation is readability. Python's whitespace indentation forces readability.

empty 'list' & 'append' statement

The empty list is designated by [ ], and a very useful method used in conjunction with lists is the 'append' method.

'isdigit' method

The method 'isdigit' checks whether the string consists of digits only. the syntax for 'isdigit' method − str.isdigit() This method returns 'True' if all characters in the string are digits and there is at least one character, 'False' otherwise.

Modulus Operator

The modulus operator (%) give the integer remainder of division: ● 5 % 3 yields 2 ● 7.0 % 3 yields 1.0 Again, the type of the result depends on the types of the operands.

Assignment

The operation to associate a value with a variable. Python uses the equal sign '=' to represent assignment. LHS = RHS Step 1: Evaluate the RHS (Right Hand Side) to get a value. Step 2: Associate that value with the variable named on the LHS (Left Hand Side). The LHS represents the variable name and the RHS represents the value.

Chained Boolean expression

A chained expression is really the equivalent of two boolean expressions that are 'and'ed' together. Example: 4 < 5 == True The equivalent 'and' expression is: (4 < 5) and (5 == True) Which is False.

While loops

Also know as a 'pre-test' loop -Tests the loop condition BEFORE it runs •May never run if the condition is false to start with •Like decisions, an iteration 'block' has 2 parts -Header While <condition>: -Body •Code within the loop, must be indented

Iterator

An iterator is an object associated with all the collection types in Python. For any Python collection—an iterator allows us to examine each individual element in that collection, one at a time. Such a collection is called an 'iterable', a collection that can be examined by a 'for' loop.

Precedence of

Operator Description () Parenthesis (grouping) ** Exponentiation +x, -x Positive, Negative *,/,% Multiplication, Division, Remainder +,- Addition, Subtraction <, <=, >, >=,! =, == Comparisons not x Boolean NOT and Boolean AND or Boolean OR

'while-else' statement

Similar to the 'if-else' statement, you can have an 'else' clause at the end of a 'while' loop. The else is strictly optional, but it does have some very nice uses. while boolean expression: # suite1 else: # suite2 The 'else' clause is entered after the 'while' loop's Boolean expression becomes (False). This entry occurs even if the expression is initially (False) and the 'while' loop never ran (its suite was never executed). As with other header statements, the 'else" part of the 'while' loop can have its own associated suite of statements. Think of the 'else' statement on the 'while' loop as "cleanup" for the action performed as the loop ends normally. The 'else' clause is a handy way to perform some final task when the loop ends normally.

'if-elif-else' Statement

The 'elif' is simply shorthand for "else if"—a shorthand that also exists in some other languages. The 'elif' is simply shorthand for "else if"—a shorthand that also exists in some other languages. The 'elif header' has an associated condition, just like an if statement. It too has an associated 'suite'. Again, note the indentation: the keywords (if, elif, else) are indented the same amount as they are part of the overall if statement. Further, each of the 'if', 'elif', and 'else' statements can have an associated suite. The basic idea of a set of 'if-elif-else' statement is to find the first (True) condition in the set of 'if' and 'elif' headers and execute that associated suite. If no such (True) condition is found, the 'else' is executed. The important point is that only one suite will be executed. if boolean expression1: # suite1 elif boolean expression2: # suite2 elif boolean expression3: # suite3 # as many elif statements as you like else: # suite last The 'if-elif-else' statement operation is as follows: 1. Evaluate boolean expression1 to yield True or False. 2. If boolean expression1 yields True, (a) Execute suite1. (b) Continue with the next statement after suite last. 3. If boolean expression1 yields False, then evaluate boolean expression2. If boolean expression2 yields True, (a) Execute suite2. (b) Continue with the next statement after suite last. 4. If all preceding boolean expressions yield False, evaluate boolean expression3. If boolean expression3 yields True, (a) Execute suite3. (b) Continue with the next statement after suite last. 5. If all preceding boolean expressions yield False, (a) Execute the else part and suite last. (b) Continue with the next statement after suite last. For each 'elif' statement the associated suite will be executed if all preceding boolean expressions are (False) and its boolean expression is (True). If all 'if' and 'elif' conditions are (False), then the 'else' clause is executed.

'break' Statement

The 'else' clause is often used in conjunction with the break statement. The 'break' statement can be used to immediately exit the execution of the current loop and skip past all the remaining parts of the loop suite. The 'break' statement is useful for stopping computation when the "answer" has been found or when continuing the computation is otherwise useless.

'range' function

The 'range' function generates a collection data type, which is a sequence of numbers. T The range type is also called an 'iterable' - a set of values that can be iterated over—say, by a for loop. Examples: >>> range(1,10) range(1, 10) >>> my range=range(1,10) >>> type(my range) <class 'range'> >>> len(my range) 9 >>> for i in my range: print(i, end=' ') 1 2 3 4 5 6 7 8 9 >>>

'pass' statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. Odd as it seems, pass has its uses: 1. It can be used to test a statement (say, opening a file or iterating through a collection) just to see if it works. You don't want to do anything as a result, just see if the statement is correct. 2. More interestingly, you can use pass as a place holder. You need to do something at this point, but you don't know what yet. You place a pass at that point and come back later to fill in the details.

Type conversion

● int(some_var) returns an integer ● float(some_var) returns a float ● str(some_var) returns a string ● should check out what works: - int(2.1) -> 2, int('2') ->2, but int('2.1') fails - float(2) -> 2.0, float('2.0') -> 2.0, -> float('2') -> 2.0, float(2.0) -> 2.0 - str(2) -> '2', str(2.0) -> '2.0', str('a') -> 'a'

Expression

A combination of values and operations that creates a new value that we call a return value—i.e., the value returned by the operation(s). If you enter an expression into the Python shell, a value will be returned and displayed. >>> my int + 5 # expression , value associated with my int added to 5 10 >>> my int # no s ide e f f e c t of expres sion , my int i s unchanged 5 >>>

Copy Slice

>>> name one = 'Monty' >>> name two = name one[:] >>> name two 'Monty' >>> Remember, a new string is yielded as the result of a slice; the original string is not modified. Thus a copy slice is indeed a new copy of the original string.

'while' loop

A 'while' loop works as follows: 1. The program enters the 'while' construct and evaluates the Boolean expression (condition). 2. If the Boolean expression is (True), then the associated 'while suite' is executed. 3. At the end of the 'suite', control flows back to the top of the 'while', where the Boolean expression is re-evaluated. 4. If the Boolean expression yields (True), the loop executes again. If the Boolean yields (False), then the 'while' suite is skipped and the code following the 'while' loop is executed. Some things to note about how a 'while' statement works: 1. The condition is evaluated before the suite is executed. This means that if the condition starts out (False), the loop will never run. 2. If the condition always remained True, the loop will never end, i.e. an 'infinite loop'.

Collection

A collection in Python is a single object that contains multiple elements that are associated with the collection object. Examples: 1. strings 2. lists 3. dictionaries 4. sets

Side effect

A side effect is some change that results from executing the statement.

Types

● In Python, each OBJECT is an example of a TYPE. ● The TYPE of an object determines two things: 1. ATTRIBUTES - its content 2. Operations that can be performed on the object ● The type( ) function returns the type of any object: >>> num1 = 7 >>> type(num1) <class 'int'> >>> num2 = 2.5 >>> type(num2) <class 'float'> ● Some Python types: ● int --> integer ● float --> floating-point numbers ● bool --> Boolean ● A collection type contains multiple objects organised as a single object type. ● collection types: ● str --> string ● list --> list ● dict --> dictionary ● set --> set Note: ● Strings & lists are collections that are ordered and are known as sequences

Object

● In Python, every 'thing' in the system is an OBJECT ● An OBJECT has: ● An identity ● some attributes ● Zero or more names ● Whenever an object is created (instantiated) by Python, it receives an identification number, ID. ● The ID number is used by python to distinguish one object from another ● The ID number is system-dependent; it will differ from session to session or machine to machine. ● The id( ) function used to find an objects ID number: >>> num1 = 7 >>> id(num1) 16790848 >>> num2 = 2.5 >>> id(num1) 7397652 ● An object can also have a name or multiple names. The name is not part of the object's ID. It is used by programmers to make code more readable. ● Python uses the namespace to associate a name (e.g. a variable name) with an object. ● Attributes are information about the object: ● type ● methods ● names of any values stored in the object In Python, every 'thing' in a program is considered to be an object. Some attributes - information about the object; e.g. type, such as int, float, str or Boolean; type tells Python which operations can be used with an object and the results they return. The type function returns the type of any object. >>>print(type("David")) yields <class 'str'>

Python name conventions more

● Names for variables and functions start with a lowercase letter and use lower_with_under: --> my_list --> square_root_function ● Classes start with upper case letter and use Pascal case: class FoodItem(Product): ● Constants use all UPPERCASE: MINIMUM_ALCOHOL_THRESHOLD = 0.00 # class attribute

Dynamically typed language

● Python is a dynamically typed language ● Python does not require you to pre-define what type can be associated with a variable: age = 13 is an integer name = "David" is a string numbers = [1, 2, 3] is a list ● What type a variable holds can change ● Nonetheless, knowing the type can be important for using the correct operation on a variable. Thus proper naming is important! print(type(age)) returns <class 'int'>

Strings Are Iterable

A data type that is iterable means that the individual elements can be "iterated through" using a 'for' loop (or other methods). Example: >>> for char in 'Hi mom': print(char, type(char)) H <class 'str'> i <class 'str'> <class 'str'> m <class 'str'> o <class 'str'> m <class 'str'> >>> As with range, the for assigns each individual element of the string, one at a time, to the variable 'char' and prints them out. Also printed is the type of the object associated with 'char', which is of course type 'str'.

'half-open' range

A half-open range designates the beginning of the sequence that is included in the result along with an end of the sequence that is not included. hello str = 'Hello World' For hello str[6:10] the range indicates a subsequence consisting of the strings at indices 6, 7, 8, and 9. The string at index 10 is not included. Every range can be specified with two values: the beginning index of the range and end index of the range, separated by a colon (:). If a value on either side of the colon is missing, a 'default' is used in place of the missing value. If the first index is missing, default is 0: hello str[:5] is 'Hello' is the same as hello str[0:5] is 'Hello' If the last index is missing, default is the end of the sequence, INCLUDING the last character. hello str[6:] is 'World' is the same as hello str[6:11] is 'World'

List type

A list in Python is of type 'list'. A list is also a sequence type, like a string, though it can have elements other than characters in the sequence. Because sequences are collections, a list is also a collection. Lists are indicated with square brackets ([ and ]), and their contents are separated by commas. Example: [4, 3.57, 'abc']

Statement

A statement does not return a value, but does perform some task. Some statements may control the flow of the program, and others might ask for resources; statements perform a wide variety of tasks. >>> my int = 5 # statement , no return value but my int now has value 5 >>> my int 5

String type

A string in Python has the type 'str'. A string is our first collection type. A collection type contains multiple objects organized as a single object type. The string type is a 'sequence'. It consists of a collection of characters in a sequence (order matters), delimited by single quotes (' ') or double quotes (" "). For example, "This is a string!" or 'here is another string' or even a very short string as "x".

Variables

A variable is a name you create in your program to represent "something" in your program. That "something" can be one of many types of entities: - a value (an integer, a string, a floating-point number, and so on) - another program to run - a set of data - a file Variables should have meaningful names, because the purpose of a good variable name is to make your code more readable. Once a variable is created, you can store, retrieve, or modify the data associated with that variable. Every time you use your variable in a program, its value is retrieved by Python and used in that variable's place. Thus, a variable is really a way to make it easier to read the program you are writing.

'if-else' Statement

A variation on the basic 'if' statement adds the ability to execute one suite of statements if the decision Boolean is (True) or to execute a different suite of statements if the Boolean expression is (False). Note that there are two statements and two suites here: the suite associated with the 'if' and the suite associated with the 'else'. Also note that the 'if' and 'else' are at the same indentation; the 'else' is not part of the 'if' suite, but together they create an 'if-else' compound statement. The if-else statement operation is as follows: 1. Evaluate boolean expression to yield True or False. 2. If boolean expression yields (True), (a) Execute the 'if suite', indented under the 'if'. (b) Continue with the rest of the Python program. 3. If boolean expression yields (False), (a) Execute the 'else suite', indented under the 'else'. (b) Continue with the rest of the Python program.

Naming types

Because the type information is not part of the variable, it is often helpful to help keep track of types by affixing the type name to their variables, such as my_int,b_float, phone_book_dict.

For loops

Before we start the loop, we set the value of the variable that is used as the counter -On each iteration the value of variable increases by one, until it is equal to end -On the last iteration the value of variable will be end •E.g. For count in range (10): Print(str(count)) Will display the numbers 1,2,3,4,5,6,7,8,9 and 10 One after the other

Getting values in Python

Existing Python function: -variableName = input(prompt) •Displays prompt (whatever it's value) and then gets a value from the keyboard. This value will be stored in variableName

Floating-Point Numbers

Floating-point or real numbers are designated in Python as type 'float'. The floating-point type refers to non-integer numbers—numbers with decimal points. Floats are created either by typing the value, such as 25.678, or by using exponential notation, with the exponent represented by an "e." Thus, 2.99 × 108 is written as 2.99e8 and 9.109 × 10−31 can be written as 9.109e-31. N.B. Floats represent Real numbers, but only approximately! Examples: >>> 2.0 / 3.0 0.6666666666666666 >>> 1.1 + 2.2 3.3000000000000003 >>> 0.1 + 0.1 + 0.1 - 0.3 5.551115123125783e-17 >>> If you were to do the calculations yourself on paper, you would find that 1.1+2.2 is equal to 3.3. However, the session shows it is 3.3000000000000003. Same for the last addition. The result should be zero but Python returns a very small value instead. Approximations like this, if carried through multiple evaluations, can lead to significant differences than what is expected. Python does provide a module called the 'decimal' module that provides more predictable, and controllable, results for floating-point numbers. It is important to remember that floating-point values are approximate values, not exact, and that operations using floating-point values yield approximate values.

Syntax errors

How do we identify them? -Run code •How do we find them? -READ error messages •No, really, READ them! •How do we fix them? -Practice and familiarity •Build up a dictionary of commons errors and their fixes

Logic errors

How do we identify them? -Test, test and test again -Incorrect results indicate logic errors -What makes good test data? •KNOWN results •(otherwise what are you comparing it to?) •How do we find them? -Debugging •How do we fix them? -Modify code

Object type

In Python, and in many other languages, each object is considered an example of a type. For example, 1, 27, and 365 are objects, each of the same type, called int (integer). Knowing the type of an object informs Python of two things: 1. Attributes of the object tell us something about its ''content.'' For example, there are no decimal points in an integer object, and there are no letters in either an integer object or a float object. 2. Operations we can perform on the object and the results they return. For example, we can divide two integer objects or two float objects, but the division operation makes no sense on a string object.

Variable creation

In Python, when a name is first used (assigned a value, defined as a function name, etc.) is when the name is created. Python updates the namespace with the new name and its associated value.

Variables

In contrast to literals, variables are symbols that can be assigned a value, and that value can be modified during the execution of the code.

Slicing strings

Indexing also allows selection of subsequences of the string with the proper indices. Python calls such a subsequence a slice. Remember, just like for a single index, a slice returns a new string and does not change the original string in any way. To index a subsequence, you indicate a range of indices within the square bracket by providing a pair of indices separated by a colon (:). Example: >>> hello str = 'Hello World' >>> hello_str[6:10] 'Worl' >>>

Compound statement

Is considered to be one logical statement. Indentation is used to indicate that the indented statements following the 'if' are associated with that 'if'. Consists of the 'if' keyword which is part of the header and the set of indented statements is called the 'suite'. All headers end with a colon (:) A suite of statements is a set of statements that has the same indentation and these statements are executed as a group.

Keywords

Keywords are special words in Python that cannot be used by you to name things. They indicate commands to the Python interpreter. Examples: - print, if, import, while, and, not, True, False, def, return etc.

Order of operations and parentheses

Operator Description ( ) Parentheis * * Exponentiation +x, -x Positive, Negative *, /, %, // Multiplication, Division, Remainder, Quotient =, - Addition, Subtraction ● Remember, parentheses always takes precedence

Operators

Operators are special tokens (sequences of characters) that have meaning to the Python interpreter. Using them implies some operation, such as addition, subtraction, or something similar. Examples: +, -, /, //, <, >, %, & etc.

Precedence of relational operators

Precedence & associativity (order) of relational operators: highest to lowest. Operator Description () parentheses (grouping) ** exponentiation +x, -x positive, negative *,/,%,// multiplication, division, remainder, quotient +,- addition, subtraction <, <=, >, >=, !=, == Comparisons not x Boolean NOT and Boolean AND or Boolean OR

Print statement

Print is a function that performs a much-used operation—printing values to the Python shell. - Printable elements are placed in the parentheses after the print statement. - If the element being printed is quoted, it is printed exactly as it appears in the quotes; if the element is a variable, then the value associated with the variable is printed. - Each object (string, variable, value, etc.) that is to be printed is separated from other objects by commas.

Whitespace

Python counts as whitespace the following characters: space, tab, return, linefeed, formfeed, and vertical tab. Python has the following rules about how whitespace is used in a program: - Whitespace is ignored within both expressions and statements. For example, Y=X+5 has exactly the same meaning as Y = X + 5. - Leading whitespace, whitespace at the beginning of a line, defines indentation. Indentation plays a special role in Python (see the following section). - Blank lines are also considered to be whitespace, and the rule for blank lines is trivial: blank lines are allowed anywhere and are ignored.

Function

Python function: - Represents a single operation to be performed - Takes zero or more arguments as input - Returns one value (potentially a compound object) as output

Types of Python variables

Python has many types... Type. The values it has int. All whole numbers (..., -3, -2, -1, 0, 1, 2, 3, ...) float. Some real numbers (...,-2.73,-1.0,-0.5,0.0,0.5,3.1415, ...) str Any sequence of characters ('hello world', 'answer', ...) list A collection of objects ... ...

'indexing' operator

Python lets us look at the individual characters in the string sequence using the indexing operator, represented by the square brackets operator [ ]. Python also allows indexing from the back end of the sequence. Thus, if you want to index from the string end, Python starts indexing the last character of the string with -1 and subtracts one from the index for each character to the left. >>> hello str = 'Hello World' >>> hello str 'Hello World' >>> hello str[0] # counting s t a r t s at zero 'H' >>> hello str[5] ' ' >>> hello str[-1] # negative index works back from the end 'd' >>> hello str[10] 'd'

Namespace

Python makes a list of names (variables, but other names as well) that are being used right now in the Python interpreter. The interpreter maintains a special structure called a namespace to keep this list of names and their associated values.

Continuation

Python provides ways to make long lines more readable by splitting them. Such splitting is called a continuation. If a single statement runs long, that statement can be continued onto another line (or lines) to help with readability. That is, a continued line is still a single line, it just shows up over multiple lines in the editor. You indicate a continuation by placing a backslash character (\) at the end of a line. Multiple-line expressions can be continued similarly. In this way, a long line that may be difficult to read can be split in some meaningful and readable way across multiple lines.

Augmented Assignment Operators

Python, like other languages, has shortcuts for operations—especially groups of operations—that are used repeatedly. The shortcut make typing easier and, at some point, make the code shorter and easier to read. Our first shortcut is the combination of an integer operation and the assignment sign (=). Shortcut Equivalence my_int += 2 my_int= my_int + 2 my_int -= 2 my_int = my_int - 2 my_int /= 2 my_int = my_int / 2 my_int *= 2 my_int = my_int * 2

Naming objects

Rules for naming: 1. Every name must begin with a letter or the underscore character ( _ ): - A numeral is not allowed as the first character.3 - Multiple-word names can be linked together using the underscore character ( _ ) e.g. monty_python_holy grail. A name starting with an underscore is often used by Python to denote a variable with special characteristics. You will see these as we go along, but for now it is best to not start variable names with an underscore until you understand what that implies. 2. After the first letter, the name may contain any combination of letters, numbers, and underscores: - The name cannot be a keyword - Delimiters, punctuation, or operators cannot be used in a name. 2 ibid1. 3. A name can be of any length. 4. UPPERCASE is different from lowercase: my_name is different than my_Name or My_Name or My_name.

Augmented assignment

Shortcuts can be distracting, but one that is often used is augmented assignment: ● combines an operation and reassignment to the same variable ● useful for increment/decrement Shortcut Equivalence num += 2 num = num + 2 num -= 2 num = num - 2 num /= 2 num = num / 2 num *= 2 num = num * 2

String Representation

Single-character strings, like all other data, are represented in a computer as numbers. The individual characters are stored in a special computer representation know as Unicode (UTF-8 is the Unicode default for Python 3). UTF-8, and any Unicode set in general, maps each character to an integer. By "map," we mean that in the UTF-8 set, each character is associated with a particular integer value. That integer is what gets stored in a computer, and Python labels its type as str. Example: Character Dec 'a' 97 'A' 65 @ 32 \ 92 'u' 117 'U' 85

Extended Slicing

Slicing allows a third parameter that specifies the step in the slice. This means that you can have as many as three numbers in the index operator brackets separated by two colon characters: the first number is the beginning of the sequence, the second number specifies the end of the sequence, and the third is the step to take along the sequence. If not indicated, the step number has a default of 1. Examples: >>> hello str = "Hello World" >>> hello str[::2] # every other l e t t e r in the slice 'HloWrd' >>> hello str[::3] # every third l e t t e r 'HlWl' >>> hello str[::-1] # step backwards from the end to the beginning 'dlroW olleH' >>> hello str[::-2] # backwards , every other letter 'drWolH' >>> >>> digits = "0123456789" >>> digits[::2] # even digits (default start at 0; skip every other ) '02468' >>> digits[1::2] # odd digits (start at 1; skip every other ) '13579' >>> digits[::-1] # reverse digits '9876543210' >>> digits[::-2] # reverse odds '97531' >>> digits[-2::-2] # reverse evens (start with 2nd last letter ) '86420'

The Triple-Quote String

Special kind of string denoted by triple quotes, as in '''Hello World'''. This, too, is a string, but it has one special property. This string preserves all the format information of the string. If the string spans multiple lines, those carriage returns between lines are preserved. If there are quotes, tabs, any information at all, it is preserved. In this way, you can capture a whole paragraph as a single string. Here is an example from The Zen of Python: zen_str = '''Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.'''The

Structure of for loops

Structure for i in range(5) print("I am wonderful") •Index variable is automatically set to zero •The first time through the loop our index has the value of 0. Next iteration it will be 1 then 2 then 3, etc. •After all the statements in the loop are executed, the control flows back to the start of the loop and checks that the index variable is still within the given range •If the condition is true, the statements in the body of the loop are executed again •If the condition is false, the control exits the loop and goes to the next section of code. Pseudocode total = 0 For i = 1 to 10: total = total + i Next i display total Python total = 0 For i in range(10): total = total + i print(str(total))

Structure of While loops

Structure while <condition>: <code goes here> •Program enters the while statement and evaluates the condition •If the condition for the loop is true then the program executes the statements in the body of the loop •After all the statements in the loop are executed, the control flows back to the start of the loop and checks the loop condition again •If the condition is true, the statements in the body of the loop are executed again •If the condition is false, the control exits the loop and goes to the next section of code

'import' function

The 'import' command allows Python to load modules into a program.

'while' statement

The 'while' statement allows us to repeat a suite of Python code as long as some condition (Boolean expression) is True. When the condition becomes False, repetition ends and control moves on to the code following the repetition. A 'while' statement is structurally similar to an 'if'. It consists of a header (which has the loop condition) and a 'suite' of statements. We can repeatedly execute the while suite as long as the associated condition is (True). The condition is, as was true with selection, a Boolean expression. We evaluate the condition and, if the condition is (True), we evaluate all of the 'while suite' code. At the end of that suite, we again evaluate the condition. If it is again True, we execute the entire suite again. The process repeats until the condition evaluates to False. The 'while loop' contains a Boolean decision that can be expressed in English as:

'id' function

The function 'id' returns the ID number of any object. The ID number is a system-dependent ID number. That number will be different from session to session or machine to machine. Example: >>> a_int = 7 >>> id(a_int) 16790848 >>> b_float = 2.5 >>> id(b float) 17397652 # note the two di f f e r e n t ID' s >>> a_int = b_float # associate a_int with value of b_float >>> id(a_int) 17397652 # a_int has the same ID as b_float

'type' function

The function 'type' returns the type of any object. >>> a_int = 7 >>> type(a_int) # a_int contains a type 'int' <class 'int'> >>> b float = 2.5 >>> type(b_float) # b_float contains a type 'float' <class 'float'> Most important, the type of an object has nothing to do with the variable name; instead it specifies only the object with which it is associated. >>> a_int = b_float # assign a_int with value of b_float >>> type(a int) <class 'float'> # a_int contains a type 'float'

Integers

The integer type is designated in Python as type 'int'. The integer type corresponds to our mathematical notion of integer. In Python, integers can grow to be as large as needed to store a value, and that value will be exact, but really big integers can be slower to operate on.

Two types of division

The standard division operator (/) yields a floating point result no matter the type of its operands: ● 2 / 3 yields 0.6666666666666666 ● 4.0 / 2 yields 2.0 ● Integer division (//) yields only the integer part of the divide (its type depends on its operands): ● 2 // 3 yields 0 ● 4.0 // 2 yields 2.0 ● 7 / 2 yields 3.5 (float) ● 7 // 2 yields 3 (int)

'for' Statement

The variable an element is a variable associated with the for loop that is assigned the value of an element in the collection. The variable an element is assigned a different element during each pass of the for loop. Eventually, an element will have been assigned to each element in the collection. The variable collection is a collection that has an associated iterator that acts as the source of elements. The keyword in precedes the collection. Like the 'if' and 'while' statement, the 'for' statement has a header and an associated suite. for element in collection: # for suite As with a 'while' loop, the entire for suite is evaluated during each pass of the loop. One can therefore perform operations on each element of a collection in a very straightforward way.The for loop completes when the last of the elements has been evaluated by the suite.

Naming Python variables

Variable names in Python follow the alphanumeric style •The rules of the style are: -A variable name may contain any letters (uppercase or lowercase), digits (0 to 9), and the underscore character -A variable name cannot start with a digit •Examples: _name = "bob" theAnswer = 42 my_pets_name = "bonbon"

Constructing New Values

There are also some operations associated with the type itself. One of the most useful of those operations is the constructor. A constructor is a special operation that is used to make a particular object of that type. Each type has an associated constructor: the constructor's name is the name of the type (int, float, str, . . .). If no value is provided within the parentheses, then a default value of that type is provided (for int it is 0; for float it is 0.0, for str it is ''). If a value is provided in the parentheses, then the constructor will convert that value to a new object of the specified type if it can. Thus, constructors can be used to convert one object to a new object of a different type. You have already seen conversion in examples: int(my_var) returns an integer representation of the object associated with my_var. - Note my_var itself is unaffected. The object associated with my_var is provided to the function int, a new object is created, the my_var object is converted to an int, and that new, converted object is returned. - If the object associated with my_var cannot be converted to an integer (say, the value ""), then an error will occur. float(my_var) returns a floating-point representation of the object associated with my_var. As with int, if the object cannot be converted to a floating-point number, then an error will occur. str(my_var) returns a string representation of the object associated with my_var. It is again important to note that 1 and "1" are very different. 1 is the integer 1. "1" is the character digit that gets typed on a keyboard.

Tokens

These are special keywords, symbols, and characters that can be used in a Python program. These special language elements are known generically as tokens. Examples: - keywords, operators, punctuators & delimiters and literals

While loops for error checking

This is a very standard error checking loop. You will need to use code like this very often in your programs. Pseudocode get value from user while value is less than zero: print an error display prompt get value display value Python code num = input ("Enter a number") while num < 0: print("Number is too small") num = input("Enter a number") print(str(num))

Python Variables

To get a variable in Python we just need to type the variable name and assign it a value with the '=' symbol (assignment operator) -We do not need to tell the computer the variable's data type -The variable's type will be determined by what type of value we store in it -We assign a value to a variable by saying: height = 1.65 message = "Hello World!" -Note that the equal sign here is not the same as in math. This is not an equation where both sides are equal -We are assigning a space in memory called height with the value 1.65 and a space called message with a greeting

Displaying variables

We can easily display a single thing using the 'print()' statement. •What if we want something more complex? -For example: •"The sum of 3 and 12 is 15" We can join things together in a string using 'concatenation', another word to add to our vocabulary -In planning we use '+' to indicate this: •display "The sum of " + num1 + " and " + num2 " is " + num3 -The Python symbol is + as well •print("The sum of " + str(num1)+ " and " + str(num2) " is " + str(num3)) -OR •print("The sum of", num1, "and", num2, "is", num3)

Mixed Types

What is the difference between 42 and 42.0 ? ● their types: the first is an integer, the second is a float What happens when you mix types: ● done so no information is lost 42 * 3 -> 126 42.0 * 3 -> 126.0

dot ( . ) operator

● the dot operator indicates that object on the right of dot is a member of object on the left Example: from kivy.app import App 'app' is a module within 'kivy' which is a package

If statement

an 'if' statement has a Boolean expression (or condition) that is evaluated, and the result of that Boolean expression dictates what happens next. 'if' boolean expression: # if suite(code executed if True) The basic 'if statement' allows you to do the following: 1. Evaluate boolean expression, yielding either (True) or (False). 2. If boolean expression yields (True), (a) Execute the Python suite of code indented under the if, the 'if suite'. (b) Once the indented code is executed, continue with any Python code after the indented code (that is, any code following the 'if' at the same indentation as the 'if' itself ). 3. If boolean expression yields (False), (a) Ignore any code indented under the if, (that is, do not execute it). (b) Continue with any Python code after the indented code (that is, any code following the if at the same indentation as the if itself ).

Assignment example

my_var = my_var + 1 The process is to evaluate everything in the expression on the right-hand side, get the value of that expression and assign it to the name on the left-hand side.

String methods

name = "David" name.upper() name.lower() name.capitalize() name.count() name.isalpha() Note: --> the parenthesis ( ) at the end of the method

Methods

● A method is a variation on a function: --> it has a name --> it has a list of arguments in parentheses ● However, methods differ in the way they are invoked ● every method is called in conjunction with a particular object ● The methods that can be used in conjunction with an object depends on the object's type ● The invocation is done using the dot ( . ) notation

Module

● A module is a file containing programs to solve particular problems; e.g., the math module Modules are files that can be imported into your Python program. ● use other, well proven code with yours Example is the math module ● we import a module to use its contents ● we use the name of the module as part of the content we imported

The memory model for Python is:

● A program contains variables and objects: --> A variable is a label that is assigned to one object --> An object holds a value, and every value has a type ● We can visualise the memory model as a diagram

Python name conventions

● All names must begin with a letter or underscore _: --> Ab_123 is OK, but 123_ABC is not. ● may contain letters, digits, and underscores: --> this_is_an_identifier_123 ● may be of any length ● upper and lower case letters are different: Length_Of_Rope is not length_of_rope ● names starting with _ (underline) have special meaning. Be careful!

Naming indices

● Exception to best practice: --> letters 'i', 'j' & 'k' which are industry standard defaults for 1st, 2nd & 3rd indices: >>> for i in range(5): print(i)

Strongly typed language

● Python is a strongly typed language: >>> age = 13 >>> name = "David" >>> age + name returns TypeError: unsupported operand type(s) for +: 'int' and 'str'

Example naming

● distance_in_metres reveals its intent better than distance ● using d to map to the concept of distance is even worse ● monthly_rainfall is more pronounable than mthly_rfall ● game_over is a poor name to represent that a game is running, since it implies another more obvious meaning ● However, is_game_over is a good name for a Boolean i.e. Y or N ● It's standard industry practice to use variable names such as i j inside loop constructs: for i in range(start, end): print(i)

Python "types"

● integers: 5 ● floats: 1.2 ● booleans: True ● strings: "anything" or 'something' ● lists: [] ['a',1,1.3] ● dictionaries: {} ['Jane': 23, 'Alan': 39] ● classes: class Shape: ● exceptions: NameError ● others we will see


संबंधित स्टडी सेट्स

ألصف العاشر - إمتحان ١

View Set

ECON 2113 Test 2 Review Homework Problems

View Set

What is the function of the following:

View Set

phys section 2 waves and their effects

View Set

International Marketing chapter 12

View Set

Generative Design for Additive Manufacturing

View Set

Special Tests for wrist and hand

View Set