Python partial

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

What's the difference between "=" and "=="?

"=" is an assignement operator whereas "==" is a comparison operator used in boolean expressions

Exercice: In Python, the instruction '2' + '8' returns:

'28'

Write a single text string to show the following city names on three different lines: New York Paris London

'NewYork\nParis\nLondon\n'

What are the different espace codes?

*\n* send the text to a new line *\t* indents the text by a tab *\* allows to exclude a character

Exercice: What happens if this program is run? name = "Marie" name_list = ["Pierre", "Paul", "Jacques"] print(name + name_list)

A TypeError occurs because the operator + is applied to two objects of different type (in this case, a string and a list)

What is the *webbrowser module*?

Allows opening a URL in the browser. One of the most relevant function is: *webbrowser.open(URL)*, which asks the browser to open URL

Which characteristics does the .find() method has?

It finds the first element and returns its index; it is case sensitive

Is it possible to have nested conditions in Python?

Yes, just like in Excel, you can nest if-else statements

Which mode arguments exist to the open function? What does adding a + to the mode do?

*'r'*: opens the file in read-only mode. If the file is opened in this way, it is not possible to modify the data or write to the file. This is the default mode if the mode argument is omitted. When accessing the file Python is positioned at the beginning of the first row (position 0). If the file does not exist, Python returns an error *'w'*: the function opens the file in write mode. If the file already exists, the data it contains are deleted when it is opened. If the file does not exist, it is created automatically *'a'*: the function opens the file in append mode. When accessing the file Python is positioned at the end of the last row, therefore all data that Python writes in the file are added to the end of the existing content. If the file does not exist, it is created automatically and Python is positioned at the beginning of the file The *+* symbol after the mode enables a double mode of access to the file

What are the uses of the break and continue functions?

*Continue:* in for and while loops, it might happen that the loop has to be suddenly interrupted, when specific conditions occur *Break*: at other times, it is necessary to move on to the next loop iteration, when specific conditions occur

What is the difference between lists and tuples?

*Lists are mutable* and are enclosed in square brackets *[ ]* *Tuples are immutable* and are enclosed in parentheses *( )*, although they aren't necessary

What's an *object*? What's a *class*? What's an *instance*?

*Object:* is the abstract definition used for elements that are characterized by attributes (how it is made) and methods (how we can modify and use it) *Class:* is the abstract description of an object. It represents the set of objects («family») of a certain type. A class is made of attributes and methods *Instance:* is the term used for a specific «real» object of a class

What types of decision making structures can be implemented? Which keywords are used by each structure?

*Simple* decision-making structure: if *Alternative* execution (or double alternative): if-else *Chained conditionals:* if - elif - else

Exercice: What is the output of the following instructions? 1) 'A' in [('A', 'B', 'C'), ['X', 'Y'], 'AZ'] 2) 'A' in {'A': 10, 'B': 11, 'C': 12} 3) 11 in {'A': 10, 'B': 11, 'C': 12}

1) False, because the operator in checks if one or more elements of the list are exactly equal to 'A' 2) True, because the operator in checks if *key* 'A' belongs to the dictionary 3) False, because the operator in checks if *key* 11 belongs to the dictionary, yet here 11 is a value and not a key

Which logical operators (aka Boolean operators) are there?

*and:* Returns True when all the arguments are true, otherwise it returns False *or:* Returns True when at least one of the arguments is true, otherwise it returns False *not:* Returns True if the argument is false and False when it it true

What must always be use with "while True"?

*if* and *break* statements must both be employed, but there is no need to previously initialise the variable, while it is necessary in the standard "while" loop

Which data types does Python have?

*int:* integer of arbitrary size *float:* floating-point number *bool:* for true or false values *str:* used to represent types You can find the type of the variable by using the built-in type function. Be careful! '43' in quotation marks will be a str, whereas 43 without quotation marks will be an integer. If you want to convert '43.7' to an integer, you first have to convert the string to a float, and then the float to an integer which will cut the .7 off and return 43

Which methods can be used to remove elements from a dictionary?

