class: center, middle, inverse # Variables, Expressions and Statements --- ## Variables A **variable** is a name that refers to a value. An **assignment statement** creates a new variable (if necessary) and gives it a value: ``` >>> message = 'And now for something completely different' >>> n = 17 >>> pi = 3.141592653589793 ``` --- ## Naming Variables Variable names: - can be as long as you like - can contain both letters and numbers - cannot begin with a number - can use uppercase letters, but it is conventional to use only lower case Use the underscore character to make multi-word names more readable: - your_name - airspeed_of_unladen_swallow. --- ## Naming Variables If you give a variable an illegal name, you will get a syntax error: ``` >>> 76trombones = 'big parade' SyntaxError: invalid syntax >>> more@ = 1000000 SyntaxError: invalid syntax >>> class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax ``` 76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal character, @. But what’s wrong with class? --- ## Python Keywords `class` is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. Python 3 has these keywords: False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise You don’t have to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you’ll know. --- ## Expressions An **expression** is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions: ``` >>> 42 42 >>> n 17 >>> n + 25 42 ``` When you type an expression at the prompt, the interpreter **evaluates** it, which means that it finds the value of the expression. --- ## Statements A statement is a unit of code that has an effect, like creating a variable or displaying a value. ``` >>> n = 17 >>> print(n) ``` When you type a statement, the interpreter **executes** it, which means that it does whatever the statement says. --- ## Order of Operations When an expression contains more than one operator, the order of evaluation depends on the **order of operations**. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules: - parentheses (can be used to force an expression to evaluate in the order you want) - exponents - multiplication and division - addition and subtraction Operators with the same precedence are evaluated from left to right --- ## String Operations In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so this is illegal: `'2'-'1'` But there are two exceptions, + and *. The + operator performs string **concatenation**, which means it joins the strings by linking them end-to-end. ``` >>> first = 'throat' >>> second = 'warbler' >>> first + second throatwarbler ``` The asterisk operator also works on strings; it performs repetition. For example: ``` >>> 'Spam'*3 SpamSpamSpam ``` If one of the values is a string, the other has to be an integer. --- class: center, middle, inverse # Comments --- ## Comments As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why. For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called **comments**, and they start with the # symbol: ``` # 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 execution of the program. --- ## Comments 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 more useful to explain why. This comment is redundant with the code and useless: ``` v = 5 # assign 5 to v ``` This comment contains useful information that is not in the code: ``` v = 5 # velocity in meters/second. ``` Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff. --- class: center, middle, inverse # Types of Errors --- ## Program Errors **Syntax error**: "Syntax" refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so `(1 + 2)` is legal, but `8)` is a syntax error. If there is a syntax error anywhere in your program, Python displays an error message and quits, and you will not be able to run the program. **Runtime error**: This 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. **Semantic error**: "Semantic" means related to meaning. If there is a semantic error in your program, it will run without generating 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. Semantic errors are also called logic errors. --- class: center, middle, inverse # Python Scripts --- ## Script Mode So far we have run Python in **interactive** mode, which means that you interact directly with the interpreter. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy. The alternative is to save code in a file called a **script** and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py. --- ## Differences between Interactive Mode and Script Mode Interactive mode: ``` >>> 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. It turns out that a marathon is about 42 kilometers. 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) ``` --- class: center, middle, inverse # Vocabulary --- ## Vocabulary variable: A name that refers to a value. assignment: A statement that assigns a value to a variable. keyword: A reserved word that is used to parse a program; you cannot use keywords like `if`, `def`, and `while` as variable names. operand: One of the values on which an operator operates. expression: A combination of variables, operators, and values that represents a single result. evaluate: To simplify an expression by performing the operations in order to yield a single value. --- ## Vocabulary statement: A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements. execute: To run a statement and do what it says. interactive mode: A way of using the Python interpreter by typing code at the prompt. script mode: A way of using the Python interpreter to read code from a script and run it. script: A program stored in a file. order of operations: Rules governing the order in which expressions involving multiple operators and operands are evaluated. concatenate: To join two operands end-to-end. --- ## Vocabulary comment: Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program. syntax error: An error in a program that makes it impossible to parse (and therefore impossible to interpret). exception: An error that is detected while the program is running. semantics: The meaning of a program. semantic error: An error in a program that makes it do something other than what the programmer intended.