CS161A - Python 3

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

PEP 8

(Python Enhancement Proposal) is a document that outlines the basics of how to write Python code neatly and consistently.

Exponent Operator

** ie. x = 5 y = 3**x

age = input("What is your age? ")

"What is your age?" is called, a prompt.

Commenting

# text

1.6.4: Processor Executing Instructions

0 | Mul 97, #9, 98 1 | Div 98, #5, 98 2 | Add 98, #32, 99 3 | Jmp 0 4 | ......... 96 | ?? 97 | 20 98 | 38 99 | 68 // Add 98, #32, 99 // // 36 + 32 = 68 //

Container; List; Element

A *container* is a construct used to group related values together and contains references to other objects instead of data. A *list* is a container created by surrounding a sequence of variables or literals with brackets [ ]. Ex: my_list = [10, 'abc'] creates a new list variable my_list that contains the two items: 10 and 'abc'. A list item is called an *element*.

Program

A computer program consists of instructions executing one at a time.

Module

A file containing Python code that is imported by a script, module, or the interactive interpreter.

Method

A method instructs an object to perform some action, and is executed by specifying the method name following a "." symbol and an object. ie. my_list = [23, "three"] my_list.append('abc')

Precedence Rules

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

Identifier

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.

Interactive Interpreter

An interactive interpreter is a program that allows the user to execute one line of code at a time.

Object

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.

Application

Another word for program. The programmer-created sequence of instructions is called a program, application, or just app. or, an algorithm.

Whitespace

Any blank space or newline.

OverflowError

Assigning a floating-point value outside of this range generates an overflow error. Overflow occurs when a value is too large to be stored in the memory allocated by the interpreter.

list.count(val)

Count the number of occurrences of the value val in list.

Python was first implemented in 1960.

False. Python was conceived in the late 1980s, and first implemented in the early 1990s.

max(list)

Find the element in list with the largest value.

min(list)

Find the element in list with the smallest value.

list.index(val)

Find the index of the first element in list whose value matches val.

sum(list)

Find the sum of all elements of a list (numbers only).

Modulo Examples

Given a non-negative number x, which expression has the range -10 to 10? >> (x % 21) - 10 x % 21 yields 0 - 20, and -10 makes it -10 to 10.

id()

Gives the value of an objects identity (memory address). ie. x = 2 + 2 print(id(x)) >> 1752608

Assembly Language

Human-readable processor instructions. An assembler is a program that translates assembly language instructions into machine instructions.

Raw String

Ignores escape sequences. ie. x = r"This \' is a raw sequence\'." print(x) >> This \' is a raw sequence\'.

Which type of error does not cause the program to crash?

Logic error

Operating System

Manages programs and interfaces with peripherals.

Identifiers

Must start with a letter or an underscore.

Name Binding

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.

Syntax Error

One kind of mistake, known as a syntax error, is to violate a programming language's rules on how symbols can be combined to create a program.

Basic instruction types are input, process, and ____.

Output

Script

Programmers typically write Python program code in a file called a script. A program whose instructions are executed by another program called an interpreter. Running baby_names.py as a script (python baby_names.py) causes the code within the if __name__ == '__main__' block to execute, which prints some baby statistics. python baby_names.py = script

Variable

Programs use variables to refer to data, like x, y, and z below. The name is due to a variable's value "varying" as a program assigns a variable like x with new values.

Clock

Rate at which a processor executes instructions.

Modulo Operator (%)

Remainder. ie. 23 % 3 = 3

Reserved Words

Reserved words, or keywords, are words that are part of the language, and thus cannot be used as a programmer-defined name.

Disk

Non-volatile storage with slower access.

Expression

Right side of an assignment as long as it is not a literal. Has to be evaluated. ie. (x * y) / 2 2 + 2 NOT, x = 4 An expression is a combination of items, like variables, literals, operators, and parentheses, that evaluates to a value, like 2 * (x + 1).

Dividing by zero is an example of which type of error?

Runtime

String Literal

Text enclosed in quotes is known as a string literal.

Python Interpreter

The Python interpreter is a computer program that executes code written in the Python programming language.

append()

The append() list method is used to add new elements to a list.

chr()

The built-in function chr() returns a string of one character for an encoded integer.

ord()

The built-in function ord() returns an encoded integer value for a string of length one.

Moore's Law

The doubling of IC (integrated circuit) capacity roughly every 18 months.

Floating-point number

The term "floating-point" refers to the decimal point being able to appear anywhere ("float") in the number.

Space, tab, and newline are all called _____ characters.

Whitespace

Python installed.

Windows does not come with python installed, linux and mac does.

Indexing - Accessing Individual Characters

