Week 1: Basics of Python 3

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

what is a dictionary in python? (Video 1.2.7: Dictionaries)

Dictionaries are mappings from key objects to value objects. They consist of Key:Value pairs, where the keys must be immutable and the values can be anything. Dictionaries themselves are mutable.

Why may you not edit the key "Tim" to "Tom"? "Tom" is not a valid dictionary key. "Tom" is already used as a dictionary key. Dictionary keys are not mutable. Dictionaries are not mutable. (CC 1.2.7: Dictionaries)

Dictionary keys are not mutable

What is the difference between == and is ? (CC 1.1.6: Expressions and Booleans)

== tests whether objects have the same value, whereas is tests whether objects have the same identity.

what does a compound statement consist of? (Video 1.3.3: Statements)

A compound statement consists of one or more clauses, where a clause consist of a header and a block or a suite of code. The clause headers of a particular compound statement start with a keyword, end with a colon, and are all at the same indentation level. A block or a suite of code of each clause, however, must be indented to indicate that it forms a group of statements that logically fall under that header.

what is the distinction between shallow and deep copies of objects? (1.3.2: Copies)

A shallow copyconstructs a new object whose contents refer to the original object In contrast, a deep copy constructs both a new variable name as well as a new object with new content, but equal values to the original

True/False: Different numeric types can't be mixed up (Video 1.1.4: Numbers and Basic Calculations)

False

True/False: Elements of a tuple should be of the same type. (Video 1.2.3: Tuples)

False

True/False: one can't splice a string (Video 1.2.5: Strings)

False

what is the output of the following python boolean expression: True and False (Video 1.1.6: Expressions and Booleans)

False

True/False: sets can be concatenated using "+" (Video 1.2.6: Sets)

False.

True/False: Python is statically typed language. (Video 1.3.1: Dynamic Typing)

False. Python is dynamically typed.

True/False: one gets an error when arithmetic operations like + or * are used with sequences of the same type like strings. (Video 1.2.5: Strings)

False. when "+" is used with sequences it means concatenation. For example "at"+"_"+"home"="at_home". and "*" means repeat. For example 3 * "hi" = "hihihi"

True/False: Mutable objects in Python with identical content have the same identity. (Video 1.3.1: Dynamic Typing)

False. Mutable objects in Python can be identical in content and yet be actually different objects.

True/False: a variable can reference another variable. (Video 1.3.1: Dynamic Typing)

False. A variable can only reference an object

True/False: sequences of different type can be concatenated together. (Video 1.2.5: Strings)

False. Concatentating ,say, a tuple to a list will give an error.

True/False: sets are immutable. (Video 1.2.6: Sets)

False. Despite that a type of sets called frozen set is immutable, sets are normally mutable.

True/False: a collection of lists can be assigned to a set. (Video 1.2.6: Sets)

False. Sets are a collection of unique immutable objects

True/False: sets are ordered a collection of mutable objects. (Video 1.2.6: Sets)

False. Sets are an unordered collection of unique immutable objects like numbers and strings.

True/False: the output of the following expression is [10,4,2,9] x = [5,2,1,3] y = [5,2,1,6] x+y (1.2.2: Lists)

False. The correct output is the concatenation of the two lists x and y [5,2,1,3,5,2,1,6]

why is integers are never too long to fit into python's integer type

Because integers in python have unlimited precision

what is the difference between static typing and dynamic typing? (Video 1.3.1: Dynamic Typing)

Static typing means that type checking is performed during compile time,whereas dynamic typing means that type checking is performed at run time.

Which of the following data structures may be used as keys in a dict? Strings Lists Tuples (CC 1.2.7: Dictionaries)

Strings, Tuples

what does "_" mean in the interactive mode of python? (Video 1.1.4: Numbers and Basic Calculations)

The "_" returns the last calculated value

explain the output and comment on the behaviour of reverse() function x = [1,2,3,4,5] x.reverse() x (1.2.2: Lists)

output is [5,4,3,2,1]. The reverse function works in place by reversing the order of the elements within the original object.

what is the difference between strings and lists?

strings: -immutable. -a sequence of individual characters list: -mutatble -a sequence of any type of python objects

How can you use a list comprehension, including if and for, to sum the odd numbers from 0 through 9? (CC 1.3.5: List Comprehensions)