*x = dict_name.popitem()* removes the *last pair key-value* and returns it in a tuple, which is assigned to variable x in the example written above *y = dict_name.pop(k)* removes the pair key-value corresponding to key k and returns it in a tuple, which is assigned to a variable y in the example written above. XXXXXXX clarifications necessary

Which functions and methods are used to modify the order of the element of a list?

- *Function sorted:* it requires the list to be sorted as an argument and returns the sorted list --> the original list is not modified - *Method sort:* it modifies the list to which it is applied, sorting the elements - *Method reverse:* it modifies the list to which it is applied, reversing the current order of elements Remember: methods modify the original list whereas functions don't !!

Which types of errors can occur in a program?

- *Syntax errors:* eg. missing colon in the header of a function, missing quotes in a text string, using a Python keyword as a variable name, mismatch between opening and closing brackets... - *Runtime errors:* ZeroDivisionError, NameError (when the program calls a variable which isn't yet defined), TypeError(when an operator is applied to unsupported types of data or mandatory arguments are missing), ValueError (when a program tries converting a text string into a number) - *Semantic errors:* occur when the program is executed without producing error messages, but the results are not the correct ones; they derive from the wrong code design

What are modules in Python? Which examples are there?

- In Python, additional functionalities come as modules: these are *files acting as containers, grouping useful functionalities* by the topic they relate to - *math* and *random* are examples of modules - Modules installed by default with Python make up the *Python standard library* Assuming a module is installed, in order to use it we need to *import it into the program's running session*. Importing is valid only for the current session!

What are the main features of Python?

- It is a high level programming language and it is interpreted, interactive and object-oriented *Interactive:* possible to write several instructions in the shell *Object-oriented:* the solution not expressed as a sequence of instructions but actually in terms of objects and their attributes - It is both procedural and declarative *Procedural:* algorithms which lead to an objective *Declarative:* describing reality and declaring a requested objective

What is the constructor *method __init__*

- It is the method that Python search in the class when it has to initialize the state of an object - It *can include the definition of the attributes and of any other feature* and option needed to the objects of the class, like: call of functions, opening of files, access to databases etc. - The syntax follows the *same rules used when defining a function*, with the parameters (mandatory or optional) that are used to initialize the attributes, specified in parentheses - There must be at least one parameter - *conventionally named self* - that represent the reference to the name of the instance that will be create

Exercice: What is the output of the following instructions? 1) 'a' in 'ABRACADABRA' 2) 7 in '7up' 3) '41' not in 'sum41'

1) False, remember that Python is a case sensitive language! 2) TypeError because the left operand of the operator in must be a string when it searches for an element in a string 3) False, because in this case '41' has been correctly enclosed as a string, and therefore '41' is in 'sum41'

Exercice: what is the output of the following instructions? 1) min([5000, 'a', 'z']) 2) max(['4', 'python', 'z']) 3) max([1, (100, 200), 3, 10])

1) TypeError, because functions min and max need homogeneous data 2) 'z', because here the '4' is in quotes and therefore it is a string so it's possible to apply the max function since the data is homogeneous. Then, when you have numbers as a string, they are always at the beginning (even before the letter a). If you start from these observations, here the max is 'z' because it is greater than 'p' from 'python' and also greater than a number (here 4) 3) TypeError, because functions min and max need homogenous data

State 3 rules which must be applied when writing a list of parameters of a custom function:

1. Parameters must be separated by commas 2. Mandatory parameters come before optional parameters 3. A default value must be assigned to each optional parameter

Which elements are contained in the header of a custom function?

1. The keyword def 2. The function's name 3. A set of parentheses containing the function's parameters, separated by commas 4. The symbol :

Which syntax rules must be applied when you implement a simple decision-making structure?

1. The structure needs a *heading* and a *body* 2. The heading contains, in the following order: the *if keyword*, a *boolean expression* and a *:* punctuation mark 3. The body must be indented

Which comparison operators are there?

== : equal to != : different from > : greater than >= : great than or equal to < : less than <= : less than or equal to

What is the difference between local and global variables? What is the scope of a variable?

A *global variable* can be reached by any instruction in a program A *local variable* can be reached only within its scope, that is within the part of the program in which it is defined, such as a function The *scope of the variable* is the part of program in which a variable can be reached

What is the difference between a void and productive function? When do you need a return statement?

