Chapter 2 Variables and assignments Flashcards

1
Q

In a program, a variable is a …?

An assignment statement assigns…?

A

In a program, a variable is a named item, such as x or num_people, used to hold a value. A good variable name should describe the purpose of the variable, such as “temperature” or “age,” rather than just “t” or “A.”

An assignment statement assigns a variable with a value, such as x = 5. That statement means x is assigned with 5, and x keeps that value during subsequent statements until x is assigned again.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

An assignment statement’s left side must be a …?

The right side can be …?

A

An assignment statement’s left side must be a variable. The right side can be an expression, so a statement may be x = 5, y = x, or z = x + 2. The 5, x, and x + 2 are each an expression that evaluates to a value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

= is not equals

A

In programming, = is an assignment of a left-side variable with a right-side value. = is NOT equality as in mathematics. Thus, x = 5 is read as “x is assigned with 5,” and not as “x equals 5.” When one sees x = 5, one might think of a value being put into a box.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Define identifier

A

An identifier, also called a name, is a sequence of letters (a-z, A-Z), underscores (_), and digits (0–9), and must start with a letter or an underscore.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

IS Python case sensative?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Reserved words, or keywords,

A

Certain words like “and” or “True” cannot be used as names. Reserved words, or keywords, are words that are part of the language, and thus, cannot be used as a programmer-defined name. Many language editors will automatically color a program’s reserved words.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Python 3 Reserved Keywords

A
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Define an object

A

An object represents a value and is automatically created by the interpreter when executing a line of code. For example, executing x = 4 creates a new object to represent the value 4. A programmer does not explicitly create objects; instead, the interpreter creates and manipulates objects as needed to run the Python code. Objects are used to represent everything in a Python program, including integers, strings, functions, lists, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Define garbage collection

A

Above, the interpreter performs an addition of 2+2, resulting in a new object being created with a value of 4. Once 4 is printed the object is no longer needed, so the object is automatically deleted from memory and thrown away. Deleting unused objects is an automatic process called garbage collection that helps to keep the memory of the computer less utilized.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Define name binding

A

Name binding is the process of associating names with interpreter objects. An object can have more than one name bound to it, and every name is always bound to exactly one object. Name binding occurs whenever an assignment statement is executed, as demonstrated below.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Name the 3 properties of objects in Python

A

Each Python object has three defining properties: value, type, and identity.

Value: A value such as “20”, “abcdef”, or 55.
Type: The type of the object, such as integer or string.
Identity: A unique identifier that describes the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Define Mutability

The built-in function type() returns the type of an object.

Python provides a built-in function id() that gives the value of an object’s identity.

A

The type of an object also determines the mutability of an object. Mutability indicates whether the object’s value is allowed to be changed. Integers and strings are immutable; modifying their values with assignment statements results in new objects being created and the names bound to the new object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Define Floating Point number

A

floating-point number is a real number, like 98.6, 0.0001, or -666.667. The term “floating-point” refers to the decimal point being able to appear anywhere (“float”) in the number. Thus, float is a data type for floating-point numbers.

A floating-point literal is written with the fractional part even if that fraction is 0, as in 1.0, 0.0, or 99.0. scientific notation is written using an e preceding the power-of-10 exponent, as in 6.02e23 to represent 6.02x1023. The e stands for exponent. Likewise, 0.001 is 1x10-3, so it can be written as 1.0e-3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Define OverflowError

A

Float-type objects have a limited range of values that can be represented. For a standard 32-bit installation of Python, the maximum floating-point value is approximately 1.8x10308, and the minimum floating-point value is 2.3x10-308. Assigning a floating-point value outside of this range generates an OverflowError. Overflow occurs when a value is too large to be stored in the memory allocated by the interpreter. For example, the program in the figure below tries to store the value 2.01024, which causes an overflow error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

print(f’{math.pi:.4f}’) outputs Pi to only four digits after the decimal. The last digit is rounded up in the output, but the value of Pi remains the same.

A

Default output of Pi: 3.141592653589793

Pi reduced to 4 digits after the decimal: 3.1416

int(f’{9.1357:.3f}’)) outputs 9.136 because the third digit after the decimal point is rounded.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

An expression is a combination of items, like variables, literals, operators, and parentheses, that evaluates to a value, like 2 * (x + 1). A common place where expressions are used is on the right side of an assignment statement, as in y = 2 * (x + 1).

A literal is a specific value in code like 2. An operator is a symbol that performs a built-in calculation, like +, which performs addition. Common programming operators are shown below.

A

Arithmetic operator Description
+ The addition operator is +, as in x + y.
- The subtraction operator is -, as in x - y. Also, the - operator is for negation, as in -x + y, or x + -y.
* The multiplication operator is *, as in x * y.
/ The division operator is /, as in x / y.
** The exponent operator is **, as in x ** y (x to the power of y).

17
Q

2x Expression?
In programming, multiplication typically must be indicated explicitly using the * operator. Abutment is allowed in math, but not usually in programming.

2 + (xy) Expession?
In programming, doing multiplication via abutment, as in xy, is not usually allowed, because xy could be the name of another variable.

A

y = x + 1 Expession

x + 1 alone is an expression, but y = x + 1 is an assignment and not itself an expression.

18
Q

Evaluation of expressions

An expression evaluates to a value, which replaces the expression. Ex: If x is 5, then x + 1 evaluates to 6, and y = x + 1 assigns y with 6.

An expression is evaluated using the order of standard mathematics, and such order is known in programming as precedence rules, listed below.

A

( ) Items within parentheses are evaluated first. In 2 * (x + 1), the x + 1 is evaluated first, with the result then multiplied by 2.

exponent ** ** used for exponent is next. In x**y * 3, x to the power of y is computed first, with the results then multiplied by 3.

