Think Python Chapter 1, 2 3, 5 & 6

Ace your homework & exams now with Quizwiz!

alternative execution

A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this: if x%2 == 0: print 'x is even' else: print 'x is odd'

What is a statement?

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.

compound statement:

A statement that consists of a header and a body. The header ends with a colon (:). The body is indented relative to the header.

conditional statement:

A statement that controls the flow of execution depending on some condition.

What are most programs written in?

Due to the advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications.

What are the advantages of high-level languages?

First, it is much easier to program in a high-level language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications

What happens if you put a space in a variable name?

If you put a space in a variable name, Python thinks it is two operands without an operator: >>> bad name = 5 SyntaxError: invalid syntax

What are operators and operands?

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

How can parentheses be used?

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn't change the result

What type of variable are true & false values?

True and False are special values that belong to the type bool; they are not strings: >>> type(True) <type 'bool'> >>> type(False) <type 'bool'>

What programs process high-level languages into low-level languages?

Two kinds of programs process high-level languages into low-level languages: interpreters and compilers.

function

a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can "call" the function by name.

program

a sequence of instructions that specifies how to perform a computation

What is elif an abbreviation of?

elif is an abbreviation of "else if."

The + operator works with strings, but it might not do what you expect:

it performs concatenation, which means joining the strings by linking them end-to-end. For example: first = 'throat' second = 'warbler' print first + second The output of this program is throatwarbler

What 2 ways can you use the interpreter?

script mode & interactive mode

What are the relational operators?

x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y x == y # x is equal to y

script mode

y, you can store code in a file and use the interpreter to execute the contents of the file, which is called a script. By convention, Python scripts have names that end with .py. To execute the script, you have to tell the interpreter the name of the file. If you have a script named dinsdale.py and you are working in a UNIX command window, you type python dinsdale.py. In other development environments, the details of executing scripts are different. You can find instructions for your environment at the Python website http: //python.org

What can you use the modulus operator for?

you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y. Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

what is a module?

A module is a file that contains a collection of related functions.

Syntax

refers to the structure of a program and the rules about that structure

How to use comments on Python?

# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60 In this case, the comment appears on a line by itself. You can also put comments at the end of a line: percentage = (minute * 100) / 60 # percentage of an hour Everything from the # to the end of the line is ignored—it has no effect on the program. Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why. Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.

What is a disadvantage of low-level languages?

. Low-level programs can run on only one kind of computer and have to be rewritten to run on another

A variable is a name that refers to a value. An assignment statement creates new variables and gives them values: give examples (message, pi, n)

>>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.1415926535897932 This example makes three assignments. The first assigns a string to a new variable named message; the second gives the integer 17 to n; the third assigns the (approximate) value of π to pi. The type of a variable is the type of the value it refers to. >>> type(message) <type 'str'> >>> type(n) <type 'int'> >>> type(pi) <type 'float'>

What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks like strings. >>> type('17') >>> type('3.2') They're strings.

>>> type('17') <type 'str'> >>> type('3.2') <type 'str'> They're strings.

How does a compiler work?

A compiler reads the program and translates it completely before the program starts running. In this context, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation

nested conditional:

A conditional statement that appears in one of the branches of another conditional statement.

chained conditional:

A conditional statement with a series of alternative branches.

Interactive Mode

A way of using the Python interpreter by typing commands and expressions at the prompt. In interactive mode, you type Python programs and the interpreter displays the result: >>> 1 + 1 2 The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 1 + 1, the interpreter replies 2.

How many branches will be executed in the chained conditional?

Again, exactly one branch will be executed. If there is an else clause, it has to be at the end, but there doesn't have to be one. if choice == 'a': draw_a() elif choice == 'b': draw_b() elif choice == 'c': draw_c() Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

Do we want to use nested conditionals?

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.

What is an expression?

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable

boolean expression:

An expression whose value is either True or False

How does an interpreter work?

