software development test

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

What is //?

// Floor division (only integer part) ex=8//3 #2 (only get 2 not 2.666666666)

What is the result of 45 / 4?

11.25

What is the value of the following expression? 16 - 2 * 5 // 3 + 1

14

number = 6 cost = number * 2 if cost < 8 : cost = 8 cost = cost + 2 print(cost) What is displayed?

14

Rational Operators : Conditional expressions can be formed using the following operators : == != < > <= >=

Equal to Not equal to Less than Greater than Less than or equal to Greater than or equal to

Boolean: or

Evaluate two expressions. Evaluates to True if either of the two values is True. x = 10 y = 20 print(x == 3 or y == 20) • Truth table: #True A or B. Evaluates to True or True True True or False True False or True True False or False. False

If a single quote is a part of the string place string in _____ quotes. Double quoted strings can contain single quotes inside them: "Bruce's beard" ; not 'Bruce's beard' Using escape sequence (\") or (\'): 'Bruce\'s beard' Single quoted strings can have double quotes inside them: 'She said "Hi!"' ; not "She said "Hi!" "

double

Elif

elif allows you to give the program another condition to try. If none match then run else-block (optional). example : letter="c" if letter == "a": print ("Letter is a") elif letter == "b": else:print("Letter is b") print("Letter is not a or b")

Which of the following evaluates to TRUE? "pineapple" < "Peach" "apple" > "pineapple" "apple" in "Pineapple" "p" in "Pine"

"apple" in "Pineapple"

Python line comment begins with:

#

String Method Syntax • Python string method syntax example: word.upper() • This dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. What does this print? word = 'banana' new_word = word.upper() print(new_word) what does lower() do?

# BANANA takes a string and returns a new string with all lowercase letters.

List Comprehension vs for loop • E.g., to make a new list where each element is the result of some operation: squares = [] what is the outcome? for x in range(10): squares.append(x**2) print(squares)

# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] More concise list comprehension version: squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Python String Formatting • The following example formats a string using two variables and summarizes three string formatting options in Python. Explain each method name = 'Peter' age = 23 print('%s is %d years old' % (name, age)) print('{} is {} years old'.format(name, age)) print(f'{name} is {age} years old') • Each method gives the same output: Peter is 23 years old

# method 1 : - oldest option. uses the % operator and types such as %s and %d. # method 2 : - uses the format() function introduced in Python 3.0 to provide advanced formatting options. # method 3 : - newest option: python f-strings.

x =[18, 20, 25, 29, 31] The same indexing that we have used to read the elements of a list can be used to change them: x[3] = 26 x[-1] = 33 print(x) new result?

#[18, 20, 25, 26, 33]

Write the Python program using the following pseudocode. INPUT num_1 INPUT num_2 total <- num_1 + num_2 PRINT total

#coverts string input to int num_1 = int(input('Enter number one: ')) num_2 = int(input('Enter number two:')) total= num_1 + num_2 print(total)

num_4=num_1//num_2

#value of num_4 = 2

What is %?

% Modules - Returns remainder ex = result = 16%5

Function with Zero Parameters : def greet1(): print("Hello") • The function will only perform an operation when the function is ______. • This function can be ______ by .... # main program greet1() # Hello

'called' writing the function name followed by empty parentheses

What is the output? def add(a, b): return a+5, b+5 result = add(3, 2) print(result)

(8,7)

Range Ex: print("Counting Backwards") for i in range (10, 0, -1): print(i) what sequence of integers does it generate?

* Third argument specifies the sequence incrementation (step). • As well as positive numbers you can also program the computer to loop backwards with a negative number. • Sequence generated: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

For Loops - Also known as a count controlled loop - Repeats what two things?. - The loop ends when ..... it reaches the number of times it was set to loop.

- Repeats part of a program for a stated number of times. - Repeats its loop body for each element of the sequence in order. - it reaches the number of times it was set to loop.

Question - What is the output of the code snippet? i = 0 while i!= 9: print(i, end = " ") i = i + 2

0 2 4 6 8 10 12 .... (infinite loop)

break What will this example print? count = 0 while True: print(count) count += 1 if count >= 5: break

0,1,2,3,4

What is the output of the code snippet ? for i in range(1, 11): print(i, end = " ")

1 2 3 4 5 6 7 8 9 10

1. Create a list "mylist" containing integers : 1,2, 3, 4, 5 2. Print the second item in the list. 3. Use a negative index to print the second-to- last element. 4. Use list slicing to print the second to the fourth item in the list. E.g., [2, 3, 4] 5. Replace the first list item with the value 10. 6. Append the number 11 to the list.

1. mylist = [1, 2, 3, 4, 5] 2. print(mylist[1]) 3. print(mylist[-2]) 4. print(mylist[1:4]) 5. mylist[0]=10 6. mylist.append(11)

What is printed? for i in range(10, 12): for j in range(2, 4): print(i, j, end = " ")

10 2 10 3 11 2 11 3

How many times is the word HELLO printed by the following statements? s = "python rocks" for ch in s: print("HELLO")

12 empty space is a character

What is printed? mydict = {"cat":12, "dog":6, "elephant":23} mydict["mouse"] = mydict["cat"] + mydict["dog"] print(mydict["mouse"])

18, add the value for cat & value for dog (12 + 6) and create a new entry for mouse

What is printed? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} answer = mydict.get("cat") + mydict.get("dog") print(answer)

18, get returns value associated with a key (adds 12 and 6)

What is printed by the Python code? print('2' + '3')

23

Suppose list1 is [3, 22, 200, 10, 25], What is list1[-1] ?

25 Correct - [-1] is used -1 to access the last element

Suppose x is 1. What is x after x += 2?

3

x = 10 while x > 5: print("*") x = x - 2 How many stars are displayed by the code snippet above?

3

Which of the following expression results in a value 1?

37 % 6

What is printed by the following? alist = [4, 2, 8, 6, 5] alist.pop(2) alist.pop() print(alist)

4 2 6

What is the output? def b(): a = 99 #local variable a print(a) a = 42 print(a) #global variable a b() print(a)

42 99 42

What is printed? total = 0 mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} for akey in mydict: if len(akey) > 3: total = total + mydict[akey] print(total)

43, The for statement iterates over the keys. It adds the values of the keys that have length greater than 3.

The user enters 45. What is the output? number = int(input("Please enter a number: ")) if number < 100 : number = number + 5 if number < 500 : number = number - 2 if number > 15 : number = number + 1 else : number = number - 1 print(number)

49

sum = 2 while sum < 15: sum = sum + 3 print("*") Question - How many stars are displayed by the above code snippet?

5

What will be displayed by the following code? x = 2 def f1(): x = 5 print(x) f1() print(x)

5 2

What is printed? mydict = {"cat":12, "dog":6, "elephant":23} print(mydict["dog"])

6

What is the output of the following? print(len('Room 7:11'))

9

len() function returns the number of characters in a string. len('Monday PM') evaluates to?

9

Which of the following is a rational operator?

<=

What is the output of the following code? x = 'abcd' for i in x: print(i.upper())

A B C D

Set variables a=1 and b=2 Then write the instructions to swap them so the value in a ends up in b and the value in b ends up with a. Set variables a=1 and b=2. Write instructions to swap them.

A = 1, 1, 1 B= 2, 2, 1 1 #2 is replaced Need additional variable temp=b b=a a=temp

Function with return value : ? def mysum(a, b): return a + b #function call - returned value stored in variable result = mysum(3, 4) print(result)

A function that returns a value would normally assign the value to a variable or use it as part of an expression otherwise the return value is lost.

List Operations : Slices of a List

