Python

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

In the case of opening a file for input (read), is X

'r'

The mode string is X for input files

'r'

for output files

'w'

Any character (except newline character) [MetaCharacters]

.

Slice [Syntax]

:

not True

False

[T/F] 42 == 42.0

True

X means the string must begin with spam.

^spam

A variable name can use only letters, numbers and the __ charecter

_

All classes have a function called X, which is always executed when the class is being initiated.

__init__()

The X function is called automatically every time the class is being used to create a new object

__init__()

If you use data members with names using the double underscore prefix such as X, Python makes it a private variable, which is only directly accessible inside a class.

__privateAttr

The X keyword arguments take a list of regular expression strings to determine what the PyInputPlus function will accept as valid input

allowRegexes

A value being passed to a function in a function call is an .

argument

When you call the print() or len() function, you pass them values, called X, by typing them between the parentheses.

arguments

You'll store values in variables with an __________

assignment statement

An Object contains both X and Y

attributes, behavior

Changes the current working directory to path.

chdir(path)

items are separated with

commas

To define a function is to create it, just like an assignment statement. The X statement defines the sayHello() function

def

The X statement will delete values at an index in a list.

del

A X approach works by recursively breaking down a problem into two or more sub-problems of the same or related type

divide-and-conquer

Inputs a line of text and returns it as a string,including the newline. Returns '' if the end of file is reached.

f.readline()

Outputs aString to a file.

f.write(aString)

If there are groups in the regular expression, then X will return a list of tuples.

findall()

Returns the path of the current working directory.

getcwd()

Ensures the user enters one of the provided choices

inputChoice()

A Regex object's X method searches the string it is passed for any matches to the regex.

search()

Pass the string you want to search into the Regex object's X method. This returns a Match object.

search()

Returns a Match object if there is a match anywhere in the string.

search()

The x method will return None if the regex pattern is not found in the string.

search()

While X will return a Match object of the first matched text in the searched string,

search()

A slice goes up to, but will not include, the value at the X

second index

A common use of X is to split a multiline string along the newline characters.

split()

Python also comes with a set of modules called the

standard library

X methods return True if the string value they are called on begins with the string passed to the method

startswith()

The X is a difference between each number in the sequence.

step

This specifies the string to be searched.

str

The multiple assignment trick is also called

tuple unpacking

Method returns strings uppercase

upper()

Python will give you an IndexError error message if you use an index that exceeds the number of X in your list value.

values

A ______ is like a box in the computer's memory where you can store a single value

variable

Fields are

variables

The X matches 0 to m of the preceding group.

{,m}

To add new values to a list, use X or X methods

Append() . Insert()

A process of using details from a new class without modifying existing class.

Inheritance

Returns a match if the specified characters are at the beginning of the string

\A

Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word

\B

Any character that is not a numeric digit from 0 to 9.

\D

Any character that is not a space, tab, or newline.

\S

Returns a match where the string DOES NOT contain a white space character

\S

Backslash [Escape Character]

\\

Returns a match where the specified characters are at the beginning or at the end of a word

\b

Any numeric digit from 0 to 9.

\d

a X in a regex stands for a digit character —that is, any single numeral from 0 to 9.

\d

Newline (line break) [Escape Character]

\n

Any letter, numeric digit, or the underscore character. (Think of this as matching "word" characters.)

\w

str(29)

'29'

What is the result ?

3

>>> a = ','.join(['a', 'b', 'c']) What is the result of len(a)?

5

X store the line number of the original function call so that Python can remember where to return.

Frame objects

X is a way of creating new class for using details of existing class without modifying it.

Inheritance

As Few As Possible (shortest match)

Lazy

['cat', 'bat', 'rat', 'elephant']

List Value

Object Oriented Programming Acronym

OOP

OOP Means

Object Oriented Programming

Variables that contain arguments.

Parameters

Writes the instruction "x=36" and gives it to the Python; Python can understand the intend of the programmer, and then instruct the OS find a block of space in its managed memory space, create an Integer 36

Step One of the Three Step Rule

What does the ___init___() function do in Python

The function is called when a new object is instantiated

There are ____ rules for blocks

Three

and, or and not

Three Boolean Operators

X mode will overwrite the existing file and start from scratch, just like when you overwrite a variable's value with a new value.

Write

Returns a match for any two-digit numbers from 00 and 59

[0-5][0-9]

Continue Lines with

\

The X matches at least n and at most m of the preceding group.

{n,m}

The X matches n or more of the preceding group.

