Python

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

what does the append function do when used in a list?

Adds the appended element to the end of the list

An else statement follows __________.

An if statement

What does the continue function do?

Continues with the next iteration of the loop

______________ gives us this ability to choose among outcomes based off what else is happening in the program.

Control flow

A loop that repeats a specific number of times is know as a(n)_________________.

Count controlled loop

A float is a number with a _______.

Decimal

The or operator takes two arguments and evaluates to true if ______________.

Either (or both) arguments is/are true.

elif statements can have a final ________.

Else statement

When a function is executed, what happens when the end of the function statement block is reached?

Execution returns to the statement that called it.

(T or F) When you want to print a variable inside of a string, the best way is concatenation

False

(T or F) items in a list must be inside of quotes

False

(T or F) when using the .items() function on a dictionary, it will print the items (keys and values) in the order they are in the dictionary

False

(T or F) False or not 3 <= 5 * 2

False

(T or F) The range function must be attributed to a certain list name when used in a for loop

False

(T or F) When creating a method, you do not have to pass in the self argument if you already did so in __init__()

False

Is this a true or false statement? 1 != 1

False

You can multiply a string by a float. (T or F)

False

abs() is part of the math module (T or F)

False

if you want to do something with every item in a list you can use a ___ ______.

For Loop

Write an opening line of code that uses the zip function on a list called list_a and list_b

For a , b in zip(list_a , list_b):

When accessing a value from a dictionary you use a ___ instead of an index

Key

The only characters allowed in a variable name are:

Letters, Numbers, Underscores

\n represents a ___ ______.

New Line

According to operator precedence what is the output of this code? if 1 + 1 * 3 == 6: print("Yes") else: print("No")

No

is 13_Hab an acceptable variable name?

No, variable names cannot begin with numbers

What is this Boolean operator? !=

Not equal to

Use _________ to determine which operations are performed first

Parenthesis

What will putting a comma after a print statement do?

Prevent the next output from going to the next line

For a function to be used in an expression, it must _____________ .

Return a Value

use _________ to determine if a string is letters.

STRING.isalpha()

Methods using dot notation (such as "String".upper() ) only work with _________.

Strings

Create a sting by putting _______ between ' or " marks.

Text

(T or F) A list is a data type

True

(T or F) You can use a while / else loop

True

You can also take the value of the variable from user input. (T or F)

True

evaluate not 65 < 50

True

What will the following print to the console? my_list = range(10) print filter(lambda x: x**2 / 3 < 5, my_list)

[0, 1, 2, 3]

What will this code return? my_list = [1, 3, 5, 7] my_list.remove(3)

[1, 5, 7]

what is the format for taking only certain elements from a list?

[start:end:stride]

___ is automatically put in the output, where you press Enter. IF you put your string inside of _ sets of quotes.

\n , 3

What is a class?

a way of organizing and producing objects with similar attributes and methods.

What is the absolute value function?

abs()

What is a lambda?

an anonymous function

how do you convert an integer into binary?

bin()

The and operator takes two arguments and evaluates as true if _________.

both arguments are true

Variable names are _____ sensitive.

case

How would you insert the item "Blue" as the second item in the list named colors?

colors.insert(1,"Blue")

What is buffered data?

data that it is held in a temporary location before being written to the file.

What function can be used to supply an index to each element of a list as you iterate through it?

enumerate()

You can use a for loop on a string to perform an action on ____________ in the string.

every character

Why is it not always a good idea to use a universal import?

if you have functions named the same as the functions in the module it can confuse the program.

an __/_____ statement says "If this expression is true, run this indented code block; otherwise, run this code after the else statement."

if/else

Each character inside of a sting has a number, this number is called the _____

index

how can you give all objects of a class the same variable without actually initializing it?

inside of the class, before __init__(), create a new variable and set it equal to the desired value

What is the format for calling a method inside of a class?

instance = ClassName(att1, att2, att3) print instance.method()

How do you convert the string "83" into the integer 83?

int("83")

When you divide an integer by an integer the result is always a ______ _________ down

integer rounded

Write a line of code that will check the amount of keys in a dictionary

len(dictionary.keys())

How do you append an element to a list?

list_name.append("New Element")

what can you use to find the index of a certain element in a list?