A list of temperatures, one per month: temp = [18, 21, 24, 33, 39, 40, 39, 36, 30, 22, 18] To obtain temperatures for the third quarter, with index values 6, 7, and 8 use the slice operator: thirdQuarter = temp[6 : 9] • To replace the values in elements 6, 7, and 8: temp[6 : 9] = [45, 44, 40] # [18, 21, 24, 33, 39, 40, 45, 44, 40, 22, 18] Which elements would the following slices obtain? temp[ : 6] temp[6 : ]

Which function is used to execute a query? A) execute() B) query() C) executequery() D) commit()

A) execute()

Which is true? a) An argument is a value passed to a function when the function is called. b) A parameter is a value passed to a function when the function is called. c) An argument is the variable listed inside the parentheses in a function definition d) A parameter is always a global variable.

A, An argument is a value passed to a function when the function is called.

Which of the following is a valid function header (first line of a function definition)? A. def drawCircle(t): B. def drawCircle: C. drawCircle(t, sz): D. def drawCircle(t, sz)

A, def drawCircle(t):

What happens if you give range only one argument? E.g., range(4) A. It will generate a sequence starting at 0, with every number included up to but not including the argument it was passed. B. It will generate a sequence starting at 1, with every number up to but not including the argument it was passed. C. It will generate a sequence starting at 1, with every number including the argument it was passed. D. It will cause an error: range always takes exactly 3 arguments.

A. It will generate a sequence starting at 0, with every number included up to but not including the argument it was passed.

List Operations : Amending/Extending

Add a single element to the end of a list with append() x = [18, 20, 25] print(len(x)) #3 x.append(29) print(x) #[18, 20, 25, 29] print(len(x)) #4 To append more than one element to the list use extend(): x = [18, 20, 25] print(x) #[18, 20, 25] x.extend([29,31]) print(x) #[18, 20, 25, 29, 31]

What will be the result of this code that manipulates a tuple? my_tuple = (1, 2, 3, 4) my_tuple.append( 5 ) print(len(my_tuple))

An excpection is thrown as tuples are immutable.

How does Python tell the difference between a string and boolean variable if the type is not declared?

As soon as you put quotes in front of something, it is a string.

What does the following code print? if 5 > 10: print("a") elif 8 != 9: print("b") else: print("c")

B

Which of the following will throw an error? D = [2, 3, 4, 3, 3, 3, 4, 5, 6] B = [[3, 3, 3] [4, 4, 4] [5, 5, 5]] C = [(1, 2, 4), (5, 6, 7), (8, 9, 10)] A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

B = [[3, 3, 3] [4, 4, 4] [5, 5, 5] Correct - Slices go up to, but not including, the number shown after the colon [ :-1]

Which of the following creates and connects to a new SQLite Database? A) import sql conn = sql.create("test.db") B) import sqlite3 conn = sqlite3.connect("test.db") C) import sqlite3 Conn = sqlite3.create("test.db") D) import sql conn = sql.connect("test.db")

B) import sqlite3 conn = sqlite3.connect("test.db")

What is printed? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} answer = mydict.get("cat") + mydict.get("dog") print(answer) A) 126 B) 18 C) catdog D) Error, + is not a valid on dictionaries

B, 18 gets return value associated with a key (adds 12+6)

What is printed? total = 0 mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} for akey in mydict: if len(akey) > 3: total = total + mydict[akey] print(total) A) 18 B) 43 C) 0 D) 61

B, 43 The for statement iterates over the keys. It adds values of the keys that have length greater than 3 so, it adds elephant and bear which equals 43

What is printed? mydict = {"cat":12, "dog":6, "elephant":23} print(mydict["dog"]) A) True B) 6 C) dog : 6 D) Error

B, 6 : is associated with the key

What will be displayed by the following code? print("B", end = ' ') print("C", end = ' ') print("D", end = ' ')

BCD or B C D (e.g., on one line)

User Defined Functions : special variable called __name__

Before the Python interpreter executes a program, it defines a special variable called __name__ and sets the value to: * "__main__" when the program is being executed by itself. * Or the module name if the program is being imported by another program. Therefore, we can use an if statement to check if the program is standalone (value is "__main__") or being used by another program. Then select to execute code based on value. if __name__ == "__main__": main()

What is printed? mydict = {"cat":12, "dog":6, "elephant":23} mydict["mouse"] = mydict["cat"] + mydict["dog"] print(mydict["mouse"]) A) 12 B) 0 C) 18 D) Error - no mouse key

C, 18 : add the value for cat and dog (12+6) and create a new entry for mouse

Python f-strings - Which of the following statements is FALSE? a) 'f-strings' is short for formatted string literals b) This is an example of an f-string: print(f'{name} is {age} years old') c) This is an example of an f-string: print('{} is {} years old'.format(name, age)) d) f-strings have been available since Python 3.6

C, This is an example of an f-string: print('{} is {} years old'.format(name, age))

Which of the following function headers is valid? a) def f(a = 1, b): b) def f(a = 1, b, c = 2): c) def f(a, b = 1, c = 2): d) def f(a = 1, b = 1, c = 2, d):

C, def f(a, b = 1, c = 2):

What is printed? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} keylist = list(mydict.keys()) keylist.sort() print(keylist[3]) A) cat B) dog C) elephant D) bear

C, elephant line 2 : keys() returns a view of its underlying keys. the view is converted into a list of keys with list() line 3: sorts the list of keys. line 4: the item at index 3 is printed

Which of the following is NOT valid Cursor methods used to retrieve query results? A) fetchall() B) fetchone() C) fetchmany()

C, fetchmany() You can retrieve query results using the fetchone() and fetchall() methods.

elif (Example 2) a=int(input()) if a == 10: print('a is equal to ten') elif a<10: print('a is less than 10') else: print('this should never print!')

Can use multiple elifs Test conditions for the first match. Only the first true branch runs (even if other conditions true). • If none match then run else-block (optional).

___________ _________ give us the ability to write programs that do different things based on different conditions. Examples?

Conditional statements - if - if-else - elif

Which function is used to save a change permanently ? A) save() B) close() C) execute() D) commit()

D) commit

Function Default Arguments

Defaults values can be provided. E.g., inc is assigned 1 in the parameter list: def my_function(start, stop, inc=1): print(f'start= {start}, stop= {stop}, inc= {inc}') • When calling the function, the third argument is now optional. However, the default value can be overridden. Place these at the end of the parameter list. a = my_function(1, 10, 5) # start= 1, stop= 10, inc= 5 a = my_function(1, 10) # start= 1, stop= 10, inc= 1 Example 2: If function called without an argument use default value . def my_country(country = "UK"): print("I am from " + country) my_country("Spain") my_country("India") my_country() Note: default parameters MUST always go after non-default parameters You have met default arguments in use before. E.g., The print function uses end='\n'as a default value. ◦ We can customize the value of end to suppress printing a new line, by using end=' ' print('Dog', end=' ' ) print('Cat')

What is printed? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} keylist = list(mydict.keys()) keylist.sort() print(keylist[3])

Elephant, bc Line 2: keys() returns a view of its underlying keys. The view is converted into a list of keys with list(). Line 3: sorts the list of keys. Line 4: the item at index 3 is printed

What is printed by the following statements: s = "Fall" s[0] = "B" print(s)

Error

What is printed by the following statements: s = "Ball" s[0] = "C" print(s) a) Ball b) Call c) Error

Error bc strings are mutable

Boolean: and

Evaluate two expressions. Evaluates to True if both of the two values are True. x = 10 y = 20 print(x == 10 and y == 20) #True example: This program validates user input x=int(input("Enter a number between 1 and 100:")) if x>=1 and x<=100: print("Valid number") else:print("Your number is not valid") • Trace which lines would be printed for x: 0, 1, 100, 101

Augmented Assignment Operator : +=

Example Equal to x+= 3 x=x+3

Augmented Assignment Operator : *=

Example Equal to x*=4 x=x*4

Augmented Assignment Operator : -=

Example Equal to x-=2 x=x-2

Augmented Assignment Operator : /=

Example Equal to x/=5 x=x/5