sum([number for number in range(0,9) if number%2 != 0]

how to compute the sum of numbers in the following tuple x=(1,3,4,2) (Video 1.2.3: Tuples)

sum(x)

Does pyhon code need compiling before running? (Video 1.1.1: Python Basics)

No. python is an interpreted language.

True/False: multiple variables can reference the same object. (Video 1.3.1: Dynamic Typing)

True.

True/False: sets contain a unique collection of unordered objects. (Video 1.2.6: Sets)

True.

True/False: adding a key, value pair to the dictionary automatically updates the view objects of the keys and values of the dictionary. (Video 1.2.7: Dictionaries)

True. As the dectionary is modified, the view objects will change automatically.

True/Function: when a function is defined we later reassign the function object to a new name. (Video 1.3.7: Introduction to Functions)

True. The def statement creates an object and assigns it to a name. This means that we can later in the code reassign the function object to another name.

what's tuples in python? (1.2.3: Tuples)

Tuples are immutable sequences typically used to store heterogeneous data.The best way to view tuples is as a single object that consists of several different parts. One especially important use case is when you want to return more than one object from your Python function.In that case, you would typically wrap all of those objects within a single tuple object, and then return that tuple. For example, make a list of tuples.

what are the types of sequences in python? (Video 1.2.1: Sequences)

lists, tuples, and so-called "range objects". strings are also sequences.

how to interpret a negative index? (Video 1.2.1: Sequences)

a negative index means backward. So, to get the last element in a sequence x, we would simply write x[-1]

create a text file called "intro" containing the following three lines: My name is Mohamed I got into programming by learning python 5 years ago Now I'm trying to study the language again and practice it more (Video 1.3.6: Reading and Writing Files)

file = open("intro.txt", "w") file.write("My name is Mohamed\nI got into programming by learning python 5 years ago\nNow I'm trying to study the language again and practice it more\n") file.close()

how to check if a character is part of a string? (Video 1.2.5: Strings)

"character" in "string_that_might_contain_the_character"

Consider the following tuple and index (1,2,3)[-0:0] . What will this return? (CC 1.2.1: Sequences)

() Python includes all values from the beginning of the first index in the slice up to and not including the second value in the slice. In this case, the slice contains no indices, not even 0, so it returns an empty tuple.

Consider a list x=[1,2,3]. Which index corresponds to 2 in x? (CC 1.2.2: Lists)

1

Consider the following tuple and index (1,2,3)[-0] . What will this return? (CC 1.2.1: Sequences)

1 Counting from index 0, this moves backwards 0 steps, which is still index 0. For this tuple, this returns value 1.

what are the different types of numbers in Python? (Video 1.1.4: Numbers and Basic Calculations)

1-Integers 2-floating points 3-comples numbers

True/False: the function methods keys and values returns lists of keys and values of the dictionary, respectively. (Video 1.2.7: Dictionaries)

False. The type of the object is not a list. it's what is called a view object.

True/False: the type of the following object is tuple x=(2) (Video 1.2.3: Tuples)

False. The type of x is integer. To create a one element tuple, the syntax should be as follows x(2,)

True/False: the functions sort and sorted work in the same way. (1.2.2: Lists)

False. These two functions do the same task of sorting a sequence in two different ways. sort() function reorders the elements within the original list being sorted. One the other hand, sorted() creates a new list with the elements of the original list sorted, but without modifying the order of elements in the original list.

True/False: Variable names and objects are stored in the same part of computer's memory. (Video 1.3.1: Dynamic Typing)

False. Variable names and objects are stored in different parts of computer's memory.

True/False: a substring of characters in a string can only be replaced with another substring of the same length. (Video 1.2.5: Strings)

False. a subtring can be replaced with another string, using the replace function method, even if it was an empty string.

True/False: sets can be sliced like lists and tuples. (Video 1.2.6: Sets)

False. sets cannot be indexed

True/False: the function method split() splits a string into a tuple of multiple substrings.

False. split() gives a list of substrings

True/False: count() method throws an error when it counts a non-existing element in a sequence. (Video 1.2.3: Tuples)

False. the count of a non-existing element is 0

True/False: to add a new object to a set, one can use the function method append() (Video 1.2.6: Sets)

False. the function method add() is used to add a new object to a set

True/false: random.choice will not work on immutable types. (CC 1.1.5: Random Choice)

False: random.choice only requires that the object has several values regardless of mutability.

When to use while loop and when to use for loop? (Video 1.3.4: For and While Loops)

For a While Loop you're testing some condition some number of times. When you enter that loop you don't know how many times exactly you'll be running through that loop. This is in contrast with For Loops where when beginning the loop, you know exactly how many times you would like to run through the block of code.

what is a sequence in python? (Video 1.2.1: Sequences)

In Python, a sequence is a collection of objects ordered by their position.

how does slicing work in python? (Video 1.2.1: Sequences)

In python, slicing works by extracting all the elements from a sequence covered by a range of numbers representing the indices of a sequence, except the last number. For example, x[0:5] will extract all the elements with the indices from 0 to 4, but not 5. Always remember that indices in python starts at 0.

what is the similarity and difference between the following two python expressions: m = x m = x[:] (Video 1.3.1: Dynamic Typing)

The two expressions assign the content of list x to m. The first one creates a new variable called m that reference to the same object as x. The second one creates a new variable called m and creates a new object that have the same content as the object referenced by x.

Consider the dictionary: age={'Tim':29, 'Jim':31, 'Pam':27, 'Sam':35} age[0] returns an error. Why? For dictionaries, indices begin with 1 . In this dictionary, no one has age 0 . 0 is not a valid key to add to a dictionary. There is no key 0 in the dictionary. (CC 1.2.7: Dictionaries)

There is no key 0 in the dictionary.

Consider the following function: def modify(mylist): mylist[0] *= 10 return(mylist) L = [1, 3, 5, 7, 9] M = modify(L) M is L What is the value of the final line? True False This code contains an error. (CC 1.3.7: Introduction to Functions)

True

True/False: Your integer will never be too long to fit into python's integer type. (Video 1.1.4: Numbers and Basic Calculations)

True

True/False: elements inside dictionaries lack order like sets. (Video 1.2.7: Dictionaries)

True

True/False: ranges are immutable sequences. (Video 1.2.4: Ranges)

True

True/False: strings are immutable (Video 1.2.5: Strings)

True

what is the output of the following python boolean expression: True and not False is True (CC 1.1.6: Expressions and Booleans)

True

what is the output of the following python boolean expression: True and not False (Video 1.1.6: Expressions and Booleans)

True

what is the output of the following python boolean expression: True or False (Video 1.1.6: Expressions and Booleans)

True

True/False: A variable is a reference to the given object. (Video 1.3.1: Dynamic Typing)

True.

True/False: all names created or assigned in a function are local of that function and they exist only while the function runs. (Video 1.3.7: Introduction to Functions)

True.

Define Typing or assigning in programming. (Video 1.3.1: Dynamic Typing)

Typing or assigning data types refers to the set of rules that the language uses to ensure that the part of the program receiving the data knows how to correctly interpret that data.

what is the output of the following expression? odd= [1, 3, 5, 7] odd.append(9) odd (1.2.2: Lists)

[1,3,5,7,9] append function adds the number 9 to the end of the list odd

chose the correct output of the code below: def modify(mylist): mylist[0]*=100 l = [1,3,4,5] modify(l) l [1,3,4,5] [100,3,4,5] (Video 1.3.7: Introduction to Functions)

[100,3,4,5]

Consider the following code: L1 = [2,3,4] L2 = L1 L2[0] = 24 What does L1 equal? [24, 3, 4] correct [2,3,4] incorrect This code contains an error. (CC 1.3.1: Dynamic Typing)

[24, 3, 4] correct Explanation. Because [2,3,4] is a mutable object, L1 and L2 still refer to the same object when its contents are altered.

create a list of squared numbers from 0 to 9 using list comprehensions (1.3.5: List Comprehensions)

[number**2 for number in range(0,9)]

what is the line-break character? (Video 1.3.6: Reading and Writing Files)

\n is the line break character. It's added to the end of each line to start a new line after. line-break character is a ninja, it's always there, but you can't see it.

explain the following code: x = [list of objects of the same type] random.choise(x) (1.1.5: Random Choice)

chose a random object from the list x

explain how range objects in python save space? (Video 1.2.4: Ranges)

defining a sequence of,say, mililion number can be represented by only three numbers, the first number, the last number, and the size of the increment.

why we should strip the line-break character from the end of the lines being read into python? (Video 1.3.6: Reading and Writing Files)

going to cause extra line breaks in subsequent processing of your text. In other words, python will add an empty line after the line that ends with a line-break character.

what does "//" numeric operation mean? (Video 1.1.4: Numbers and Basic Calculations)

integer division

what does "w" indicate in the expression below: file = open("intro.txt", "w") (Video 1.3.6: Reading and Writing Files)

it indicates that the file is for writing not reading

what is the concept of polymorphism in python? (Video 1.2.5: Strings)

it means that arithmetic operations like "+" and "*" when used with sequences have different functions, concatenation and repeation, respectively.

what is an "expression" in python? (Video 1.1.6: Expressions and

it's a combination of objects and operators that calculates value

what does len() function do in python? (1.2.2: Lists)

it's a generic function that gives the length of a sequence object.

find out the number of unique elements in the string below: "adsfasfasfasgereerwtwetewtggdsgd" (Video 1.2.6: Sets)

len(set("adsfasfasfasgereerwtwetewtggdsgd"))

what is the function of "-" in set operations? (Video 1.2.6: Sets)

set_1 - set_2 gives the objects in set_1 that are not in set_2

Which of the following lines of code will fail to return the integers 0 through 9 in a single string? "0"+"1"+"2"+"3"+"4"+"5"+"6"+"7"+"8"+"9" "".join([str(i) for i in range(10)]) str(range(10)) string.digits (using the string library) (CC 1.2.5: Strings)

str(range(10))

how to concatenate a number of sequences of the same type side-by-side? (Video 1.2.3: Tuples)

the "+" is a generic function for concatinating a sequences of the same type together. sequence_1+sequence_2+sequence_3

what is the difference between the following two comparisons: 2 == 3 [2,3] == [3,3] [3,3] == [3,3] [3,3] is [3,3] 3 == 3.0 (Video 1.1.6: Expressions and Booleans)

the first one compares the two values only and gives False. the second one works in an element-wise fashion. So it's multiple comparisons. The answer to this one is False since the first element in the two lists is not the same. third one gives true since the same elements from the two list are the same. Fourth one gives False despite that lists have the same values. This is because "is" compares the identity of the objects. And since they are different objects, they have different identities. The fifth one compares two numbers of different types. in this case, python converts the first number from integer to floating-point. now it's 3.0. which is the equal to the second number. and gives True

how to know the functional methods available a python object? (Video 1.2.5: Strings)

the function dir can be used for this task to get the directory of all arttributes.

Given the fact that strings are immutable, is there a way to alter a string object? (Video 1.2.5: Strings)

the function method replace() allows the replacement of a character with a nother one. The following is an example on how to basicly use the function to get a string called "mohamed" "XohaXed".replace("X","m")

how to cut a string into smaller substrings? (Video 1.2.5: Strings)

the method function split() takes a string and a character where the function splits the string.

what does a pass statement do? (Video 1.3.3: Statements)

the pass statement is used to do nothing in situations where we need a placeholder for syntactical reasons.

what is the output of the following expression: set(range(0,11)) (Video 1.2.6: Sets)

this will give a set of numbers from 0 to 11

Explain the operation of tuple packing and depacking. (Video 1.2.3: Tuples)

tuples packing: combining two objects into a tuple x=1 y=5 coordinates = (x,y) tuples depacking: assign the elements of a tuple to different objects (x_coordinate, y_coordinate) = coordinates

how to get the elements of a python range object? (Video 1.2.4: Ranges)

turn the range object into a list as follows list(range(1,2,3,4))

what are the set operations in python? (Video 1.2.6: Sets)

union is achived using "|" and intersection is achived usin "&"

how to check for membership in a dictionary? (Video 1.2.7: Dictionaries)

using the "in" boolean operation, one can check for the membership of a string in the keys of a list

How to strip the line-break character from the end of a line? (Video 1.3.6: Reading and Writing Files)

using the rstrip() method.

how to loop over a dictionary and get the same values each time ordered according to the corresponding key? (Video 1.3.4: For and While Loops)

we can first sort the keys of the dictionary: for key in sorted(dictionray.keys()): print(dictionray[key]) the reverse order of the dictionary can be obtained by adding reverse=True attribute to sorted() function as follows for key in sorted(dictionray.keys(), reverse= True): print(dictionray[key])

Consider a list x=[1,2,3] . Enter the code for how you would use the append method to add the number 4 to the end of list x . (CC 1.2.2: Lists)

x.append(4)

what is the number of 5s in the following tuple x = (1, 2, 3, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 4, 4, 4, 4, 1, 1, 1, 1, 1) (CC 1.2.3: Tuples)

x.count(5)

Consider again sets x={1,2,3} and y={2,3,4} . Which of the following lines of code will determine if all elements of x are in y ? x.issubset(y) x.isin(y) x.is_in(y) x in y (CC 1.2.6: Sets)

x.issubset(y)

Consider the following tuple x= (1,3,45,4,3). what will the following expressions return? x[1] x[0] x[0:1] x[0:2] x[0:-1] x[-2] x[-2:0] x[-2:-3] x[-2:-1] x[-4:1] x[-4:-1]

x[1] 3 x[0] 1 x[0:1] (1,) x[0:2] (1, 3) x[0:-1] (1, 3, 45, 4) x[-2] 4 x[-2:0] () x[-2:-3] () x[-2:-1] (4,) x[-4:1] () x[-4:-1] (3, 45, 4)


Kaugnay na mga set ng pag-aaral

Statistical and Non-Statistical Questions

View Set

Web and UX + UI Design Principles = Heuristic Principles (Derived from Nielsen's Heuristics)

View Set

Health Assessment Case 7: Jared Griffin (PRE)

View Set

Exam 3: chapter 53 saunders adult health i

View Set

AP Psych Review Multiple Choice Questions

View Set

Memory-Psych unit 3 area study 2

View Set

C706 - Chapter 5 -- Design and Development (A3)

View Set

Brunner-Suddarth Med-Surg 13th Ed. Ch. 42

View Set

GA Real Estate Exam Practice Questions

View Set

Free Cash Flow, Market-Based, Residual Income & Private Company Valuation (R31, R32, R33, R34)

View Set