list_name.index("element")

How do you remove an item from a list?

list_name.remove('item')

how can you alphabetically or numerically sort a list?

list_name.sort()

How do you assign a new element to a specific index in list?

list_name[desired index] = entry

how do you select an element from a list within a list?

listname[outer_list_index][inner_list_index]

How do you open a file in read only mode?

my_file = open('filename.txt', 'r')

How do you open a file in read and write mode?

my_file = open('filename.txt', 'r+')

str() turns _______ into ________

non-strings into strings

What does this .pop() function do? listname.pop(x)

removes the item at index x and returns list

How do you convert the integer 83 into the string '83'

str(83)

Besides datetime what is another function you can use to obtain current time functions?

strftime

how do you separate a sentence (string) into a list with each word?

string.split()

What does this class inherit? class ClassName(object):

the properties of an object, which is the simplest, most basic class

What built in function allows you to iterate over two lists at once?

the zip function

What does this code do? def cube(number): return number**3 def by_three(number): if number % 3 == 0: return cube(number) else: return False

when cube is called it will return the cube of the number. when by_three is called it will return the number cubed IF the number is divisible by three

How is a dictionary formatted?

{ 'Key' : value , 'Key2' : value }

what is missing? a=apples b=titties print "do you prefer %s or %s ?" ___ ( a , b )

%

How do you print a float to the second decimal place using string formatting?

%.2f

How do you insert a float using string formatting?

%f

use the % operator to replace the__ placeholders with the variables in parentheses.

%s

How do you read one line of a file at a time?

.readline()

Computer scientists love to start counting from ____

0

This is the correct way to initialize a class def __init__(self, new_var): new_var = self.new_var

False

This is the correct way to print the 'condition' of 'my_car' class Car(object): condition = 'new' my_car = Car() print condition.my_car()

False

evaluate not not 50 != 50

False

evaluate not 41>40

False

(T or F) Dictionaries are oredered

False, dictionaries are unordered

(T or F) The zip function will stop at the end of the longer list

False, it will stop at the end of the shorter list

(T or F) When accessing a value from a dictionary you use curly brackets.

False, use [] brackets as in a list

What is file I/O?

File input / output

Using a / for division produces a _______.

Float

Computers can't store ______ completely accurately, which can lead to bugs.

Floats

What are two keywords used to start loop (repeating) statements in Python 2.7?

For & While

what does the string function .len() do?

Gives you the number of characters in the string. (length)

What are these Boolean operators? <= >=

Greater than / less than (or equal to)

Is this a true or false statement? 2 != t

True

T or F You can call another function from within a function

True

This is the correct way to initialize a class def __init__(self, new_var): self.new_var = new_var

True

This is the correct way to print the 'condition' of 'my_car' class Car(object): condition = 'new' my_car = Car() print my_car.condition

True

Variables can be reassigned as many times as you want. (T or F)

True

You can assign a variable to an integer and then later assign that same variable to a string. (T or F)

True

You can multiply a string by an integer. (T or F)

True

What are the two Boolean values in python?

True and False

How do you perform exponentiation?

Two asterisks - (Base**Exponent)

How do you include a character that can't be directly included in a string? Ex: a double quote

Use a backslash

What is one method for using a while loop so that it does not become infinite and iterates a certain amount of times?

Use an increment count

Besides using a for loop, how can you iterate through items in a list?

Using the range function

A _______ allows you to store a value by assigning it to a name.

Variable

A while loop executes _____________________.

WHILE a condition holds true

When does python write data to a file?

When you close the file

How do you take just the portion of this list between the second and third positions? letters = ['a', 'b', 'c', 'd', 'e'] *remember to begin counting at 0 and that the number after the colon is NOT included

portion = letters[1:3]

Line of code that will output: Hello, World!

print ('Hello, World')

Write a line of code that calls the method 'description' on the object 'hippo' and prints it

print hippo.description()

write a line of code that prints the result of reading my_file

print my_file.read()

what is the benefit of using with and as?

python will automatically close the file for you

Replace the line in the function so that the functions prints every other list item. def print_list(x): for counter in ________________: print x[counter]

range(0, len(x),2)

How do you prompt the user for input?

raw_input('prompt')

what does this .remove() function do? listname.remove(x)