Example Pseudocode: Calculate the average of three numbers

Example pseudocode: INPUT num_1 INPUT num_2 INPUT num_3 average <- (num_1 + num_2 + num_3) / 3 PRINT average

What is **?

Exponent ex= answer = 4**2 (4 to the power of 2)

What is printed - True or False? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print(23 in mydict)

False, key is NOT in dictionary

What is printed - True or False? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print(23 in mydict)

False, key is not in dictionary or key. 23 is a value

Key commands for working with Python and databases : db = sqlite3.connect(<database name>) : ? cursor = db.cursor() : ? cursor.execute(<sql statements>) : ? db.commit() : ? db.close() : ?

Forms the connection with the database. If the file exists, it opens it. If the file does not exist, it creates it. To execute SQLite statements in Python, you need a cursor object created by using the cursor() method. Used to execute a SQL statement. Save (commit) the changes permanently. Closes the database connection. Need to commit() first or you changes will be lost.

Match the code with the correct output : pizza = 'Hawaiian' print(pizza[0]) print(pizza[:5]) print(pizza[0:2]) print("pizza[6]") print(pizza) print(pizza[6]) print(pizza[2:4]) print(pizza[3:])

H Hawai Ha pizza[6] Hawaiian a wa aiian

List Operations : Insert an Element at a specific position • Sometimes the order in which elements are added to a list is important • A new element has to be inserted at a specific position in the list: Ex : #1 friends = ["Harry", "Emily", "Bob", "Cari"] The created list : .... #2 friends.insert(1, "Cindy")

Harry Emily Bob Cari The new list : Harry Cindy Emily Bob Cari

List Elements In some languages the elements of a list have to be of the same type. Is this the same in Python? • Lists inside lists are known as ______ lists.

However, in Python, the list elements can be any type. [10, 20, 30, 40] ['apple', 'pear', 'banana'] And can be mixed type: ['spam', 2.0, 5, [10, 20]] • a string, a float, an integer, and another list nested

Global vs Local Variable

If a variable is defined outside of any function, it is a global variable. If a variable is defined anywhere within a function, it is a local variable. def square(x): y=x*y #y is local to function only return y z = square(10) print(y) # Error Variable y only exists while the function is being executed (its lifetime). Parameters are also local - lifetime of x begins when square() is called, and ends when the function completes its execution

List Operations : Finding an Element

In operator - to know whether an element is present in a list: x =[18, 20, 25, 29, 31] print("18 in x?", 18 in x) #True print("19 in x?", 19 in x) #False print("31 in x?", 31 in x) #True print("31 not in x?", 31 not in x) #False Use the index() method to know the position at which an element occurs . Yields the index of the first match print("Index of 18:", x.index(18)) # 0 print("Index of 25:", x.index(25)) # 2

Both lists and strings are sequences, and the [ ] operator is used to access an element in any sequence. There are two differences between lists and strings : What are they?

Lists can hold values of any type, whereas strings are sequences of characters. Strings are immutable - you cannot change the characters in the sequence: greeting = "Hello, world!" greeting[0] = 'J' # ERROR! • Lists are mutable: numbers = [42, 123] numbers[1] = 5 # [42, 5]

SQLite and Python types : SQLite supports the following types: ____, ______, ____, ____, ____. The following table shows how the SQLite types map to the corresponding Python types.

NULL, INTEGER, REAL, TEXTr NULL - None INTEGER - int REAL - float TEXT - str BQ - bytes

What is the outcome of running this program? def fun1(num): return num + 25 fun1(5) print(num)

NameError

What will the following function return? def addEm(x, y, z): print(x + y + z)

None

What is the output of the following code? for char in 'PYTHON STRING': if char == ' ': break if char == 'O': continue print(char, end='')

PYTHN

Dictionary Method : Items()

Returns a view of the key-value pairs in the dictionary Method items() returns a list of tuples, one tuple for each key:value list(eng2sp.items()) #[('one', 'uno'), ('two', 'dos'), ('three', 'tres')] • Tuples are useful for getting both the key and the value while looping: for (k,v) in eng2sp.items(): print("Got",k,"that maps to",v) Output: Got one that maps to uno Got two that maps to dos Got three that maps to tres

Dictionary Method : Keys

Returns a view of the keys in the dictionary Iterating over the view: eng2sp = {"one":"uno", "two":"dos", "three":"tres"} for k in eng2sp.keys(): print("Got key", k, "maps to value", eng2sp[k]) Output: Got key one maps to value uno Got key two maps to value dos Got key three maps to value tres • We can turn the view into a list by using the list conversion function. ks = list(eng2sp.keys()) print(ks) #['one', 'two', 'three'] • We can omit the keys method call in the for loop — iterating over a dictionary implicitly iterates over its keys: for k in eng2sp: print("Got key", k)

Dictionary Method : Values ()

Returns a view of the values in the dictionary • The values method is similar; it returns a view which can be turned into a list: list(eng2sp.values()) #['uno', 'dos', 'tres']

To create a table we use the ____ ______ _______ _______. Then we use the ______________ statement for the SQL to be carried out.

SQL Create Table Command cursor.execute() Example: Creating the film table import sqlite3 #Import sqlite3 library db = sqlite3.connect("film.db") # Create Connection object cursor = db.cursor() # Create Cursor object

Range Ex: range(1,7) what sequence of integers does it generate?

Sequence generated: 1,2,3,4,5,6 (setting the start number to 1)

What is the error in this statement: if scoreA = scoreB : print("Tie")

Should be compared with == not =

What does SQL stand for?

Structured Query Language

What happens if a program is processing user input and the user enters the wrong type of data?

The 'try/except' construct can prevent the program crashing with an error. Exception: An error that occurs at runtime. Handle an exception by wrapping the block of code in a try . . . except construct. Syntax: try: Python commands except: Exception handler

In general, you can't perform mathematical operations on strings : '2' - '1' #illegal Two exceptions follow...

The + operator performs string concatenation. e.g. : first = 'throat' second = 'warbler' third = first + second #throatwarbler The * operator performs repetition on strings 'Spam' * 3 : #SpamSpamSpam

Python's Use of Indentation for While Loops

The Python indentation for the while "block" is not cosmetic. A sequence of lines that have the same indentation forms a block. Here, both lines get run or neither of them do. The block is ended by the first line that follows it with no indentation. number = 0 while number < 10 : print(number) number = number + 1 print('Done!') The indentation indicates a "block" of code. The first non- indented line marks the end of the block.

Suppose you want to write a condition statement with multiple alternatives to print out the single tax bracket that someone is in, based on their income. Assume the variable income holds the annual income. What is wrong with the following ? if income < 10000: print('Lowest tax bracket') if income < 20000: print('Middle tax bracket') if income < 30000: print('High tax bracket')

The conditions should use elif conditionals

Pass Statement

The pass statement in Python is used as a temporary placeholder for future code. E.g., for a Python function that will be fully implemented at a later time. Nothing happens when it executes, but it avoids errors where empty code is not allowed. Empty code is not allowed in function definitions, loops and if statements. def my_function(): pass

Where to Place Function Definitions res = return_sum(4,5) def return_sum(x,y): return x + y What will be the outcome of the program?

This will cause: NameError: name 'return_sum' is not defined You need to define your function before you call it. Put your functions at the start of programs, below any import statements, to avoid issues.

why do we use a cursor object?

To execute SQL queries

The in expression is a logical expression and returns ... There is also a not in operator. 'x' not in 'apple'

True or False and can be used in an if statement if 'a' in fruit : print ('Found it!') #Found it!

What is printed - True or False? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print("dog" in mydict)

True, key is in dictionary

If-Else Statement

Two Outcomes - Get the program to do something if statement is false. Get the program to do something if statement is false using "else" keyword. a = int(input('Enter number: ')) if a == 10: print('a is equal to ten') else:print('a is not equal to ten') print('Not in the if or else block') Print first message if expression is true, otherwise print second message.