alphabet = 'abcdefghijklmnopqrstuvwxyz' print(alphabet[0]) >> a also, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" user_number = int(input('Enter number to use as index: ')) print() print('\nLetter', user_number, 'of the alphabet is', alphabet[user_number]) >> Enter number to use as index: (2) Letter 2 of the alphabet is C

NameError

day_of_the_week = Friday

Removing smallest value in a list.

final_scores = [55, 62, 84, 100] final_scores.remove(min(final_scores)) min_score = min(final_scores) print(min_score) >> 62

Manipulating Float Output

ie. myFloat = 3.14159 print('{:.2f}'.format(myFloat)) >> 3.14 NOTE: IT ROUNDS UP! ie. myFloat = 9.1357 print('{:.3f}'.format(myFloat)) >> 9.136

Factorial

ie. 4 1 * 2 * 3 * 4 = (24)

ValueError

int("Thursday")

String Literal

A string literal is a string value specified in the source code of a program. A programmer creates a string literal by surrounding text with single or double quotes, such as 'MARY' or "MARY".

Byte

8 bits

Code

Code is a common word for the textual representation of a program (and hence programming is also called coding). A line is a row of text.

pop()

list.pop(i): Removes the element at index i from list. Ex: my_list.pop(1)

Garbage Collection

Deleting unused objects is an automatic process called garbage collection that helps to keep the memory of the computer less utilized.

Import

Executes the contents of a file containing Python code and makes the definitions from that file available. A module is made available for use via the import statement.

Expressions

Expressions are code that return a value when evaluated; for example, the code wage * hours * weeks is an expression that computes a number. The symbol * is used for multiplication. The names wage, hours, weeks, and salary are variables, which are named references to values stored by the interpreter.

Python comes pre-installed on Windows machines.

False

Python string objects are mutable, meaning that individual characters can be changed.

False

Reserved Keywords

False - None - True - and - as - assert - async - await - break - class - continue - def - del - elif - else - except - finally - for - from - global - if - import - in - is - lambda - nonlocal - not - or - pass - raise - return - try - while - with - yield

Python is a high-level language that excels at creating exceptionally fast-executing programs.

False. Python excels at providing powerful programming paradigms such as object-oriented programming and dynamic typing. Python incurs additional overhead costs because the language is interpreted.

A processor is a circuit that executes a list of _____.

Instructions

A(n) _____ is a program that executes a script.

Interpreter

type()

Prints the type of an object. ie. x = 8 y = x + 2 print(type(x)) >> <class 'int'>

Cache

Relatively small, volatile storage with fastest access located on processor chip.

Scientific Notation

The e stands for exponent. Likewise, 0.001 is 1x10^-3, so it can be written as 1.0e-3. ie. Type 1.0e-4 as a floating-point literal but not using scientific notation, with a single digit before and four digits after the decimal point. = 0.0001 ie. Type 7.2e-4 as a floating-point literal but not using scientific notation, with a single digit before and five digits after the decimal point. = 0.00072 ie. Type 540,000,000 as a floating-point literal using scientific notation with a single digit before and after the decimal point. = 5.4e8 ie. Type 0.000001 as a floating-point literal using scientific notation with a single digit before and after the decimal point. = 1.0e-6 ie. Type 623.596 as a floating-point literal using scientific notation with a single digit before and five digits after the decimal point. = 6.23596e2