{n,}

The X matches exactly n of the preceding group.

{n}

Exactly the specified number of occurrences [MetaCharacters]

{}

Either or [MetaCharacters]

|

X code checks that values entered by the user, such as text from the input() function, are formatted correctly.

Input validation

Think of a X as a container for variables

Scope

The Python attaches the label x to the memory storage block.

Step Three of the Three Step Rule

The programmer prepares a label (i.e., a variable) x in order to refer to the value 36 later.

Step Two of the Three Step Rule

There are two types of fields - X and Y

class variables, object variables

After reading or writing a file, call the X method before opening the file again.

close()

Python ignores __________

comments

________ is just a more specific name in the context of flow control statements.

condition

When the program execution reaches a X statement, the program execution immediately jumps back to the start of the loop and reevaluates the loop's condition.

continue

AN statement that always follows an if or another X statement.

elif

All methods (i.e., behaviors) in a class have only one specific difference from ordinary functions - they must have an X that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method

extra first name

Closes an output file. Not needed for input files.

f.close()

Inputs the contents of a file and returns them as a single string. Returns '' if the end of file is reached.

f.read()

Perform a global search over a whole string. Returns a list containing all matches, or an empty list if no matches are found.

findall()

In a slice, the X is the index where the slice starts.

first integer

Indexes can be only integer values, not X.

floats

The while loop keeps looping while its condition is True (which is the reason for its name), but what if you want to execute a block of code only a certain number of times?

for Loop

When your program calls a function, Python creates a X on the top of the call stack.

frame object

Returns True if path names a file and False otherwise

getsize(path)

Returns the size of the object names by path in bytes

getsize(path)

If you need to modify a global variable from within a function, use the X

global statement

But if the variable is not used in an assignment statement, it is an X.

global variable

If there is a global statement for that variable in a function, it is an X.

global variable

The dot-star uses X mode

greedy

Returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters

istitle()

The X method is useful when you have a list of strings that need to be joined together into a single string value

join()

What's the data type of mo in the following? import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')

list

The dot-star will match everything except a X.

newline

A class variable refers to an

object

An X represents an entity in the real world with its attributes and behaviors

object

Variables that have arguments assigned to them are

parameters

When a function is called with arguments, the arguments are stored in the X.

parameters

The X function will return a randomly selected item from the list.

random.choice()

All the regex functions in Python are in the X module

re

Removes the file named path from the current working directory

remove(path)

The concept of OOP in Python focuses on creating X code.

reusable

If you need to quickly reverse the order of the items in a list, you can call the X list method.

reverse()

The X is the index where the slice ends.

second integer

This particular parameter X serves as a placeholder and refers to the actual object itself constructed from this class

self

Just as an index can get a single value from a list, a X can get several values from a list, in the form of a new list.

slice

Lists of number values or lists of strings can be sorted with the X method.

sort()

spam = spam % 1

spam %= 1

spam = spam * 1

spam *= 1

spam = spam / 1

spam *= 1

spam = spam + 1

spam += 1

spam = spam - 1

spam -= 1

The _____ function can be passed an integer value and will evaluate to a string value version of the integer.

str()

The X string method will return a new string without any whitespace characters at the beginning or end.

strip()

'Alice' * 5

'AliceAliceAliceAliceAlice'

The X operator puts the value on the right into the variable on the left.

=

Equal to

==

The X operator asks whether two values are the same as each other.

==

Greater than

>

Greater than or equal to

>=

The X matches zero or one of the preceding group.

?

'Alice' * 5.0

Error

The activity of obtaining relevant information from a collection of (commonly massive) information resources

Information retrieval

Valid or Invalid Variable name? _42

Valid

Valid or Invalid Variable name? account4

Valid

Valid or Invalid Variable name? currentBalance

Valid

Valid or Invalid Variable name? current_balance

Valid

One or more occurrences [MetaCharacters]

+

False and False

False

Valid or Invalid Variable name? 42

Invalid

An escape character consists of a X

backslash (\)

However, a string is X it cannot be changed

immutable

Tuples, like strings, are

immutable

To import a module you need the keyword

import

Technically, a for loop repeats the code block once for each item in a X

list value

Mutliline Comment [Syntax]

""" """"

A class is a X for creating objects

"blueprint"

Ends with [MetaCharacters]

$

Are tuples typed with () or []

()

Multiplication

*

The X matches zero or more of the preceding group.

*

Zero or more occurrences [MetaCharacters]

*

Exponent [Syntax]

**