Assign a variable question with the value: Where's the lecture room?

Two solutions: question = "Where's the lecture room?" question = 'Where\'s the lecture room?'

Can we work with dictionaries in f-strings?

We can work with dictionaries in f-strings. user = {'name': 'John Doe', 'occupation': 'gardener'} print(f"{user['name']} is a {user['occupation']}") • The example evaluates a dictionary in an f-string. Output: John Doe is a gardener

What is the output of the following code? def myFunc(message, num = 1): print(message * num) myFunc('Welcome') myFunc('Hello', 3)

Welcome HelloHelloHello

What will be the output of the following program? my_list = ["Westminster", [2, 4, 8, 16]] print(my_list[0]) print(my_list[0][1]) print(my_list[1][3])

Westminster e 16 0 - westminster 0- element westminster but first which is e 1- element 2,4,8,16 but 16 is 3rd bc 2 is 0

List Operations : Sorting The sort() method sorts a list of numbers or strings. It modifies the list. values = [1, 16, 9, 4] values.sort() x.sort(reverse=True) #descending print(values) #[23, 19, 17, 13, 11] What is the new value?

[1, 4, 9, 16] • The sorted() method creates a new list containing a sorted version of the list. The original list is unsorted. values = [1, 16, 9, 4] sorted(values) #[1, 4 , 9, 16] print(values) #[1, 16, 9, 4]

What is printed? numbers = [3, 4, 5, 20, 5, 10, 2] numbers.pop(4) print(numbers) numbers.pop() print(numbers)

[3, 4, 5, 20, 10, 2] [3, 4, 5, 20, 10] Correct - pop() removes an element at a given position or the last element if an index is not given.

What is printed? alist = [4, 2, 8, 6, 5] alist.append(True) alist.append(False) print(alist)

[4, 2, 8, 6, 5, True, False] Correct - Add a single element to the end of a list with append()

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] What is the value of: A[1]

[4, 5, 6] Correct - accessing elements in a nested list.

What is printed? alist = [4, 2, 8, 6, 5] alist.insert(1, False) print(alist)

[4, False, 2, 8, 6, 5] Correct - insert Boolean False at index 1

What will be displayed by the following code? a = [1, 3] b = a a[0] = 7 print(b)

[7,3] Correct - The code b = a results in both a and b referencing the same list so that you modify the list through either a or b.

Common escape sequences: ignores what's behind it

\\ : literal backslash \' : single quote \" : double quote \n : Newline \t : Tab

Exception Handling in Python - Example

a = "1" try: b = a + 2 except: print (a, " is not a number") • We try to add a number and a string (generates an exception). We trap the exception let the user know instead of letting the program crash. • The above does not specify a specific exception (error) to handle, so can be used for any errors that occur while executing these commands

What is the output of the following code? x = 'abcd' for i in x: i.upper() print(x)

a b c d

Dictionary - Del statement • The del statement removes .... ex?

a key:value pair. E.g., dictionary contains fruits and number of each fruit in stock: stock = {"apples": 430, "bananas": 312, "pears": 217} • If all pears are bought - remove the entry from the dictionary: del stock["pears"] print(stock) # {'apples': 430, 'bananas': 312}

nested iteration- for i in range(3): print(i) • We know the value of i will be 0, then 1, then 2. The print will be performed once for each pass. • A nested iteration is ... a • We could call these the _____ iteration and the _____ iteration.

a loop within a loop. e.g. for i in range(3): for j in range(2): print(i,j) outer & inner

A function is a ....

a piece of code written to carry out a specific task.

In Python, how do you create a variable "a" that is equal to 2?

a=2

Format specifiers are specified after ? • width specifier sets ____ for x in range(1, 6): print(f'{x:02} {x*x:3} {x*x*x:4}') • The example prints three columns. Each of the columns has a predefined width. The first column adds a leading 0 is the value is shorter than the specified width (the other columns use spaces). Output: 01 1 1 02 4 8 03. 9 27 04 16 64 05 25 125

after the colon character the width of the value. The value may be filled with spaces or other characters if the value is shorter than the specified width.

In-Place Algorithms Changing information via index is different. An index works via memory location and not by reference. Changing a list item in a list by the index location will ....

alter the original variable

slicing ([:]) A slice is a substring of a string. 'bananas and cream'[3:6] evaluates to? bananas and cream'[1:4] evaluates to?

ana ana

Booleans operators

and or not

Nested List A nested list is a list that ...

appears as an element in another list. in this list, the element with index 3 is a nested list: nested = ["hello", 2.0, 5, [10, 20]] If we output the element at index 3, we get: print(nested[3]) # [10, 20] To extract an element from the nested list: nested[3][1] # 20 This expression gets the 3'th element of nested and extracts the 1'th element from it.

Argument vs Parameter

argument: A value passed to a function when a function is called. parameter: the variable listed inside the parentheses in the function definition - used to refer to the value passed to it. ex : def mysum(a, b): print(a + b) mysum(3, 4) # call function This function assigns the arguments 3 and 4 to the parameters a and b.

2. Which is correct : a, b or c? a) age < 17 or > 150. #don't drive b) age < 17 or age > 150. #don't drive c) age < 17 and age > 150. #don't drive

b) age < 17 or age > 150

Variables must ...

begin with the letter (a-z, A-Z) or underscore (_) other characters can be letters, numbers, or _ variable names are case sensitive. These are different variables: case_sensitive, CASE_SENSITIVE, Case_Sensitive Must not have spaces inside of them (e.g. 'running total' not allowed)

Python provides the _______ ____ that can be either set to True or False. E.g., finished = True

boolean type A boolean expression evaluates to one of two states # the operator == tests if two values are equal print(5 == 5) # produces True print(5 == 6) # produces False

Traversal with a for loop: By Item • Python has a version of the for loop that operates exclusively on strings. We can replace the range() function as shown in Example 1: fruit = "banana" for letter in fruit: print(letter) * Each time through the loop, the next character in the string is assigned to a variable letter until no characters are left. Example 2: s = "python rocks" for ch in s: print(ch)

both of these produce : b a n a n a p y t h o n r o c k s

Which statement is used to stop a loop?

break

Which of the following statements will result in the output: 6? a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] a) a[2][3] b) a[2][1] c) a[1][2] d) a[3][2]

c, a[1][2] Correct - accessing elements in a nested list.

String Methods Method Parameters Description capitalize none = strip none = count item = replace old, new = find item =

capitalize : returns a string with first character capitalized, rest lower strip : returns a string with the leading and trailing whitespace removed count : returns the number of occurrences of item replace : replaces all occurrences of old substring with new find : returns the leftmost index where substring found or -1 if not found

Python is ____ sensitive. Use print() rather than Print() or PRINT() Ex : print('Hello') print(42) greeting = 'Hello' print(greeting)

case

Conditional Execution

check for condition and run appropriate code.

Database Terms : • Table - ? • Primary Key - ?

collection of related data held in a table format within a database. Database tables consist of rows and columns used to uniquely identify a record in a table

Lists are used to store multiple items in a single variable. Each value has its index (starting at zero) and can appear in the list multiple times. A list is defined as a ....

comma-separated list of values, enclosed in square brackets: x =[18, 20, 25, 29, 31]

SQL - the language of databases • SQL is a standard language for .... • SQL stands for ? • SQL can be pronounced as both sequel or S-Q-L. • It is independent of the programming language we are using (in this case Python). • Is it case-sensitive?

communicating with databases by carrying out queries structured query language no

A string is a sequence of characters A string literal uses quotes 'Hello' or "Hello" For strings, + means __________ When a string contains numbers, it is still a string We can convert numbers in a string into a number using ____

concentrate int()