unary - - used for negation (unary minus) is next. In 2 * -x, the -x is computed first, with the result then multiplied by 2.

* / % Next to be evaluated are *, /, and %, having equal precedence. (% is discussed elsewhere.)

+ - Finally come + and - with equal precedence. In y = 3 + 2 * x, the 2 * x is evaluated first, with the result then added to 3, because * has higher precedence than +. Spacing doesn’t matter: y = 3+2 * x would still evaluate 2 * x first.

left-to-right If more than one operator of equal precedence could be evaluated, evaluation occurs left to right. Note: The ** operator is evaluated from right-to-left. In y = x * 2 / 3, the x * 2 is first evaluated, with the result then divided by 3.

19
Q

Compound operator
is shorthand for when variable is being updated, not for a more general assignment.

A

Table 2.6.1: Compound operators.
Compound operator Expression with compound operator Equivalent expression
Addition assignment age += 1 age = age + 1
Subtraction assignment age -= 1 age = age - 1
Multiplication assignment age *= 1 age = age * 1
Division assignment age /= 1 age = age / 1
Modulo (operator further discussed elsewhere) assignment age %= 1 age = age % 1

20
Q

Modules

The interactive Python interpreter allows a programmer to execute one line of code at a time. This method of programming is mostly used for very short programs or for practicing the language syntax. Instead, programmers typically write Python program code in a file called a script, and execute the code by passing the script as input to the Python interpreter.

A

Programmers often write code in more than just a single script file. Collections of logically related code can be stored in separate files, and then imported for use into a script that requires that code. A module is a file containing Python code that can be used by other modules or scripts. A module is made available for use via the import statement. Once a module is imported, any object defined in that module can be accessed using dot notation.

21
Q

. A module is Python code located in another file. The programmer can import the module for use in their own file, or in an interactive interpreter. The programmer first imports the module to the top of a file

A

import math

num = 49
num\_sqrt = math.sqrt(num)
22
Q

sqrt() is known as a function. A function is a list of statements that can be executed simply by referring to the function’s name. The statements for sqrt() are within the math module itself and are not relevant to the programmer. The programmer provides a value to the function (like num above). The function executes its statements and returns the computed value. Thus, sqrt(num) above will evaluate to 7.0.

A

The process of invoking a function is referred to as a function call. The item passed to a function is referred to as an argument. Some functions have multiple arguments, such as the function pow(b, e), which returns be. The statement ten_generation_ancestors = 1024 * num_people could be replaced by ten_generation_ancestors = math.pow(2, 10) * num_people to be more clear.

23
Q

math.

Number representation and theoretic functions
Function Description
ceil(x) Round up value
fabs(x) Absolute value
factorial(x) factorial (3! = 3 * 2 * 1)
floor(x) Round down value
fmod(x, y) Remainder of division
fsum(x) Floating-point sum of a range, list, or array.

Power, exponential, and logarithmic functions

Function Description
exp(x) Exponential function ex
log(x, (base)) Natural logarithm; base is optional
pow(x, y) Raise x to power y
sqrt(x) Square root

A

Trigonometric functions Function Description
acos(x) Arc cosine asin(x) Arc sine
atan(x) Arc tangent atan2(y, x) Arc tangent with two parameters
cos(x) Cosine sin(x) Sine
hypot(x1, x2, x3, …, xn) Length of vector from origin degrees(x) Convert from radians to degrees
radians(x) Convert degrees to radians tan(x) Tangent
cosh(x) Hyperbolic cosine sinh(x) Hyperbolic sine
Complex number functions
gamma(x) Gamma function erf(x) Error function
Mathematical constants
pi (constant) Mathematical constant 3.141592… e (constant) Mathematical constant 2.718281…

24
Q

Python uses Unicode to represent every possible character as a unique number, known as a code point. For example, the character ‘G’ has the code point decimal value of 71.

A

Encoded text values.

DecimalCharacter32space33!34”35#36$37%38&39’40(41)42*43+44,45-46.47/48049150251352453554655756857958:59;60<61=62>63?

DecimalCharacter64@65A66B67C68D69E70F71G72H73I74J75K76L77M78N79O80P81Q82R83S84T85U86V87W88X89Y90Z91[92\93]94^95_

DecimalCharacter96`97a98b99c100d101e102f103g104h105i106j107k108l109m110n111o112p113q114r115s116t117u118v119w120x121y122z123{124|125}126~

25
Q

A newline character, which indicates the end of a line of text, is encoded as 10. Since there is no visible character for a newline, the language uses the two-item sequence \n to represent a newline character. The \ is known as a backslash. Upon reaching a \, the interpreter recognizes that item as the start of a special character’s two-item sequence and then looks at the next item to determine the special character. The two-item sequence is called an escape sequence.

A

Common escape sequences.

Common escape sequences.

Escape SequenceExplanationExample codeOutput\Backslash ()

print(‘\home\users\’)

\home\users\

'Single quote (‘)

print(‘Name: John O'Donald’)

Name: John O’Donald

"Double quote (“)

print(“He said, "Hello friend!".”)

He said, “Hello friend!”.

\nNewline

print(‘My name…\nIs John…’)

My name… Is John…

\tTab (indent)

print(‘1. Bake cookies\n\t1.1. Preheat oven’)

  1. Bake cookies 1.1. Preheat oven
26
Q

Escape sequences can be ignored using a raw string. A raw string is created by adding an ‘r’ before a string literal, as in r’this is a raw string'’, which would output as this is a raw string'.

A

gnoring escape characters with a raw string.

my_string = ‘This is a \n 'normal' string\n’my_raw_string = r’This is a \n 'raw' string’print(my_string)print(my_raw_string)

This is a ‘normal’ string This is a \n 'raw' string