The X matches one or more of the preceding group.

+

Subtraction

-

The X character in a regular expression is called a wildcard and will match any character except for a newline.

.

You can use the dot-star X to stand in for that "anything." Remember that the dot character means "any single character except the newline," and the star character means "zero or more of the preceding character."

.*

Division

/

int division / floored quotient

//

The first value in the list is at index

0

X mode, on the other hand, will append text to the end of the existing file.

Append

End when the indentation decreases to zero or to a containing block's indentation.

Blocks

X begin when the indentation increases

Blocks

The ____________ data type has only two values: True and False.

Boolean

The X is how Python remembers where to return the execution after each function call

Call Stack

The newly formed class is an X

Child Class

What statements define functions?

Def

DRY means

Don't repeat yourself

Hiding the private details of a class from other objects

Encapsulation

'Alice' + 42

Error

Errors can be handled with try and X statements.

Except

False or False

False

Regular expressions allow a user to specify a pattern of text to search for. Regular expressions can be used only in Python. [T/F]

False

T/F?

False

[T/F] 42 == '42'

False

There is only one X, and it is created when your program begins

Global Scope

Variables that are assigned outside all functions are to exist in the

Global scope

As Many As Possible (longest match)

Greedy

import re haRegex = re.compile(r'(Ha){1,3}') mo1=haRegex.search('HaHaHa')print(mo1.group())

HaHaHa

Regex Module syntax

Import re

Valid or Invalid Variable name? TOTAL_$UM

Invalid

Valid or Invalid Variable name? current-balance

Invalid

AX is created whenever a function is called

Local Scope

Parameters and variables that are assigned in a called function are said to exist in that function's

Local Scope

X Cannot Be Used in the Global Scope

Local Variables

A while is what type of statement?

Loop

Functions are

Methods

While indexes start at 0 and go up, you can also use X for the index

Negative Indexes

Escape character \n is printed as:

Newline

Can a variable name begin with a number?

No

In Python, there is a value called X, which represents the absence of a value.

None

The X value is the only value of the NoneType data type.

None

All of the values in the list after the deleted value will be moved up X

One Index

Parentheses, Exponents, Multiplication, Division, Addition, Subtraction

PEMDAS

Similarly, the existing class is a X

Parent Class

X is a Python module used for serializing and de-serializing Python object structures, also called marshalling or flattening

Pickle

A concept of using common operation in different ways for different data input.

Polymorphism

If the user ever enters invalid input, such as a badly formatted date or a number that is outside of an intended range, X will prompt them for input just like our code in the previous section did.

PyInputPlus

X contains functions similar to input() for several kinds of data: numbers, dates, email addresses, and more.

PyInputPlus

X is not a part of the Python Standard Library, so you must install it separately using Pip.

PyInputPlus

Passing a string value representing your regular expression to re.compile() returns an X

Regex pattern object

X go one step further: they allow you to specify a pattern of text to search for

Regular expressions

X refers to the process of converting an object in memory to a byte stream that can be stored on disk or sent over a network.

Serialization

A raw string completely ignores all escape characters and prints any backslash that appears in the string. [T/F]

True

False or True

True

In OOP, a class creates a new type where objects are instances of the class? [T/F]

True

Strings use indexes the same way as lists do.

True

The code in a while clause will be executed as long as the while statement's condition is X.

True

True and True

True

True or False

True

True or True

True

[T/F] 42.0 == 0042.000

True

not False

True

Valid or Invalid Variable name? TOTAL_SUM

Valid

Local Scopes Cannot Use X in Other Local Scopes

Variables

X means the string must end with spam.

X

What is an accurate declaration x=Circle()? Circle is a class

X contains a reference to a circle Object

What's the output of the following? import re msg = 'My lucky number is 777.'msg Regex = re.compile(r'\d') result = msgRegex.findall(msg[10:100])print(result)

['7', '7', '7']

Returns a match for any digit between 0 and 9

[0-9]

Returns a match where any of the specified digits (0, 1, 2, or 3) are present

[0123]

A set of characters [MetaCharacters]

[]

X matches any character that isn't between the brackets.

[^abc]

Returns a match for any character EXCEPT a, r, and n

[^arn]

Returns a match for any lower case character, alphabetically between a and n

[a-n]

Returns a match for any character alphabetically between a and z, lower case OR upper case

[a-zA-Z]

X matches any character between the brackets

[abc]

Returns a match where one of the specified characters (a, r, or n) are present

[arn]

Signals a special sequence (can also be used to escape special characters) [MetaCharacters]