List comprehensions provide .... Syntax: [expression for variable_name in iterable] • Each element of iterable (e.g., list, tuple, range etc) is taken out as variable_name and evaluated by expression to create a new list. squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

concise way to create lists.

If you need to break out of a loop there are two important keywords: Explain them.

continue and break • Continue- when it gets executed the loop will stop the current iteration where it is without executing anything after the continue statement and go on to the next iteration of the loop. • Break- when it gets executed it will break out of the loop and continue executing from the first instruction after the loop.

If you expect the user to type an integer, .... int() returns an integer so you need to save the result into a _________. prompt = 'What is 38 plus 5?\n' answer = input(prompt) answer = int(answer)

convert the value to integer variable

• float() function converts .... a = float(32) # 32.0 b = float('3.14159') # 3.14159

converts integers and strings to floating-point numbers:

int() function takes any value and ..... a = int('32') # a is integer 32 b = int('Hello') # produces an error • int() function can convert floating-point values to integers, but it doesn't round off; it chops off the fraction part: c = int(3.99999) # c ______________ d = int(-2.3) # d ______________

converts it, if it can, to an integer:

• str() function converts .... c = str(32) # '32' d = str(3.14159) # '3.14159'

converts its argument to a string:

Write the program to store 5 into cost, then add 3 onto cost and store the answer back in cost.

cost <- 5 cost <- cost + 3

Write the Python program using the following pseudocode. INPUT cost_of_item INPUT cash_paid (e.g., 10 for £10) CALCULATE change PRINT change

cost = float(input("Enter cost of item: ")) paid = float(input("Enter cash paid: ")) change = paid - cost print("Change is ", change)

Common Error : Off-By-One-Error

counter = 0 while counter < 10 : # Executes 10 passes <do something> counter = counter + 1 counter = 1 while counter <= 10 : # Executes 10 passes <do something> counter = counter + 1 counter = 1 while counter < 10 : # Executes 9 passes <do something> counter = counter + 1 counter = 0 while counter <= 10 : # Executes 11 passes <do something> counter = counter + 1

Common Error : Infinite Loops

counter = 1 while counter <= 10 : print(counter) counter = counter + 2 Executes 5 phases counter = 1 while counter != 10 : print(counter) counter = counter + 2 Runs Forever counter = 1 while counter != 9 : print(counter) counter = counter + 2 Runs forever counter not updated in loop body

What can you do since you can't change an existing string? ex?

create a new string as a variation of original: greeting = 'Hello, world!' new_greeting = 'J' + greeting[1:] print(new_greeting) # Jello, world! print(greeting) # Hello, world! Example concatenates a new first letter onto a slice of greeting (original string remains the same).

The range() function can be used to ? create a sequence of numbers. • The structure of the function is range what? Explain (start, stop, step).

create a sequence of numbers. (start, stop, step). o start (optional): starting number of sequence. The default is 0. o stop: generate sequence up to, but not including the specified number. o step (optional): number specifies the sequence incrementation. The default is 1. • The augments, start, stop, and step, must be integers.

An assignment statement ... message = 'Something completely different' n = 17 pi = 3.141592653589793

creates a variable and gives it a value. The first assigns a string to a variable named message; The second assigns the integer 17 to variable n; The third assigns the (approximate) value of (pi symbol) to variable pi

Syntax A Python function is defined using the ___ keyword, followed by the ________ ____, followed by ___________ ending with a _____. __________ are optional. The _____________ may contain a list of _______ (as shown) or be empty (as shown below). The code to be executed by the function is _______.

def function name parentheses () colon parameters parentheses () indented ex : with parameters : def function_name(parameter1, parameter2, ... parameterN): function_block without parameters : def function_name(): function_block

Write a function that returns the maximum of two numbers.

def max_of_two (x,y) : if x>y: return x return y max= max_of_two(4,1) print(max)

Output

display on the screen, save to file/database ect

Print() function Multiple objects separated by commas print separated by a space: print('dog', 'cat', 42) # dog cat 42 To suppress printing of a new line, use _____ print('Dog', end='') print('Cat') # DogCat

end=' ' :

What is the keyword used after the try statement to handle exceptions?

except

As programs get more complicated, add comments to your programs to ... Comments most useful when they document non-obvious code features.

explain what the program is doing. Python uses # symbols Everything from the # to the end of the line is ignored.

Give the opposite of the condition floor > 13

floor <= 13

In Python, for loops are constructed like this: for [iterating variable] in [sequence]: [do something] • The ___ and __ are key words that are inbuilt commands. • The iterating variable will hold the values of the generated sequence which is stepped through. E.g., for i in range(10): print(i)

for, in

len() - function does what? The in expression is a logical expression and returns True or False and can be used in an if statement if 'a' in fruit : print ('Found it!') #Found it!

function returns the number of characters in string: fruit = 'banana' length = len(fruit) # 6 Remember, there is no letter in the sting with the index 6 (only 0 to 5). To get the last character, you have to subtract 1 from length: last = fruit[length-1] #a *can start from -1 to -6

Input

get data from the keyboard/file/database ect.

• A sentinel value can .... What value will end this loop? salary = 0.0 while salary >= 0 : salary = float(input()) if salary >= 0 : total = total + salary count = count + 1

guarantee termination of a loop when processing sequential data. The sentinel value can detect the end of the data set when there is no other means to do so. It denotes the end of a data set, but it is not part of the data. -1 will end the loop

The following code would cause an error: x =[18, 20, 25, 29, 31] print("Index of 35:", x.index(35)) # # ValueError: 35 is not in list What additional code could you use to ensure that an error is not displayed?

if 35 in x : print("Index of 35:", x.index(35)) else: print("35 is not in x")

Amend the above to display a message for high marks (70 or above) mark = int(input('Enter Mark')) if mark >= 40: print('Satisfactory result') else: print('You have failed') Add an additional condition at the start of the program to check if the exam mark is invalid (less than 0 or greater than 100):

if mark < 0 or mark > 100: Print('Invalid mark') elif mark >= 70: print('Exceptional result') elif mark >= 40: print('Satisfactory result') else: print('You have failed')

How would you cast the string variable "a" that is equal to "2" into the integer 2?

int(a)

Write the code to put 4 into a variable called 'item 1'. Then put 6 into a variable called 'item 2'. Then write an instruction to add the two variable values together and put the answer into a variable 'item 3'

item_1 = 4 item_2 = 6 item_3 = item_1 + item_2

To use an existing built-in function, you need to know its ..... print() function= ?

its name, inputs, and outputs. print() function - send content to screen

Different languages have different naming conventions for variables (e.g. Camelcase). For Python, it is recommended to use .....

lowercase with multiple words separated with underscores. ex : your_name airspeed_of_unladen_swallow

Write a program to display "FAIL" if the mark entered is less than 40, otherwise it should display "PASS".

mark = int(input("Enter your mark:")) if mark < 40 : print ("You failed") else: print ("You passed")

A meal costs 56 pounds. Write the code to set 56 into a variable. Then multiply whatever is in the variable by 1/10 to work out the 10% tip (store the answer in a variable).

meal = 56 # is $56 possible tip = meal * 1/10

Dictionaries - Aliasing and Copying • As with lists, dictionaries are ______ - be aware of aliasing. Whenever two variables refer to the same object, changes to one affect the other. • To modify a dictionary and keep a copy of the original, use copy(). opposites = {"up": "down", "right": "wrong", "yes": "no"} alias = opposites copy = opposites.copy() • alias and opposites refer to the same object. If we modify alias, opposites is also changed. However, if we modify copy, opposites is unchanged.

mutable

Dictionaries are like lists - they are both _______. To change a value: stock["pears"] = 0 print(stock) # {'apples': 430, 'bananas': 312, 'pears': 0} • A new shipment of bananas could be handled like this: stock["bananas"] += 200 print(stock) # {'apples': 430, 'bananas': 512, 'pears': 0}

