software development test

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Python line comment begins with:

#

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

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

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

23

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

3

Which of the following expression results in a value 1?

37 % 6

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

Which of the following is a rational operator?

<=

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

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

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

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: 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

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

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 the error in this statement: if scoreA = scoreB : print("Tie")

Should be compared with == not =

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

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

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?'

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

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

Booleans operators

and or not

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

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.

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)

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

Output

display on the screen, save to file/database ect

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")

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

Input

get data from the keyboard/file/database ect.

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

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.

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)

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.

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

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 ("...")

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

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

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.

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

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.

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

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.

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)

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

• syntax errors, • runtime errors • semantic errors.


Set pelajaran terkait

American Heritage Lecture Quotes

View Set

Promulgated Addenda, Notices, and Other Forms Exam Questions

View Set

Affordability of Health Goods & Services

View Set