\

Double quote [Escape Character]

\"

Single Quote [Escape Character]

\'

Returns a match where the string DOES NOT contain digits

\D

Any character that is not a letter, numeric digit, or the underscore character.

\W

Returns a match where the string DOES NOT contain any word characters

\W

Returns a match if the specified characters are at the end of the string

\Z

Returns a match where the string contains digits (numbers from 0-9)

\d

Any space, tab, or newline character. (Think of this as matching "space" characters.)

\s

Returns a match where the string contains a white space character

\s

Tab [Escape Character]

\t

Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character)

\w

Starts with [MetaCharacters]

^

You can also use the caret symbol X at the start of a regex to indicate that a match must occur at the beginning of the searched text.

^

This is the starting index, by default its 0.

beg

The X keyword arguments take a list of regular expression strings to determine what the PyInputPlus function will reject as valid input

blockRegexes

Blocks can contain other

blocks

If another function call is made, Python puts another frame object on the X above the other one.

call stack

A X is a mutable collection of many values.

dictionary

Strings can begin and end with X, just as they do with single quotes

double quotes

This is the ending index, by default its equal to the length of the string.

end

X methods return True if the string value they are called onor ends (respectively) with the string passed to the method

endswith()

Returns True if path exists and False otherwise.

exists(path)

X will not return a Match object but a list of strings—as long as there are no groups in the regular expression.

findall()

theX method will return the strings of every match in the searched string

findall()

Python's regular expressions are X by default, which means that in ambiguous situations they will match the longest string possible

greedy

Call the Match object's X method to return a string of the actual matched text.

group()

PyInputPlus [Syntax]

import pyinputplus

Import the regex module with X.

import re

You can determine whether a value is or isn't in a list with the X operators.

in and not in

The x and x operators can be used with strings just like with list values.

in, not in

However, you can also use an index of a list to change the value at that index.

index

The integer inside the square brackets that follows the list is called an

index

List values have an X method that can be passed a value, and if that value exists in the list, the index of the value is returned. If the value isn't in the list, then Python produces a ValueError error

index()

A variable is _________ the first time a value is stored in it

initialized

The _______ function waits for the user to type some text on the keyboard and press ENTER.

input()

Is similar to inputYesNo(), but takes a "True" or "False" response and returns a Boolean value

inputBool()

Ensures the user enters a date and time

inputDatetime()

Ensures the user enters a valid email address

inputEmail()

Ensures the user enters a valid file path and filename, and can optionally check that a file with that name exists

inputFilepath()

Is similar to inputChoice(), but provides a menu with numbered or lettered options

inputMenu()

Ensures the user enters a number and returns an int or float, depending on if the number has a decimal point in it

inputNum()

Is like the built-in input(), but displays * characters as the user types so that passwords, or other sensitive information, aren't displayed on the screen

inputPassword()

Is like the built-in input() function but has the general PyInputPlus features. You can also pass a custom validation function to it

inputStr()

Ensures the user enters a "yes" or "no" response

inputYesNo()

What is the data type of variable a? a = (1)

int

The _____ function is also helpful if you have a number as a string value that you want to use in some mathematics.

int()

Returns True if the string consists only of letters and numbers and is not blank

isalnum()

Returns True if the string consists only of letters and isn't blank

isalpha()

Returns True if the string consists only of numeric characters and is not blank

isdecimal()

Returns True if path names a directory and False otherwise.

isdir(path)

The X method will return a Boolean True value if the string has at least one letter and all the letters are lowercase

islower()

Returns True if the string consists only of spaces, tabs, and newlines and is not blank

isspace()

The x method will return a Boolean True value if the string has at least one letter and all the letters are uppercase

isupper()

Values inside the list are also called

items

The X method is called on a string, gets passed a list of strings, and returns a string

join()

Indexes for dictionaries are called X

keys

The integer value -1 refers to the X in a list

last index

The function evaluates to the integer value of the number of characters in that string.

len()

The X will return the number of values that are in a list value passed to it, just like it can count the number of characters in a string value

len() function

A X is a value that contains multiple values in an ordered sequence

list

What is the data type of the variable a? >>> a = 'MyABCnameABCisABCSimon'.split('ABC')

list

Lists can also contain other X

list values

Returns a list of the names in directory named path.

listdir(path)

If the variable is used in an assignment statement in the function, it is an X

local variable

Method returns strings lowercase

lower()

The X and Xmethods will remove whitespace characters from the left and right ends