An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations

modulus operator:

An operator, denoted with a percent sign (%), that works on integers and yields the remainder when one number is divided by another. >>> quotient = 7 / 3 >>> print quotient 2 >>> remainder = 7 % 3 >>> print remainder 1

For example, if you are using Python as a calculator, you might type >>> miles = 26.2 >>> miles * 1.61 42.182 The first line assigns a value to miles, but it has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. So we learn that a marathon is about 42 kilometers. What happens if we type this in interactive mode?

But if you type the same code into a script and run it, you get no output at all. In script mode an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn't display the value unless you tell it to: miles = 26.2 print miles * 1.61

Give an example of a syntax error

For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error.

How do you resolve a semantic error?

Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.

What is a semantic error?

If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do. The meaning of the program (its semantics) is wrong.

How can you determine what type a value is?

If you are not sure what type a value has, the interpreter can tell you. >>> type('Hello, World!') <type 'str'> >>> type(17) <type 'int'> >>> type(3.2) <type 'float'>

Can you perform mathematical operations on strings?

In general, you can't perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal: '2'-'1' 'eggs'/'easy' ' third'*'a charm'

How does a function work? What is a return value?

It is common to say that a function "takes" an argument and "returns" a result. The result is called the return value.

How can we simplify nested conditionals?

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional: if 0 < x: if x < 10: print 'x is a positive single-digit number.' The print statement is executed only if we make it past both conditionals, so we can get the same effect with the and operator: if 0 < x and x < 10: print 'x is a positive single-digit number.'

What is a disadvanantage of high-level languages?

Loosely speaking, computers can only run programs written in lowl-evel languages. So programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages.

ambiguity:

Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context

How can we nest a conditional with another?

One conditional can also be nested within another. We could have written the trichotomy example like this: if x == y: print 'x and y are equal' else: if x < y: print 'x is less than y' else: print 'x is greater than y' The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.

branch:

One of the alternative sequences of statements in a conditional statement.

value:

One of the basic units of data, like a number or string, that a program manipulates.

Examples of composition

One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators: x = math.sin(degrees / 360.0 * 2 * math.pi) And even function calls: x=math.exp(math.log(x+1)) Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: the left side of an assignment statement has to be a variable name. Any other expression on the left side is a syntax error (we will see exceptions to this rule later). >>> minutes = hours * 60 # right >>> hours * 60 = minutes # wrong! SyntaxError: can't assign to operator

logical operator:

One of the operators that combines boolean expressions: and, or, and not.

relational operator:

One of the operators that compares its operands: ==, !=, >, <, >=, and <=.

How should you name a variable?

Programmers generally choose names for their variables that are meaningful—they document what the variable is used for. Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you'll see why later).

Are programming languages natural or formal languages?

Programming languages are formal languages that have been designed to express computations.

How can we use the math module

Python has a math module that provides most of the familiar mathematical functions. Before we can use the module, we have to import it: >>> import math This statement creates a module object named math. If you print the module object, you get some information about it: >>> print math <module 'math' (built-in)>

What kind of language is Python? What are other examples of this type of language?

Python is an example of a high-level language; other high-level languages you might have heard of are C, C++, Perl, and Java.

Is Python a compiled or an interpreted language? What does that mean?

Python is considered an interpreted language because Python programs are executed by an interpreter

What does python do if a logical expression contains a non-integer or string?

Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as "true." >>> 17 and True True

How many alternatives will be executed by one condition?

Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution

What is programming really?

So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.

What is a chained conditional?

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional: if x < y: print 'x is less than y' elif x > y: print 'x is greater than y' else: print 'x and y are equal'

What are the components of syntax rules?

Syntax rules come in two flavors, pertaining to tokens and structure.

What is the difference between a statement and an expression? Are they the same thing?

Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.

Does the * operator work on strings?

The * operator also works on strings; it performs repetition. For example, 'Spam'*3 is 'SpamSpamSpam'. If one of the operands is a string, the other has to be an integer.