remove the actual item x if it finds it

what will this code do? word = 'apples' print len(word)

return the length of the word 'apples'

what does the .closed attribute do?

returns True if the file is closed and False otherwise

what does the type() function do?

returns the data type of the argument: (str, int, float)

what is the output of this code: print(3 * '7')

777

If you want to write a number in binary what must it begin with?

0b

What is the output of this code and why? int('6'+'3')

63 , because the operation inside the parenthesis is done first and while '6' and '3' are inside the parenthesis they are strings so their sum is '63', which is THEN converted into the integer 63

What are the 5 basic categories of statements that programming languages have.

1.) Conditional 2.) Looping 3.) Function 4.) Assignment 5.) Declaration

What are the 3 general parts of a function?

1.) Header (includes 'def') 2.) Comment (optional) 3.) body (indented)

What does this code do? def compute_bill(food): total = 0 for n in food: total += prices[n] return total

1.) defines a function called compute_bill that takes an argument called 'food' 2.) sets the variable 'total' to 0 3.) for every item in the list 'food' it will find that item by key in the dictionary 'prices' and add its value to the other items in the 'food' list 4.) prints result

What is the order of operations for boolean operators?

1.) not 2.) and 3.) or

______ = 5.0 / 3.0 * 6.0

10.0

What is the output of this code? x = 3 num = 17 print(num % x)

2 (remainder)

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, because since 7 is not less than 5 the next nested statement is never reached

What value will be printed after this code in run? x = 12 y = 10 y += 15 myvar = x + y print myvar

37

What will this code print? my_dict = {"shirts": 5, "pants": 4, "shoes": 2} print my_dict["pants"]

4

What will this code return? max( 2 , 6 , 9, -10)

9

The end of an if statement should contain a _.

:

To assign a variable use an ____ sign

=

What is the Boolean equal operator in python?

==

What are the Boolean operators for greater than / less than?

> <

What is a variable that is only available to a certain class called?

A member / member variable

What do you call a function inside of a class?

A method

A list goes between _______ separated by ______

Brackets , commas

while in a loop, a _____________ command allows to to exit before the completion of the loop

Break

How does the 'in' operator work?

Checks if an item is in something (like a list or string) and then returns True if it is and False if it is not.

What MUST you do in order for python to write to the file properly?

Close the file when done writing to it

To add a string that contains a number to an integer you must first __________________.

Convert the string to an integer

Python uses ______ to delimit blocks of code

Indentation

You can access a certain element of a list by its ________

Index

A program takes _____ to produce ______

Input, output

%d prints ______ as %s prints strings

Integers

The operator not only takes one argument and _________ it.

Inverts

What does the zip function do?

It creates pairs of elements when passed two lists

when selecting a section of a string that should include the end, for the second index you can use .len() or you can ______.

Leave second index blank

What is the output of this code? string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

Let's not go to Camelot. 'Tis a silly place.

What will this line of code do? "parrot".upper()

Make all letters in the string "parrot" uppercase

An instance of a class automatically has access to what variables?

Member variables

You can use the ____ function to produce output.

Print

A __________ is the part of a program in which a variable may be accessed.

Scope

User input is automatically returned as a ______. (With the contents automatically escaped.)

String

An else statement contains code that is called when _____________________.

The if statement evaluates to false

(T or F) Else statements must be followed by a :

True

(T or F) Lists can be added and multiplied

True

(T or F) The > < operators can be used to compare two strings lexicographically

True

(T or F) You can access the key and the value of a dictionary with a for loop

True

(T or F) You can put lists inside of dictionaries

True

(T or F) it is acceptable to call a function with a different variable name than the one used when the function was originally created

True

(T or F) you can use a for loop on a dictionary.

True

(T or F) The zip function can handle 4 lists at once

True

What is XOR?

Will return a true (1) if EITHER of the compared values are a one, but NOT BOTH

List_name[a:b] will return the portion of list_name starting ____ the index a and ending ____ the index b.

With, before

What will this code output? list1= [1, 2, 3] print(list1 + [4, 5, 6])

[1, 2, 3, 4, 5, 6]

What will this code return? my_list = [1, 2, 3, 5] my_list[2] = my_list[1] + 2

[1, 2, 4, 5]

