Python

Ace your homework & exams now with Quizwiz!

What is the output of the following code?: def print_sum(variable, y): >>>variable += 1 >>>print(variable + y) print_sum(5, 8) How many arguments does it have?

14 The function has two arguments

What would be the output of the following: >>>print(1 + 1)

2

Mathematically, output '4'

2 + 2 (or any other mathematical scenario equaling 4)

Write the code '2 raised to the 5th'

2**5

What is the output of this code? >>>float("210" * int(input("Enter a number: "))) Enter a number: 2

210210.0

What is the output for this? >>>6 * 7.0

42.0

Write a string that outputs the text 'Brian's mother'

>>>'Brian\'s mother'

Create the string 'Python' as the output.

>>>'Python'

What is a nested if statement?

An if statement within an if statement

What does the *insert* method do and how do you use it?

The *insert* method is similar to the append method, except that it allows you to insert a new item at any position in the list. words = ["Python", "fun"] index = 1 words.insert(index, "is") print(words) *Result: ['Python', 'is', 'fun']

How do you create an empty list?

emptySet= []

Write the syntax to open a file, which has been assigned 'file', and create the argument to read it. Using the read method, print the contents of the file.

file = open("filename.txt", "r") cont = file.read() print(cont) file.close()

The argument of the *open* function is the ___ to the file. If the file is in the same ___ as the program, you can specify only its name.

path, directory

Write a program that displays "Hello world!"

print('Hello world!')

User input always has the type ___. Knowing this, convert user input into something that is not this type.