What are the alternatives called?

The alternatives are called branches, because they are branches in the flow of execution

condition:

The boolean expression in a conditional statement that determines which branch is executed.

What runtime error are you most likely to make?

The runtime error you are most likely to make is a "use before def;" that is, trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong: >>> principal = 327.68 >>> interest = principle * rate NameError: name 'principle' is not defined Variables names are case sensitive, so LaTeX is not the same as latex.

What is a runtime error? When does it occur?

The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened. Runtime errors are rare in the simple programs

Structure

The second type of syntax rule pertains to the structure of a statement; that is, the way the tokens are arranged. (i.e. The statement 3+ = 3 is illegal because even though + and = are legal tokens, you can't have one right after the other.)

>>> minute = 59 >>> minute/60 0 Why does minute/60 return 0 when the exact value is not zero?

The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division. When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.

What is : print 'Hello, World!' an example of?

This is an example of a print statement, which doesn't actually print anything on paper. It displays a value on the screen. In this case, the result is the words Hello, World! The quotation marks in the program mark the beginning and end of the text to be displayed; they don't appear in the result. In Python 3, the syntax for printing is slightly different: print('Hello, World!') The parentheses indicate that print is a function

Tokens

Tokens are the basic elements of the language, such as words, numbers, and chemical elements. (i.e. One of the problems with 3+ = 3$6 is that $ is not a legal token in mathematics)

rules of precedence

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

When should you use script mode and interactive mode?

Working in interactive mode is convenient for testing small pieces of code because you can type and execute them immediately. But for anything more than a few lines, you should save your code as a script so you can modify and execute it in the future.

How are strings distinguished?

You (and the interpreter) can identify strings because they are enclosed in quotation marks.

What is composition

You can take variables, expressions, and statements and combine them

The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. Python 2 has 31 keywords:

and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try In Python 3, exec is no longer a keyword, but nonlocal is

What are the three logical operators? Give an example/explain

and, or, and not And: For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10. Or: n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3. Not: the not operator negates a boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y

What are programming errors called?

bugs

What is a type of function call

function call: >>> type(32) <type 'int'> The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this function, is the type of the argument.

What structure do if statements have? Is there a limit on the number of statements that can appear in a body? Can you have a body with no statements & what would be the purpose of this?

if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements. There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven't written yet). In that case, you can use the pass statement, which does nothing. if x < 0: pass # need to handle negative values!

What are some of the basic instructions in a program?

input: Get data from the keyboard, a file, or some other device. output: Display data on the screen or send data to a file or other device. math: Perform basic mathematical operations like addition and multiplication. conditional execution: Check for certain conditions and execute the appropriate code. repetition: Perform some action repeatedly, usually with some variation

Formal languages

languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. Formal languages tend to have strict rules about syntax

What are low-level languages?

machine and assembly languages

portable

meaning that they can run on different kinds of computers with few or no modifications

Is there a limit on the number of elif statements?

no There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn't have to be one.

When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this subconsciously). What is this process called?

parsing Once you have parsed a sentence, you can figure out what it means, or the semantics of the sentence

What three kinds of errors can occur in a program?

syntax errors, runtime errors, and semantic errors

What ability do conditional statements give us? What exactly is a condition?

the ability to check conditions and change the behavior of the program accordingly The simplest form is the if statement: if x > 0: print 'x is positive' The boolean expression after if is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.

Natural languages

the languages people speak, such as English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.

debugging

the process of tracking programming errors (bugs) down

Ambiguity

the quality of being open to more than one interpretation; inexactness Programs: The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.


Related study sets

Биохимический анализ крови

View Set

CH 1. Operating Systems Fundamentals

View Set

Global Econ - Chapter 8 Application of the Cost of Taxation - Concordia College

View Set

Expert Witness Testimony and Report Writing

View Set