Floored Division (//)

The floored division operator // can be used to round down the result of a floating-point division to the closest whole number value. 5 and lower is rounded down.

Argument

The item passed to a function is referred to as an argument.

Runtime Error

The program may have another kind of error called a runtime error, wherein a program's syntax is correct but the program attempts an impossible operation, such as dividing by zero or multiplying strings together (like 'Hello' * 'ABC').

String with vs without quotes

The string '123' (with quotes) is fundamentally different from the integer 123 (without quotes). The '123' string is a sequence of the characters '1', '2', and '3' arranged in a certain order, whereas 123 represents the integer value one-hundred twenty-three.

User Input

name = input()

remove()

list.remove(v): Removes the first element whose value is v. Ex: my_list.remove('abc')

TypeError

lyric = 99 + "bottles of pop on the wall"

Converting Types

my_string = '123' my_int = int('123')

String Concatenation

A program can add new characters to the end of a string in a process known as string concatenation ie. string_1 = 'abc' string_2 = '123' concatenated_string = string_1 + string_2 print('Easy as ' + concatenated_string) >> Easy as abc123

Input

A program gets data, perhaps from a file, keyboard, touchscreen, network, etc.

Process

A program performs computations on that data, such as adding two values like x + y.

Output

A program puts that data somewhere, such as to a file, screen, or network.

Machine Instruction

A series of 0s and 1s, stored in memory, that tells a processor to carry out a particular operation like a multiplication. 0s and 1s are hard to comprehend. Most programmers specify the program's functionality in a high-level language, which is then automatically translated to low-level machine instructions.

Statement

A statement is a program instruction. A program mostly consists of a series of statements, and each statement usually appears on its own line.

Tuple

A tuple, usually pronounced "tuhple" or "toople", behaves similar to a list but is immutable - once created the tuple's elements cannot be changed. A tuple is also a sequence type, supporting len(), indexing, and other sequence type functions. A new tuple is generated by creating a list of comma-separated values, such as 5, 15, 20. Typically, tuples are surrounded with parentheses, as in (5, 15, 20). Note that printing a tuple always displays surrounding parentheses.

IDE

This web material embeds a Python interpreter so that the reader may experiment with Python programming. However, for normal development, a programmer installs Python as an application on a local computer. Macintosh and Linux operating systems usually include Python, while Windows does not. Programmers can download the latest version of Python for free from https://python.org. Code development is usually done with an integrated development environment, or IDE. There are various IDEs that can be found online; some of the most popular are listed below. IDLE is the official Python IDE that is distributed with the installation of Python from https://python.org. IDLE provides a basic environment for editing and running programs. PyDev (http://pydev.org) is a plugin for the popular Eclipse program. PyDev includes extra features such as code completion, spell checking, and a debugger that can be useful tools while programming. For learning purposes, web-based tools like CodePad (http://www.codepad.org) or Repl (http://www.repl.it) are useful. There are many other editors available—some of which are free, while others require a fee or subscription. Finding the right IDE is sometimes like finding a pair of jeans that fits just right—try a Google search for "Python IDE" and explore the options.

Processors and Memory

To support different calculations, circuits called processors were created to process (aka execute) a list of desired calculations, each calculation called an instruction. The instructions were specified by configuring external switches, as in the figure below. Processors used to take up entire rooms, but today fit on a chip about the size of a postage stamp, containing millions or even billions of switches. Instructions are stored in a memory. A memory is a circuit that can store 0s and 1s in each of a series of thousands of addressed locations, like a series of addressed mailboxes that each can store an envelope (the 0s and 1s). Instructions operate on data, which is also stored in memory locations as 0s and 1s.

Compiler

Translates a high-level language program into low-level machine instructions. A compiler ensures a program is valid according to the language's rules, performs optimizations, then converts to the low-level machine instructions.

Lists are mutable, meaning that a programmer can change a list's contents. An element can be updated with a new value by performing an assignment to a position in the list.

True

Python 3.0 is not backwards compatible.

True

Python is open-source.

True

Dot Notation

Used to reference an object in an imported module. ie. print(math.pi)

RAM

Volatile storage with faster access usually located off processor chip.

if __name__ == '__main__'

When a module is imported, all of it is automatically executed unless >> if __name__ == '__main__' << is used, in which case it would have to be called using dot notation. Executes only if file run as a script. Running baby_names.py as a script (python baby_names.py) causes the code within the if __name__ == '__main__' block to execute, which prints some baby statistics. When favorite_child.py is run and baby_names.py is imported as a module, the baby statistics are not printed.

Indexing Lists

names = ['Daniel', 'Roxanna', 'Jean'] print(names[:2]) >>['Daniel', 'Roxanna'] -------------------------------------------------------------- names = ['Daniel', 'Roxanna', 'Jean'] print(names[1:]) >>['Roxanna', 'Jean'] -------------------------------------------------------------- names = ['Daniel', 'Roxanna', 'Jean'] print(names[0]) >>Daniel -------------------------------------------------------------- names = ['Daniel', 'Roxanna', 'Jean'] print(names[2]) >>Jean -------------------------------------------------------------- names = ['Daniel', 'Roxanna', 'Jean'] print(names[1], names[2]) >> Roxanna Jean -------------------------------------------------------------- my_list = [-100, 'lists are fun'] print(my_list[0], my_list[1]) >>-100 lists are fun

Which statement does not print a newline character at the end?

print("This is the end", end=" ")

Backwards Indexing

print(alphabet[-1]) >> z Backwards indexing starts at -1, not 0.

Len()

user_name = "Santa" print(len(user_name)) >> 5

Enter the output.

x = 9 y = 5 print(x, y) output: 9 5 *(newline, press enter after 5)*


Ensembles d'études connexes

Unit 2: Life/Health Insurance Underwriting QBank

View Set

buying using and disposing ch 10

View Set

Anatomy and physiology of the lactating breast

View Set

Chapter 1 :Perspective on Maternal , Newborn , and womens health

View Set

Life Insurance - D. Life Insurance and Annuities - Policy Replacement/Cancellation

View Set

HESI MILESTONE 2 PRACTICE QUESTION

View Set

Chapter 13- Monopolistic Competition

View Set

Chapter 35 Pediatric Emergencies:

View Set