What is this list comprehension equal to? i for i in range(10) if i % 3 == 1]

[1, 4, 7]

What will this code return? my_list = [8, 6, 4, 2] my_list.pop(1)

[8, 4, 2]

What function is required for classes to initialize objects?

__init__()

what is n? def square(n):

a parameter, which acts as a variable name for a passed in argument.

How do you initialize the object(s) of a class?

def __init__(self):

How would you delete the key-value pair with the key "Blue" in the dictionary "Colors"

del colors['Blue']

How do you delete a variable?

del variable name

what is the function which removes the item at the given index from the list but does not return the list?

del(listname[index])

Write a line of code that will return all the keys for a dictionary in no particular order

dictionary.keys()

Write a line of code that will return all the values for a dictionary in no particular order

dictionary.values()

How do you add a new key-value pair to a dictionary?

dictionary_name['Key'] = Value

You can access an attribute of a class using ___ notation

dot

The _____ statement is a shortcut to chaining if else statements.

elif

what is the syntax for using a lambda?

filter(lambda x: CONDITION , list_to_filter)

What are 3 ways a float can be produced?

float() Running an operation on two floats Running an operation on a float and an integer

How do you convert the integer 7 into the float 7.0?

float(7)

use the range function to perform the same task on a list as the ## for item in list: function

for i in range(len(list)):

How do you use a for loop for every item in a list?

for item in list_name:

How does using a for loop on a file work?

for line in f:

Write some code that will print the current date and time

from datetime import datetime now = datetime.now() print now

What if you want all of the math functions but don't want to keep typing in ' math. ' before calling each function, what can be done?

from math import * (Universal import)

How do you use pi?

from math import pi

How do you import just one function from a module?

from module import function

How do you use the sleep function?

from time import sleep

What will this code do? from random import randint randint(1,99)

give you a random integer between 1 and 99

A simple conditional statement taught in this course starts with the key word _____ .

if

Create a line of code that checks if user input has more than 0 characters AND is all letters

if len(INPUT) > 0 and INPUT.isalpha()

You can use an __ ________ to run code if a certain condition holds

if statement

Write a line of code that prints the square root of 25 using built in functions

import math print math.sqrt(25)

How do you convert user input (which is automatically a string) into an integer?

int(raw_input("prompt:"))

How do you print a list in reverse?

make the stride negative [::-1]

How do you open a file in append mode?

my_file = open('filename.txt', 'a')

Create a variable, my_file, and set it equal to calling the open() function on output.txt. In this case, pass "r+" as a second argument to the function so the file will allow you to readand write to it!

my_file = open('output.txt', 'r+')

How do you close the file when you are done writing to it?

my_file.close()

If statements can be _______ to perform more complex checks. This is one way to see if ______________ are met.

nested, multiple conditions

when using dot notation, does the object or the class name come first?

object

What do you have to do before reading or writing to a file?

open it (determine how you would like to)

What does this code do? class Triangle(Shape):

opens a class called 'Triangle' that Inherits the class 'Shape'

What does the use of 'w' do when opening a file?

opens in write-only mode

write a line of code that gets rid of all capitalization in the variable named parrot

parrot.lower()

What should the first argument passed to __init__() be?

self

What should you use as the first parameter when instantiating a class?

self

How do you call a method from another method that is from the same class?

self.method_name()

my_file.write() will only take what as an argument?

strings

As with integers and floats, _______ in Python can be added, using a process called __________.

strings, concatenation

what is the output of: 'python'[2]

t (always begin counting from 0)

what is inheritance?

the process by which one class takes on the attributes and methods of another

what will this code do? letters = ['a' , 'b' , 'c'] print ' '.join(letters)

will print the letters list with a space in place of the quotation marks and commas

What is the syntax for using with and as?

with open("file", "mode") as variable:

In-place operators allow you to write code like 'x = x + 3' more concisely, as:

x + = 3

When looping over the dictionary do you get the key or the value?

you get the key which you can use to get the value.

Dictionaries are enclosed in __.

{}


Ensembles d'études connexes

Leadership exam 2 part 3 (ch. 18,19,20)

View Set

Managing Checking and Savings Accounts

View Set

Bio 112 chapter 13 Quiz/Multiple choice study test

View Set