mutable To change a value: stock["pears"] = 0 print(stock) # {'apples': 430, 'bananas': 312, 'pears': 0} • A new shipment of bananas could be handled like this: stock["bananas"] += 200 print(stock) # {'apples': 430, 'bananas': 512, 'pears': 0}

If I wanted to capitalize the first letter of the string name = "caterina", and change the value of name, what line of code would I write?

name = name.capitalize()

What will be the output of the following code snippet? token = False while token: print('Hello')

no ouput

SQLite • SQLite can be used with many programming languages. • Does SQLite require a server to run? • Provides a local database to do what? • sqlite3 comes with Python. What are the key SQL commands that you need to know?

no, it is server-less store data Create Table Select ... From ... Where Insert Into Update Delete

Which of the following expressions checks whether a value for the num variable is either less than 100 or more than 200?

num < 100 or num > 200

Which of the following expressions checks whether a value assigned to the num variable falls in the range 100 to 200?

num>=100 and num<=200

Write the program to calculate the average of 3 numbers. Pseudocode: INPUT num_1 INPUT num_2 INPUT num_3 average <- (num_1 + num_2 + num_3) / 3 PRINT average

num_1=int(input("Enter the first number: ")) num_2=int(input("Enter the second number: ")) num_3=int(input("Enter the third number: ")) Average = (num_1 + num_2 + num_3 / 3) print("The average is: ", average)

Write the program: A number a user enters is stored in a variable called number. • Check if the number is equal to 10. • If true, display message 'number is equal to 10'.

number = int(input()) if number == 10: print('number is equal to 10') Remember the colon after the if condition. Remember to indent the next line. Indentations are used in programming to make it easier to read but in Python it also affects the code's meaning.

The in keyword can be used to check to see if ....

one string is "in" another string ex : fruit = 'banana' #True 'n' in fruit #True 'm' in fruit #False 'nan' in fruit #True

• continue What will this print? for x in range(10): if x % 2 == 0: continue print(x)

only odd numbers 1,3,5,7,9

Math

perform basic mathematical operations

Pseudocode : Write a program to get and print the number of pets a user has.