A *productive* function is a set of instructions that performs a specific task returning, when it ends, a value to the instruction that called it. A function that performs a specific task but doesn't return a value when the instruction that called it ends is a *void (empty) function* The return statement must be used in *productive* functions, i.e. when a value must be returned to the instruction which called the function

What is an iterable?

An iterable is a *Python object that can be used as a sequence*. You can go to the next item of the sequence using the next() method. You *can loop over an iterable, but you cannot access individual elements directly*. It's a *container object*: it can only return one of its element at the time.

What's the difference between .append() and .insert() methods?

Both methods add elements to the list, but: .append(element) adds the element to the end of the list, with only necessary argument the element to add; .insert(element, index) inserts the element in the list in the position specified by index

What's the difference between .remove() and .pop() methods?

Both methods remove elements from the list but: .remove () asks for the element to be removed and returns none as output .pop() asks for the index of the element to be removed and returns the removed item as output

Exercice: complete the following program to traverse the *list* band_list and print its elements on the screen: CODE 1: band_list = ['Queen', 'AC/DC', 'Muse', 'REM'] #missing code ....print(n) CODE 2: band_list = ['Queen', 'AC/DC', 'Muse', 'REM'] #missing code ....print( band_list[i])

CODE 1: band_list = ['Queen', 'AC/DC', 'Muse', 'REM'] for n in band_list: ....print(n) Remark: in this code, we're telling the program to go check out the list, and print out each element one by one CODE 2: band_list = ['Queen', 'AC/DC', 'Muse', 'REM'] for i in range(len(band_list)): ....print( band_list[i]) Remark: in this code, we're telling the program to check out the length of the list and make the index i go up one by one, printing out each element one by one

What are custom modules? How do you install them?

Custom modules are *specialized modules*, usually intended for niche audiences, that must be installed by the user To use a custom module it is necessary to *download and install it* following the instructions, or simply running the command *pip install modulename from the command line* of the operating system: - Windows: write cmd in the search box of the Windows menu - MacOS: open the Terminal application

How do you call a function? Where can a function be called?

Defining a function allows Python to understand which task must be performed, but it doesn't execute it. Each time we want to execute a function, it is necessary to call it using the following syntax: *function_name()* A function can be called in the *Python shell, by a program or by another function*. Also, if *parameters* have been specified in the definition, their value must be written in parentheses

Exercice 1 : complete the following program to traverse the *dictionary* band_dict and print its elements on the screen: band_dict = {'A': 'Queen', 'B': 'AC/DC', 'C': 'Muse', 'D': 'REM'} #missing code ....print(band) Exercice 2: complete the following program to traverse the dictionary band_dict and print its pairs key-value separated by a dash band_dict = {'A': 'Queen', 'B': 'AC/DC', 'C': 'Muse', 'D': 'REM'} #missing code ....print( key, "-", band_dict[key])

Exercice 1: band_dict = {'A': 'Queen', 'B': 'AC/DC', 'C': 'Muse', 'D': 'REM'} for band in band_dict.values(): ....print(band) Remark: here we are using the .values() method to obtain the values in the band dictionary Exercice 2: band_dict = {'A': 'Queen', 'B': 'AC/DC', 'C': 'Muse', 'D': 'REM'} for key in band_dict: ....print( key, "-", band_dict[key]) Remark: here we aren't using a method, just the fact that the name of the dictionary followed by [key] will return the related value

What is IDLE?

IDLE (Integrated Development and Learning Environment) is the programming environment included in the Python installation and it contains a *shell*, which allow you to write and immediately run single lines of code, and an *editor*, which allow you to create programs to be saved and executed whenever you wish

What is the *random module*?

It allows to generate random numbers, with some useful functions: - *random.random()*: Returns a random decimal number between 0 and 1 - *random.randint(min, max)*: Returns a random integer number between min and max - *random.choice([list])*: Returns a random element from the list given as argument -*random.randrange(min,max,step)*: Returns a random integer between min and max with an increase of step

What is a string?

It is a *sequence of characters (alphanumeric and symbolic)* enclosed in single or double quotes. Strings cannot be modified because they are *immutable*; the only way to add, remove or modify their elements is by reassigning a new string to the variable