string (*str*) float(input("Enter a float: ") int(input("Enter an integer: ")

What is the result of the following code? str = "Hello world!" print(str[6])

w *Note that strings can be indexed like lists but integers cannot

What is the highest number printed by this code? print(0) assert "h" != "w" print(1) assert False print(2) assert True print(3)

1 This is because the assertion evaluated False whereas the first one was True

How do you annotate without disrupting the sequence of code?

# followed by the comment you wish to enter. Anything after the # is ignored. If you want to comment and it will take more than one line, use """. These are referred to as Docstrings (documentation strings) For example: code code code #this part is ignored code code code """ this part is ignored """ codecode

What is the output of the following? >>>"Spam" + 'Eggs' >>>5 + 4 >>>"5" + "4" >>>"5" + 4

'SpamEggs' 9 '54' error

What is the exponentiation operator?

**

How do you create a new line?

*\n*

How do you get the number of items in a list?

By using the *len* function. nums = [1, 3, 5, 2, 4] print(len(nums)) *Result: 5

Which implementation of Python is the most popular?

CPython

Ask the user for input with "Please enter something: "

For this we use the *input()* function >>>input("Please enter something: ")

Import the math module and it's sqrt function. Change the name of the sqrt function to 'square_root' and use it.

For this you use *as* from math import sqrt as square_root print(square_root(100))

Assuming it has already been assigned, delete the variable 'variable'.

For this, we use *del* >>>del variable

What does the *append* method do and how do you use it?

The *append* method allows you to add an item to the end of an existing list. nums = [1, 2, 3] nums.append(7) print nums *Result: [1, 2, 3, 7]

Python is processed at runtime by the __. There is no need to __ the program before executing it.

Interpretor; compile

Define iteration

The repetition of a code being executed

What part of an if statement should be indented?

The statements within it

What are the three types of modules in Python?

Those you write yourself, those that you install from external sources, and those that are preinstalled with Python (*Standard Library*). All standard library modules are available online at www.python.org

Evaluate as either *True* or *False* >>>1 == 1 and 2 == 2 >>>1 == 1 and 2 == 3 >>>1 == 1 or 2 == 3 >>>2 < 1 or 3 != 3 >>>not 1 == 1 >>>not 1 > 7

True False True False False True

Taking into consideration operator precedence, evaluate the following as either *True* or *False*. >>>False == False or True >>>False == (False or True) >>>(False == False) or True

True False True *In other words, == has a higher precedence than or

Evaluate these as *True* or *False* >>>7 > 5 >>>7 > 7 >>>7 >= 7.0

True, False, True

Any statement that consists of a word followed by information in parentheses is called a ___ call.

function examples are: print() range() str()

What are Python's Boolean operators?

*and*, *or*, and *not* In other programming languages, this is typically &&, ||, and !

To end a loop prematurely, the ___ statement can be used. Give an example of it in a while loop.

*break* i = 0 while 1 == 1: >>>print(i) >>>i = i + 1 >>>if i >= 5: >>>>>>print("Breaking") >>>>>>break print ("Finished") *Result is: 0 1 2 3 4 Breaking Finished

In addition to using pre-defined functions, you can create your own functions by using the ___ statement. Define a function called my_func that prints 'spamspamspam'. How many arguments does this function have?

*def* def my_func(): >>>print("spamspamspam") my_func() This function has zero arguments.

In boolean terms, state that 2 is equal to 2. State that 2 is not equal to 3. State that hello is the same as hello.

>>>2 == 2 >>>2 != 3 >>>"hello" == "hello" All statements are *True*

Ask a user for a numerical input and store it as the variable 'number'. Print that number.

>>>number = input("Enter a number: ") >>>print(number)

Write the expression 'x = x + 3' more concisely. Write the expression 'x = x * 3 more concisely.

>>>x +=3 >>>x *=3

Assign the variable x to a value of 7 and print it using the print option. Assign the variable spam to the string "eggs" and print it 3 times.

>>>x = 7 >>>print(x) >>>spam = "eggs" >>>print(span * 3)

What is the output of the following? >>>x = "spam" >>>x +="eggs" >>>print(x)

spameggs

What is the output of the following: >>>print("spam" * 3) >>>print("spam" * 3.0)

spamspamspam error, can't multiply a string and a float

What is the output of the following code?: def shortest_string(x, y): >>>if len(x) <= len(y): >>>>>>return x >>>else: >>>>>>return y print(shortest_string(string, str))

str

What is the output of the following code? def add(x, y): >>>return x + y def do_twice(func, x, y): >>>return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(add, a, b))

30

What is the output of the following? >>>int("3" + "4")

34; this is become concatenation occurs first then the string is converted into an integer

What is the output of this code? def func(x): >>>res = 0 >>>for i in range(x): >>>>>>res += i >>>return res print(func(4))

6

What is the output of this code? list = [1, 1, 2, 3, 5, 8, 13] print(list[list[4]])

8

How many times can you reassign a variable?

As many times as you want!

An except statement without any exception specified will...

Catch all errors

Write the general format of an *if* statement? An *if-else* statement?

if expression: >>>statements if expression: >>>statements else: >>>statements

What 3 characters are allowed in Python programming? In terms of naming variables, which of these 3 are you not allowed to have as the first character?

Letters, numbers, and underscores. Numbers *Also note, Python is case sensitive

What is a module? How do you import a module?

Modules are pieces of code that other people have written to fulfill common tasks, such as generating random numbers, performing mathematical operations, etc. The basic way to use a module is to add *import* module_name at the top of your code. Then using module_name.var to access functions and values with the name var in the module. For example, the following uses the module random to generate random numbers: import random for i in range(5): >>>value = random.randint(1, 6) >>>print(value) Result: 2 3 6 5 4

What is the output of the following code? name = "123" raise NameError("Invalid name!")

NameError: Invalid name!

What is a *float*?

Numbers that are not integers (have decimals)

What is the output for this? 20 // 6 How do you determine the remainder?

Output is 3. To find the remainder... >>>20 % 6

What is concatenation? Are concatenated strings created with single or double quotes?

The addition of two or more strings. It does not matter whether single or double quotes are used.

Create a list with the words "Hello" and "World". Then create a for loop that prints the words as such: Hello World

array = ["Hello", "World"] for word in array: >>>print(word)

A *list*, a type of object in Python, is used to store an indexed list of items. It is created using ___ brackets with ___ separating items. Give an example format.

square, commas words = ["Hello", "world", "!"] print(words[0]) print(words[1]) print(words[2]) *Result: Hello world !

What is the result of this code? >>>7%(5//2)

1

Force x, which is assigned the integer 8, to become a string

>>>str(x)

What is the result of this code? if 1 + 1 * 3 == 6: >>>print("yes") else: >>>print("no")

no

What is the output of the following code?: def print_with_exclamation(word): >>>print(word + "!") print_with_exclamation("spam") print_with_exclamation("eggs") How many arguments does it have?

spam! eggs! The function has one argument.

The ___ statement is placed at the bottom of a try/except statement to ensure that specific code runs no matter what errors occur. It will always run after the execution of code in the try, and possible the except, blocks. Example format?

*finally* try: >>>print("Yo") >>>print(1 / 0) except ZeroDivisionError: >>>print("Divided by zero") finally: >>>print("This code will run no matter what") output: Yo Divided by zero This code will run no matter what

How do you access one specific function within a module? For example, import both pi and sqrt from the math module

*from* module_name *import* var from math import pi, sqrt

Code can actually be called upon when an exception occurs. This is done by using the ___ statement. What is the general syntax of this?

*try/except* The *try* block contains the code that might throw an exception. If that exception occurs, the code in the *try* block stops being executed, and the code in the *except* block is run. If no error occurs, the code in the *except* block doesn't run. Example format, *try*: >>>statements *except* SpecificException >>>statements

What do the following function do? *max*(list): *min*(list): *list.count*(obj): *list.remove*(obj): *list.reverse*():

-Returns the list item with the maximum value -Returns the list item with the minimum value -Returns a count of how many times an item occurs in a list. -Removes an object from a list -Reverses objects in a list

Python can be used to read and write the contents of files. The ___ files are the easiest to manipulate. Before it can be edited, it must be opened using the ___ function. After things are done to the file, it must be closed using the ___ method. Show the syntax for this.

.txt, *open*, *close* myfile= open("filename.txt") #do stuff to the file myfile.close()

How many lines will this code print? while False: >>>print("Looping...")

0; *while* statements work by checking if the condition is true. Another way of looking at the code is: while False == True: Since False never equals True, the loop will never run.

What is the output of the following code? print(1) raise ValueError print(2)

1 ValueError The *raise* statement allows you to raise exceptions, although you must specify the type of exception raised.

What is the output of this code? num = 7 if num > 3: >>>print("3") if num < 5: >>>print("5") if num == 7: >>>print("7")

3

What is the output for this? >>>10 / 2

5.0

What is the output of this code? >>>spam = "7" >>>spam = spam + "0" >>>eggs = int(spam) + 3 >>>print(float(eggs))

73.0

What is a *while* loop? Give an example format of a while loop.

A statement that can be run more than once. The statements within it execute as long as a condition holds. Once it evaluates to false, the next section of code executes. i = 1 while i <=5: >>>print(i) >>>i = i + 1

What is an *elif* statement short for? What does it do?

An 'else if' statement. It is a shortcut statement to use when chaining if and else statements. A series of if elif statements can have a final else block, which is called if none of the if or elif expressions are True.

What is the output of the following code? try: >>>num = 5 / 0 except: >>>print("An error occured") >>>raise

An error occured ZeroDivisionError: division by zero

What is the output of the following code?: try: >>>num1 = 7 >>>num2 = 0 >>>print(num1 / num2) >>>print("Done calculation") except ZeroDivisionError: >>>print("An error occurred due to zero division error")

An error occurred due to zero division error

What is an exception?

An event that occurs due to incorrect code or input. There are different exceptions for different reasons (i.e. ImportError, IndexError, etc). Third-party libraries also often define their own exceptions.

How many except statements can follow a try statement?

As many as necessary. For example: try: >>>statements except ZeroDivisionError: >>>statements except(ValueError, TypeError): >>>statements *Note that the second except statement contains two exceptions, of which would be handled by the same statements.

What is the output of this code? try: >>>meaning = 42 >>>print(meaning / 0) >>>print("the meaning of life") except ZeroDivisionError: >>>print("Divided by zero")

Divided by zero *Note that, print("the meaning of life") was skipped after the division by zero caused the execution of the except statement.

What does the *continue* statement do? Example code?

It is a statement used within loops that, unlike breaks, causes the code to jump back to the top of the loop, rather than stopping it. i = 0 while True: >>>i = i + 1 >>>if i == 2: >>>>>>print("Skipping 2") >>>>>>continue >>>if i = 5 >>>>>>print("Breaking") >>>>>>break >>>print(i) print("Finished") *Result: 1 Skipping 2 3 4 Breaking Finished

Many third-party Python modules are stored on the ___. The best way to install these is using a program called ___.

Python Package Index (PyPI) and pip

Why are lists within lists often used to represent 2D grids? Give an example

Python lacks the multidimensional arrays that would be used for this in other languages. number=3 things = ["string", 0, [1, 2, number], 4.56] print(things[2]) print(things[2][2]) *Result: [1, 2, 3] 3

What is the result of this code? x = 4 y = 2 if not 1 + 1 == y or x == 4 and 7 == 8: >>>print("yes") elif x > y: >>>print ("no")

Result is no *Step 1: if not 1 + 1 == y or x == 4 and 7 == 8 As per the operator precedence, the first 'and' is considered, x == 4 and 7 == 8, which evaluates to False. With this, the expression can be simplified to... if not 1 + 1 or False

What does the *index* method do and how do you use it?

The *index* method finds the first occurrence of a list item and returns its index. letters = ['p', 'q', 'r'] print(letters.index('r')) *Result: 2

What does the following code do? / What is the output? numbers = list(range(10)) print(numbers) betweenNumbers = list(range(10, 15)) print(betweenNumbers)

The *range* object creates a sequential list of numbers. Therefore, the code generated a list containing 10 integers. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [10, 11, 12, 13, 14]

What does the *return* statement do? What is the output of the following code?: def max(x, y): >>>if x >= y: >>>>>>return x >>>else: >>>>>>return y print(max(4, 7)) z = max(8, 5) print(z)

The *return* statement causes your function to exit and hand back a value to its caller. Return can be used alone to stop a function or it can be followed by the value to be returned. 7 8

What does the *in* operator do? What does the *not* operator do? Give an example

You can use the in operator to check if an item is in a list. You can use the not operator together with in to check if an item is not there. words = ["spam", "egg", "spam", "sausage"] print("spam" in words) print("egg" in words) print("tomato" in words) *Result: True True False ____ words = ["spam", "egg", "spam", "sausage"] print(not "spam" in words) print("egg" not in words) print(not "tomato" in words) *Result: False False True

What is the output of the following code? numbers1 = list(range(0, 10, 2)) numbers2 = list(range(0, 10, -2)) numbers3 = list(range(10, 0, -2)) print(numbers1) print(numbers2) print(numbers3)

[0, 2, 4, 6, 8] [] [10, 8, 6, 4, 2]

An ___ is a sanity check that you can turn on or off when you have finished testing the program. An expression is tested and if the result comes up false, an expression is raised. For this, we use the ___ statement

assertion, *assert* Programmer often place assertions at the start of a function.

What is the output of the following? for i in range(5): >>>print("hello!")

hello! hello! hello! hello! hello!

You can specify the ___ used to open a file by applying a second argument to the *open* function. Sending ___ means open in read mode (default), sending ___ means write mode for rewriting the contents of a file, sending ___ means append mode for adding new content to the end of the file. Adding a ___ means to open a file in binary mode which is used for non text files.

mode, "r", "w", "a", "b" Examples: #write mode open("filename.txt", "w") #read mode open("filename.txt", "r") #append mode open("filename.txt", "a") #binary write mode open("filename.txt", "wb")

What is the result of the following code?

nums = [1, 2, 3] print(nums + [4, 5, 6]) print(nums * 3) *Result: [1, 2, 3, 4, 5, 6] [1, 2, 3, 1, 2, 3, 1, 2, 3]


Related study sets

PP RNSG 1538 Intrapartum Mastery Quiz

View Set

Exam review insurance life and health missed questions:

View Set

Chapter 4 Adaptive Study Pre-Test

View Set

Basic Japanese Words and Phrases

View Set

Exam 2 (Ch 11-20): Mental Health: Text Review and Evolve NCLEX

View Set