pets=int(input('Enter number of pets: ")) print(pets)

What are the four Python built-in functions?

print() input() str() int()

user-defined functions : printing vs return

printing vs return def mysum(a, b): print(a + b) mysum(3, 4) # call function • The value of 7 is printed from within the function but is not available to work with later. ------------------------------------------------------------------------------------------------------------------------ def mysum(a, b): return a + b result = mysum(3, 4) # call function Here we have a value stored in variable result and it is available to work on later in the program.

There is a problem with this program. Track down where the problem is by tracing your program's execution. health = 10 trolls = 0 damage = 3 while health != 0: trolls += 1 health -= damage print("Hero defeats a troll, ") print("but takes", damage, "damage points.") print("Hero lost but defeated ", trolls, " trolls.")

problem : health != 0 will never be true - Infinite Loop! Rewrite condition: while health >= 0

Keyboard input - input() function Typical flow of a simple computer program 1. Input data 2.Work with data 3. Output answer/s. input() function - text = input() • input() can take text as an argument (e.g., a prompt stating what input is expected): name = input('What...is your name?\n') Note: \n represents a newline (line break) so that any user input will appear below the prompt message.

program stops and waits for the user input. When the user presses Return or Enter, the input is returned to the program as a string.

Which of the following returns a sequence 0, 1, 2, 3?

range(0,4)

What command correctly generates the sequence 2, 5, 8?

range(2, 10, 3)

Which range function call will produce the sequence 20, 15, 10, 5?

range(20, 3, -5)

How do you loop through the list items in values?

refer to their index number. use the range() and len() functions to create the iterable. for i in range(len(values)) : print(i, values[i]) or print all items in the list, one by one: for element in values : print(element)

List Operations : pop() and remove() pop() : pop() - with an empty parameter will .... remove() - if you do not know the index, this will remove....

removes the element at a given position (if you know the index of the element.) remove the last element q = ['a', 'b', 'c', 'd'] q.pop(1) print(q) # ['a', 'c', 'd'] q.pop() print(q) # ['a', 'c'] the first matching element. q = ['a', 'b', 'c', 'd'] q.remove('b') print(q) # ['a', 'c', 'd']

Multiple return values When you need to return more than one piece of data, you would return a collection of data: def returnMultiple(): a=5 b = 10 return [a, b] # data type holding multiple items What type of collection would the following return?

return a, b

What does the len(_) function do?

returns the number of characters in string: fruit = 'banana' length = len(fruit) # 6 Remember, there is no letter in the sting with the index 6 (only 0 to 5). To get the last character, you have to subtract 1 from length: last = fruit[length-1] #a Or use negative indices, which count backward from the end of the string. E.g., fruit[-1]yields the last letter, fruit[-2] yields second to last.

Functions provide (black boxes of) functionality : 1. 2. 3. They are ....

reusable code easier to debug easier to read/maintain named sequence of statements that performs some useful operation. May take arguments and may produce a result.

Write pseudocode to put zero into variable running_total. Then write separate instructions to add the following numbers onto what is in the variable, adding one number at a time 5, 8, 2, 3. Print running_total.

running_total <-0 (OR set_running_total <-0) running_total <- running_total + 5 running_total <- running_total + 8 running_total <- running_total + 2 running_total <- running_total + 3 PRINT running_total

indexing - Access a character in a string using its index position. 'Was'[2] evaluates to?

s

List Operations : Copying Lists • List variables do not themselves hold list elements • They hold a reference to the actual list • If you copy the reference, you get another reference to the same list: • When you copy a list variable into another, both variables refer to the same list • The second variable is an alias for the first because both variables reference the same list scores = [10, 9, 7, 4, 5] values = scores #Copying list reference A list variable specifies the location of a list. Copying the reference yields a second reference to the same list. Modifying Aliased Lists • You can modify the list through either of the variables: scores[3] = 10 print(values[3]) # Prints 10 New List : scores = ? • Sometimes, you want to make a copy of a list; that is, a new list that has the same elements in the same order as a given list • Use the list() function: prices = list(values)

scores = [10, 9, 7, 10, 5]

Which error does not cause a program error, but produces incorrect results?

semantic

A string is a

sequence of characters

Pseudocode is a .... • The implementation stage involves what?

set of instructions to solve a programming problem - carried out before the implementation stage. creating the program using the chosen programming language using the pseudocode for guidance.

Python allows ________ or _______ ________ to surround strings.

single ('...') or double quotes ("...")

A string segment is called a _____ - similar to selecting a character: ex?

slice. ex : s = 'WestMinster!' print(s[0:4]) # West print(s[4:11]) # Minster • The first index number is where the slice starts, and the second index number is 1 before the slice ends. E.g., [0:4] index range from 0 to 4 (not including 4) [4:11] index range from 4 to 11 (not 11) *0 includes W

Creating the database We will use Python and SQLite to create a database film.db to hold film information. The first steps are as follows. 1. Import the ______ _ ______. 2. Make a connection by creating a Connection object that will represent the database. This object is created using ... 3. Create a ______ ______. This allows us to execute SQL queries against a database. import sqlite3 db = sqlite3.connect("film.db")

sqlite3 library SQLite's connect () function cursor object import sqlite3 db = sqlite3.connect("film.db")

What is the output of the following code? s = 'everlasting' print(s[6:8])

st

singers = "Peter, Paul, and Mary" What will print? print(singers[2]) print(singers[0:5]) print(singers[7:11]) print(singers[17:21])

t (bc there's no colon : no slice, indexing) - starts at 0 : P = 0, E =1, T=2 Peter Paul Mary

Which elements would the following slices obtain? temp[ : 6] temp[6 : ]

temp[ : 6] : # [18, 21, 24, 33, 39, 40] If the first index is omitted, all elements from the first are included. Includes all elements up to, but not including, position 6 temp[6 : ] : # [45, 44, 40, 22, 18] Includes all elements starting at position 6 to the end of the list.

Indexing : • You can access a single character in a string with what operator? What is the number in the operator called? Note, the index of the first letter is zero. fruit = 'banana' print(fruit[0]) # b (first character) print(fruit[1]) # a (second character) • The value of the ______ has to be an ______. index has to be an integer. As an _____, you can use an expression that contains variables and operators

the bracket operator [] index Note, the index of the first letter is zero. fruit = 'banana' print(fruit[0]) # b (first character) print(fruit[1]) # a (second character) • integer. As an index, you can use an expression that contains variables and operators: i=1 fruit[i] fruit[i+1]

f-string format specifiers • Format specifiers are specified after what? • Floating point values have the f suffix. We can also specify the precision: the number of decimal places. The precision value goes right after the dot character. val = 12.335336 print(f'{val:.2f}') print(f'{val:.5f}') Prints a formatted floating point value of 2 and 5 decimal places: 12.34 12.33534

the colon character

Which of these are illegal variable names? the cost 2_much much2 *star more@ class the_cost

the cost 2_much *star more@ class No two words Numbers can be allowed at the end No special characters Keywords not allowed Underscores allowed

User Defined Functions : Using main () Many programming languages (e.g. Java and C++) use a function main() that is automatically invoked when a program is executed. Although not required by Python, some programmers incorporate main() in their programs. The following three lines are logically related in that they provide ..... Remember, in Python there is nothing special about the function name main(). We use main() to be consistent with other languages.

the main tasks that the program will perform So we create a function main() with these. def main(): num = int(input("Please enter a number")) #1 print(squareit(num)) #2 print(cubeit(num)) #3 def squareit(n): return n * n def cubeit(n): return n*n*n def main(): num = int(input("Please enter a number")) print(squareit(num)) print(cubeit(num)) main()

What happens if you omit the first index (before the colon)? What happens if you omit the second index?

the slice starts at the beginning of the string. ex : fruit = 'banana' print(fruit[:3]) # ban the slice goes to the end of the string: print(fruit[3:]) # ana

Write the program to store 5 in total. Then add 1 onto total and store the answer back into total.

total <- 5 total <- total + 1

While Loops Average of Values • Total the values • Initialize count to 0 • Increment per input • Check for count greater than 0 before divide!

total = 0.0 count = 0 value = float(input("Enter value ")) while value >= 0: total = total + value #(1) count = count + 1 #(2) value = float(input("Enter value ")) if count > 0 : average = total / count #(3) else : average = 0.0 print(average)

Sum Values: Write a program that contains a while loop that will sum the float values entered by a user until the user enters a number less than zero. Then print the total.

total = 0.0 value = float(input("Enter value: ")) while value >= 0 : total = total + value value = float(input("Enter value: ")) print(total)

Functions - Python docstring • At the start of a function, you may write a (multiline) docstring to explain what the function does. •Using ______ ______ allows ________ _______ (either type) allows _________ within the docstring.

triple quotes newlines ex: def mysum(a,b): """ Return the sum of parameters a and b. Last modified 24/09/2020 """ return a + b • Now the docstring should appear in the 'help' for the function. >>> help(mysum)

The comparison operators (>, <, >=, <=, ==, !=) work with strings. 'cat' < 'dog' evaluates to True or False? 'Wasp' < 'Bear' evaluates to True or False? 'Zebra' <= 'alligator' evaluates to True or False?

true false true

The in operator tests whether one string is inside another string. 'heck' in "I'll be checking you." evaluates to True or False? 'cheese' in "I'll be checking you." evaluates to True or False? 'cheese' not in "I'll be checking you." evaluates to True or False?

true false true

Write a program to read in someone's age. Display 'can vote' if they are old enough.

try : age = int(input("Please enter your age:")) if age >= 18: print("You can vote") else: print("Too young to vote") except ValueError: print ("You entered something thats not a number")

A statement is a .... n=17 print(n)

unit of code that has an effect. The first line is an assignment statement that gives a value to n. The second statement is a print statement that displays the value of n. You can change the value stored in a variable by entering another assignment statement. n = 6 The previous value 17 is replaced, or overwritten with the value 6.

Functions Without Return : A function without a return statement is know as .... def print42(): print(42) a = print42() # 42 print(a) # None

void, and they return None, Python's special object for "nothing". def print42(): print(42) a = print42() # 42 print(a) # None

To use pseudocode, all you do is .... • Allows you to focus on the algorithm logic without being distracted by details of language syntax. • Pseudocode is not a rigorous notation, since it is read by people. However, for consistency you can use a particular style.

write what you want your program to do in short English phrases.

x = 4 y = 5 Which of the following is true?

x !=5

• This tests whether both x and y are zero: x == 0 and y == 0 Now state how you test whether at least one of x and y is zero.

x==0 or y==0

How do you correctly call this function? def square(y): a = y * y return a

x=square(5)

String Comparison Do comparison operators work on strings? What about this example? print("apple" == "Apple")

yes ex : To check if two strings are equal: word = 'banana' if word == 'banana': print('They match.') • Uppercase and lowercase letters are different from one another. • A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison.

Do other relational operators (<, >, !=, <=, >=) work on strings? Python compares strings lexicographically. Similar to the alphabetical order you would use with a dictionary, except that all the uppercase letters come before all the lowercase letters. 'apple' < 'banana' evaluates to True. E.g., apple would be less than (come before) the word banana. After all, a is before b in the alphabet. ' banana' < 'cherry' evaluates to True. • However, all the uppercase letters come before all the lowercase letters. 'apple' < 'Apple' evaluates to ? 'Apple' < 'apple' evaluates to ? 'Zeta' < 'Apricot' evaluates to ? 'Zebra' <= 'aardvark' evaluates to ?

yes false true false true

x =[18, 20, 25, 29, 31] • To access the list elements use indices. The first element has index ____, the second one has index _, etc. Values? print(x[0]) print(x[1]) • Negative indices: -1 to access the ____ element, -2 for the __________ __ ____element, and so on. Values? print(x[-1]) print(x[-2]) • Indexing a non-existent list element will result in an error. print(x[5]) #IndexError: list index out of range

zero 1 18 20 last second to last 31 29

• Expressions - Python f-string We can put expressions between the ___ brackets. These will be evaluated at the program runtime.

{} ex: bags = 3 apples_in_bag = 12 print(f'Total of {bags * apples_in_bag} apples') • Output: Total of 36 apples Methods - We can call methods in f-strings. ex: print(f'My name is { name.upper() }') • Output: My name is JOHN DOE

Python f-string • Available since Python 3.6. • The string has the f (or F) prefix and uses __ to evaluate _________. • Provide a ______ and more _______ way of formatting strings in Python. • f-string is short for ?

{}, variables faster, concise formatted string literals. ex : print(f'{name} is {age} years old')

Tuples A tuple is similar to a list, but once created, ..... It is a ________ version of a list A tuple is created by specifying its contents as a ..... If you prefer, you can omit the ___________. • A tuple with one value must have an ....

• A tuple is similar to a list, but once created, its contents cannot be modified . • A tuple is immutable (unchangeable) version of a list. • A tuple is created by specifying its contents as a comma-separated sequence enclosed in parentheses: triple = (5, 10, 15) • If you prefer, you can omit the parentheses: triple = 5, 10, 15 • A tuple with one value must have an ending comma: single = 5, • Processing a tuple in the same ways as a list: a_tuple = (17, 13, 19, 23) print(a_tuple[0]) #17 print(a_tuple[-1]) #23 print(a_tuple[1:-1]) #(13, 19) print(sorted(a_tuple)) #[13, 17, 19, 23] print(17 in a_tuple) # True • However, tuple values are immutable. This means tuple items cannot be added, removed or replaced. • This is useful if you want to store data that you want to remain fixed during a program. • Also, they are faster than lists for Python to process. • Therefore, the following are not possible: a_tuple[2] = 5 # error a_tuple.sort() # error a_tuple.extend([34, 54]) # error a_tuple.insert(1, 39) #error a_tuple.append(400) #error a_tuple.pop() #error • We can convert a tuple to a list: a = list(a_tuple) print(a) #[17, 13, 19, 23] • We can convert a list to a tuple: b = tuple(a) #(17, 13, 19, 23)

Which is the best solution? i=1 while i < 10 : print(i) i=i+1 ----------------------------------------------------------- for i in range(1, 10) : print(i)

• Both produce the same result. - The while loop has a condition and it runs until the condition is false (condition controlled). - Use the for loop (count controlled) when you know how many items the loop should execute. for i in range(1, 10) : print(i)

Conditional statements - simplest form is if: if x > 0: print('x is positive') if - Example 2 letter = "a" if letter == "a": print("Letter is a") if - Example 2b • Now change the program 2a slightly: letter = "b" if letter == "a": print("Letter is a")

• Condition - the boolean expression after if. • If it is true, the indented statement runs. • If not true, nothing happens. • Indent your print statement so that the program knows that it is part of the if statement. 4-spaces is common choice. • Because the answer is false it does not print anything The print statement needs to be indented to be applied to the if statement block. If not indented it is not part of the if block.

• SEQUENCE - linear, one task performed sequentially after another. • Common Action Keywords for input, output and processing: • Input: _____, _____, ______ • Output: ______, ______, ______ • Compute: __________, ___________ • Initialize: ______ • Add one: __________

• Input: INPUT, READ, GET • Output: PRINT, DISPLAY, OUTPUT • Compute: COMPUTE, CALCULATE • Initialize: SET • Add one: INCREMENT

Debugging - NameError

• NameError: usually means you have used a variable before it has a value. Typo? Example: NameError: name 'wait_time_int' is not defined current_time_str = input("Current time (in hours 0-23)?") current_time_int = int(current_time_str) wait_time_str = input("How many hours do you want to wait") wait_time_int = int(wait_time_int) final_time_int = current_time_int + wait_time_int print(final_time_int) • To find: Check the right hand side of assignment statements. You could also search for the exact word highlighted in the error message

Syntax Errors

• Refers to the structure of a program and the rules about that structure. • Look for missing parentheses, quotation marks, or commas. • E.g., parentheses have to come in matching pairs so 8) is a syntax error • SyntaxError: Example: current_time_str = input("Current time (in hours 0-23)?") wait_time_str = input("How many hours until alarm?" current_time_int = int(current_time_str) wait_time_int = int(wait_time_str) final_time_int = current_time_int + wait_time_int print(final_time_int) To find: Look for missing parentheses, quotation marks, or commas. IDLE might highlight a line of code that does not have an error. So, work back line by line until you find the syntax error.

Semantic Errors

• Semantics - the meaning of a program. • Semantic error - An error in a program that makes it do something other than what the programmer intended. • The program will run without generating error messages, but it will not do the right thing.

Dictionaries • Dictionary in Python is a collection of _______ _______. • They map(associate) a .....

• Strings, lists, and tuples are sequence types - the items in the collection are ordered from left to right and they use integers as indices to access the values they contain. • Dictionary in Python is a collection of data values. • They map(associate) a key with a value. • In other languages, they are called associative arrays.

Runtime Errors

• The error does not appear until after the program has started running. These errors are also called exceptions (e.g., something exceptional has happened). • We will look at some errors related to exceptions: NameError, TypeError, ValueError, ZeroDivisionError

Dictionary method: get()

• The get() method accesses the value associated with a key. • Similar to the [ ] operator. However, get() will NOT cause an error if the key is not present - will return None. stock = {'apples': 430, 'bananas': 312, 'pears': 217} print(stock.get("apples")) # 430 print(stock.get("cherries")) # None • An optional second parameter provides an alternative return value where the key is not present. E.g., as "cherries" is not a key, return 0 (instead of None). print(stock.get("cherries", 0)) # 0

Nested iteration: for i in range(3): # 0,1,2 for j in range(2): # 0,1 print(i, j) What sequence does this produce?

• The program first encounters the outer loop (for i), executing its first iteration (0). The first iteration triggers the inner loop (for j) which then runs to completion. • Program then returns back to outer loop for next iteration. • For each value of i, all values of j will occur: 00 01 10 11 20 21 **each value is twice in a row**

Range Ex: print ("counting in fives") for i in range (0,50,5): print(i) what sequence of integers does it generate?

• Third argument specifies the sequence incrementation (step). • The first number is the start number • Second number is the stop number • Sequence generated: 0, 5, 10, 15, 20, 25, 30, 35, 40, 45

Range Ex: range(0, 7, 2) what sequence of integers does it generate?

• Third argument specifies the sequence incrementation (step). • The sequence generates the sequence in steps of 2. The default is 1. * step: integer value which determines the increment between each integer in the sequence • Generates sequence: 0, 2, 4, 6

Debugging - TypeError

• TypeError: often when an expression tries to combine two types that are not compatible (e.g., integer and string). Example: a = input('Enter number ') x = input('Enter another number ') int(a) x = int(x) total = a + x Output: Enter number 56 Enter another number 45 Traceback (most recent call last): File "C:/Users/purdyw/test2.py", line 5, in <module> total = a + x TypeError: can only concatenate str (not "int") to str >>>

Debugging - ValueError

• ValueError: Raised when an operation or function receives an argument that has the right type but an inappropriate value • Example: We ask the user for a number and instead they enter a character t. We use int() to convert user input (string) to integer but the value t cannot be converted to an integer number. ValueError: invalid literal for int() a = input('Enter number ') a = int(a) # do something here # print result • To fix: use try / except to catch this error.

Debugging - ZeroDivisionError

• ZeroDivisionError: with Python it is not possible to divide numbers by zero. • If you attempt to divide by 0, python will throw a ZeroDivisionError x = 100/0 • To fix: • Use an if statement to ensure that the value is not zero. • Or use try / except to catch this error (example later)

Range Ex: range(1, 5) what sequence of integers does it generate?

• generates sequence of integers 1, 2, 3, 4. From 1 up to, but not including, 5.

Dictionary Operators: In/Not In

• in and not in can test if a key is in the dictionary: "one" in eng2sp # True "six" in eng2sp # False "tres" in eng2sp # False 'in' tests keys, not values • Useful, since looking up a non-existent key in a dictionary causes an error.

Boolean: not

• not operator evaluates to the opposite Boolean value - Inverts a condition. • True expressions evaluate to False • False expressions evaluate to True. x = 10 print(not x == 10).#false print(not x == 3) #true • Truthtable: not A. Evaluates to not True. False not False True

Range Ex: range(7) what sequence of integers does it generate?

• produces: 0,1,2,3,4,5,6 (default start argument is 0)

Range Ex: for i in range(5, 10): print(i) what sequence of integers does it generate?

• range() with for loop • Sequence generated: 5,6,7,8,9 (setting the start number to 5). • Remember, the end point (10) is never part of the generated sequence.

Range Ex: for i in range(10): print(i) what sequence of integers does it generate?

• range() with for loop • The number passed to the range function tells the program how many times to loop. • The sequence generated is: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 • The sequence automatically starts at 0. The stop (10) is never part of the sequence.

What are the three kinds of errors that can occur in a program?

• syntax errors, • runtime errors • semantic errors.

Dictionaries Key / Value Rules Dictionary Keys: ? ? Dictionary Values: ? ?

•Must be unique •Of immutable data type such as Strings, Integers and tuples •May contain repeating values •Can be of any type


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

American Heritage Lecture Quotes

View Set

Promulgated Addenda, Notices, and Other Forms Exam Questions

View Set

Affordability of Health Goods & Services

View Set