What is the *os module*?

It is a Python module to interact with the Operating System, quite useful to inspect and manipulate files and folders. Some of its functions are: - *os.listdir([path])*: Returns a list with names of files and folders available in the folder specified as argument - *os.path.join(path,filename)*: Returns the complete path of a file (filename argument) in the specified folder (path argument) - *os.path.isfile(path)*: Returns True if the path is referring to a file, False otherwise

What is a docstring? How can you show the content?

It is a text string used to document a function. To create one you need to enclose the text string between triple quotes and write the text string in the function's definition after the header line. You can show the content (other than it being visible in the function's code) can be shown using the help function and in the function's call tip

What does exception handling mean?

It means writing a code to handle any possible error which might occur when the program is run. When an exception is not handled, it casues an error and the exit from the block of instructions in which it occurs or from the program. The try...except structure is used to handle errors

What is a call tip? How do you activate it?

It's a message which appears when you type a function. Call tips show the list of arguments required by the function and a short description of how it works. You activate call tips through edit --> show call tip

What is a sequence?

It's an object holding multiple items, stored one after the other. *Lists and dictionaries are mutable*, whereas *tuples and strings are immutable*

What is *slicing*?

It's the operation in which a portion of a sequence is selected. You can also use slicing to *reverse* the order of the string, using *[::-1]*

Which types of loops are available in programming languages? Which instructions are used in Python?

Loops can be controlled by a counter (for) or by a condition (while)

How can you access a file?

To access a file in Python we use the *built-in function open* - It opens a file and returns an object of type file to which is associated to the content of the specific file that has been opened - If the file cannot be opened, an *error* is raised - Opening a file implies the *creation of a variable* to which the object should be assigned

How can you create a class?

To create a class you need to *give it a name and define its attributes and/or methods*. All instances of the class inherit attributes and methods of the class to which they belong. Attributes and methods inherited by individual instances *can be assigned in the creation phase of the instance and/or changed at a later time*

Which character is needed to end a line of text when writing to a file?

To end a line of text when writing to a file, the *new line ("\n")* character is needed

More about the try....except structure

The *try* block lets you test a block of code for errors while the *except* block lets you handle the error. You can define *as many exception* blocks as you want !

Why are the following instructions different? x+=3 x=+3

The 1st instruction will add 3 to the current value of the x variable and is equivalent to x = x + 3 The 2nd instruction will assign the value 3 to variable x

What is the difference between using the comma separator in the print function and the "+" to concatenate?

The comma separator concatenates inputed elements together and can mix variable types, eg. print(4, "kg of chocolate a day brings", calorie, "calories a day but keeps the doctors away!") where 4 is an int, the second one is a string and calorie is a variable previously defined

What do reading methods do?

The content of a file *can be read entirely or line by line:* - The *read* method reads the contents of the *entire file* - The *readline* and *readlines* methods read the content *line by line*

Which characteristics does the .join() method have?

The iterable object received as argument by the join method must contain only strings. For example, if you try using this method on this list fileinfo = ["Python", 2021, 05, 21] filename = "-".join(fileinfo), you will get a TypeError because you are trying to join strings and int

What is the difference between sequential and decision-making structures?

The order in which program statements are executed hangs on a defined logical pattern, which is called control structure. - *Sequential:* set of statements which are executed in the order they occur - *Decision-making:* a certain action is performed only when specific conditions happen

What is super important to remember when using the range function?

The range function's syntax is (start, stop [, step]) It returns an object that produces a sequence of integers from start(inclusive) to stop(exclusive) by increments of step(optional parameter). If a step is given, it can specify the increment or decrement. Whether the step is positive or negative, the first argument will always be included and the second will always be excluded. If you want to include the upper bound, you gotta add 1 to it!

Exercice: Which instruction must be executed before you run the sqrt function?

import math

Exercice: rewrite the following program using a while loop for j in range(6, 15, 3): ....print(j)

j = 6 while j < 15: ....print(j) ....j += 3 Notice how we initialise j at value 6 and tell the program that while j is smaller than 15, we should update j and add 3 to it

What is a built-in function? Which color is applied by IDLE to built-in functions? Give some examples