lstrip(), rstrip()

Returns a Match object if there is a match found at the beginning of a string.

match()

What does the function re.search do?

matches a pattern at any position in a string

Objects can also contain

methods

Creates a new directory named path and places it in the current working directory.

mkdir(path)

The __________ is a shortcut that lets you assign multiple variables with the values in a list in one line of code.

multiple assignment trick

A X data type it can have values added, removed, or changed

mutable

A list value is a X data type:

mutable

A good variable _______ describes the data it contains.

name

he definition of the hello() function in this program has a parameter called

name

The X (also called lazy) version of the braces, which matches the shortest string possible, has the closing brace followed by a question mark.

non-greedy

Methods in objects are functions that belong to the X

object

There is only X of the class variable and when any one object makes a change to a class variable, that change will be seen by all the other instances.

one copy

The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in X

one line of code

A variable name can be only _____ ______with no spaces

one word

The X function can open files in write or append mode to create new text files or add to existing text files, respectively.

open()

The X function can open these files to read in their contents as one large string

open()

Keyword arguments are often used for X

optional parameters

Just as with functions, we need to use X to indicate that this class is empty.

pass

if the x is not accessible from the current working directory, Python raises an error.

pathname

A Python command that can print: I'm a student

print("I'm a student")

Print Function [Syntax]

print()

The X is a built-in function of Python which returns a range object, which is nothing but a sequence of integers. i.e.,

range()

A X completely ignores all escape characters and prints any backslash that appears in the string

raw string

Which module in Python supports regular expressions?

re

Which of the following creates a pattern object? (str is a valid regular expression)

re.compile(str)

The simplest way is to use the file method X to input the entire contents of the file as a single string.

read()

Regular expressions, called X for short, are descriptions for a pattern of text.

regexes

Character classes are nice for shortening X.

regular expressions

The X method is passed the value to be removed from the list it is called on.

remove()

Renames the file or directory named old to new.

rename(old, new)

Lists can be replicated just like strings.

replicated

Removes the directory named path from the current working directory

rmdir(path)

Class variables are X

shared

The code that could potentially have an error is put in a X clause. The program execution moves to the start of a following except clause if an error happens.

try

Function that shows the data type

type()

Unlike lists, items in dictionaries are X.

unordered

If a X is being used in the global scope (that is, outside of all functions), then it is always a global variable

variable

The call stack isn't stored in a X in your program

variable

import re sentence = 'we are humans' matched = re.search(r'(.*) (.*?) (.*)', sentence) print(matched.group())

we are humans

You can make a block of code execute over and over again using a

while statement

The X character is called a pipe. You can use it anywhere you want to match one of many expressions

|

Not equal to

!=

SyntaxError: EOL while scanning string literal

" "

Comment [Syntax]

#

Modulus/Remainder [Syntax]

%

'Alice' + 'Bob'

'AliceBob'

Addition

+

Less than

<

Less than or equal to

<=

'Alice' * 'Bob'

Error

False and True

False

True and False

False

Valid or Invalid Variable name? 'hello'

Invalid

Valid or Invalid Variable name? 4account

Invalid

Valid or Invalid Variable name? current balance

Invalid

Valid or Invalid Variable name? hello

Valid

Lines of Python code can be grouped together in ________.

blocks

There is a shortcut to getting the program execution to break out of a while loop's clause early.

brake Statement

If the execution reaches a X statement, it immediately exits the while loop's clause

break

Lists can be X just like strings.

concatenated

An if clause can optionally be followed by an _____ statement.

else

An __ statement's clause will execute if the statement's condition is True. The clause is skipped if the condition is False.

if

The most common type of flow control statement is the __ statement.

if

Python X generates the integer numbers between the given start integer to the stop integer, which is generally used to iterate over with for loop.

range()

At the end of an if clause, the program execution continues after the if statement. But at the end of a while clause, the program execution jumps back to the X of the while statement.

start

The X is the amount that the variable is increased by after each iteration.

step

The range() function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the X.

step argument


Set pelajaran terkait

ECON - Ch15.1 - Using Fiscal Policy - Section 1 - What is Fiscal Policy?

View Set

Chapter VI Federal Tax Consideration for Life Insurance (5 Exam Questions)

View Set

MRKT 640 Consumer Behavior Module 2

View Set

Grade 7 tissues in the human body

View Set

Life Science Chapter 9 Chemical Reactions

View Set

Life Insurance Policy Provisions, Riders, and Options

View Set

Биохимия крови норма🤙

View Set