They are functions integrated in the standard Python installation . IDLE applies a purple color to built-in functions Examples: print, input, help, type, format, str, int, float, min, max, abs

State some variable names criteria:

Variable names mus be short and meaningful, must start with a letter or the underscore character ( _ ), and then can be followed by numbers, letters or underscores. They cannot contain spaces or special characters (@, &, $, ...) nor consist of reserved Python words (keywords) such as while, if, or function names. Although it isn't recommended, it is possible to use accented names

What is the *special method __str__*

What if we just use the name of an instance as argument of a print function? - The *printout* will be the result of the special method __str__ - It *has no arguments (besides self)and must end with the return statement*

Which operations yields an int to become a float?

When a division ("/") is performed, the result is automatically a float, even if it's a whole number (eg. 16/4 will give 4.0, i.e a float) Also, if you want to check if a number is not an integer t, you can use the following line of code: float(x) != int(float(x))

A few formatting rules: - f specificies that the number that you want to obtain is a floating point - .2 indicates that we want to *round off* the number to the second decimal place - "," the comma adds the thousands separator - the "%" symbol is used to format in percentages What would be the result of the following formats? a) '.2f' b) '.1%' c) ',.0f'

a) '.2f' = 2 decimal places b) '.1%' = 1 decimal place percentage (eg. x = 0.297082 will be '29.7%') c) ',.0f' = 0 decimal place and thousands separator (eg. y = 1096450.78 will be '1,086,451')

Which colors do these correspond to in IDLE? a) purple b) green c) red d) blue e) orange

a) *purple* = built-in functions (print...) b) *green* = strings between "" and comments between """""" (called docstrings) c) *red* = errors and comments preceded by # d) *blue* = output of the instruction or name of function e) *orange* = keywords (if, else...)

Exercice: insert the missing lines of code in order to print all combinations you can get by throwing a 4-sided die and a 6-sided die for d1 in range(1,5):

for d1 in range(1,5): ....for d2 in range(1,7): ........print(d1, "-", d2)

Exercice: insert the missing line of code in order to print "Access granted" when the name given by the user is different from Homer, Bart and Lisa name = input('Insert your name: ') # missing code ....print('Access granted)

if name not in ['Homer', 'Bart', 'Lisa']: (here we're creating a list and saying that if the name inserted isn't in the list, the user can access; it's a better option when there are many many names) or if name!= 'Homer' and name!='Bart' and name!='Lisa' (here we're individually setting the instruction up)

Exercice: write the heading of a decision-making structure to check if variable y is an even integer number between 4(included) and 16(included)

if y in range(4, 17, 2) why?! the bottom end is always include with the range function, but the top isn't, so the upper bound is 16+1 = 17. Then, because we want even numbers, we set the step to 2.

Which keywords are used in decision-making structures?

if, else, elif

Which keyword can be used to skip a line of code we wish to initialize later?

pass While outlining a program, we might want to temporarily print an if, while or for construct without any statement, except for a comment. This happens when we want to test the program or go along with the next statements, without concluding a certain part. The pass statement acts as a marker for the code which is going to be completed, avoiding that incomplete constructs return an error

Exercice: Rewrite the following program using a while True loop: password = input("Enter password: ") while password ! = "Yolo": ....password = input("Wrong password bro, try again: ") print("Password accepted")

while True: ....password = input("Enter password: ") ....if password == "Yolo" ....break print("Password accepted")

Exercice: write the instruction to create a list, called words, containing the words of the string loca loca = "Upside inside out, she's living la vida loca"

words = loca.split(" ") Here, we're using the split method and asking to consider the space as a separator for each element

Which instruction allow to store a decimal value received from the user, in a variable called x?

x = float(input("Please insert x: "))


Kaugnay na mga set ng pag-aaral

TechOps Junior Level Interview Questions

View Set

Chapter 12 - Work/Life balance and other Employee Benefit Programs

View Set

FOI.6 Nucleus: Understand the storage of genetic information and how it is passed down to successive generations and the principles of basic techniques in Molecular Biology

View Set

External Bones of the Cranium/Face

View Set

Psych History ch. 10, ch. 11, ch. 12, & ch. 13

View Set