Getting Started Values, Expressions, and Statements CS 112 @ GMU
Topics where does code go? values and expressions variables and assignment 2
where does code go? we can use the interactive Python interpreter to have a "chat" with Python feed it expressions, and automatically print out the results, like a calculator we have to re-type code each time, so this is just for exploring, not for finished projects. finished programs are written in a file, and then we run the file in python only actual printing requests show up! the file can be run limitless times. interactive session demo$ python3 >>> 2+3 5 >>> print("pizza == yummy") pizza == yummy >>> quit() demo$ file: yummy.py 2+3 # no printing here print("pizza is yummy") print(2+3) feed file to python demo$ python3 yummy.py pizza == yummy 5 demo$
Values and Expressions
Values Values are the most basic pieces of data; they cannot be simplified any further. A literal value is one that has a direct representation in Python, such as 5 or 3.14159 We'll learn later about more values / types! python type meaning examples int integers 5 100-3 0 1000000 float approximates reals 2000.3-3.5 0.0064 3.141459 str sequence of characters "hello" "5" "so much star dust"
Expressions (examples) Expression: code representing a value that Python can calculate by performing the operations. >>> 2+3 interactive session 5 >>> 'happy ' + 'coders' 'happy coders' >>> abs(-3) + int("5") + min(10, 200, 300) 18 >>> 1+2-3*4/5 + 2**3 + 100%5 8.6
Expressions (definition) an expression is a combination of many things (variables, literal numbers and strings, function calls, operators, etc.) when Python reaches an expression, it will evaluate the expression to find the value that was represented. by itself, an expression doesn't tell Python what to do with the value!
Expression Examples Your years of math training have prepared you for programming! The following expressions all behave as you might expect: expression result notes 2+3*4 14 precedence: * before + 10-5-2 3 associativity: left '-' first 13/5 2.6 we get floats with division 13//5 2 // yields the quotient 13%5 3 % yields the remainder 2**3 8 ** means exponentiation "abc" + "def" "abcdef" we can add strings! PEMDAS ordering is in effect. (precedence) associativity: all are left-associative except exponent **
Poll 1.1 Expressions Type Precedence Associativity
Expressions: function calls code functions are similar to math functions: they convert inputs to an output. they also might have side effects, like printing function call expression: name the function, always include open/close parentheses, and put any required input expressions inside ( )'s separated by commas. max(5,10) 10 int("23") 23 print("hello!") None (but hello! does get printed)
Expressions: Strings A string is a sequence of characters. represented by placing the characters inside matching quotes various styles allowed: 'single quotes' "double quotes" '''triple single quotes''' """triple double quotes""" these "boundary markers" are not part of the string add strings to build larger ones with + (called 'concatenation'): ("ice "+"cream" + "please") "ice creamplease"
Strings: Escape Characters How do we represent quote symbols, then? With escape sequences. Typing a backslash before certain characters is a two-keystroke representation of a single character in the string. string representation \' meaning single quote \" double quote \n newline \t tab \\ one backslash character 'ten\' chars'
Poll 1.2 Strings
Variables and Assignment: Example We can store values for later use by assigning them to a named box, called a variable. these aren't math variables at all: only change when we assign to them. Some call them "assignables". >>> x = 5 >>> y = 10 >>> x*y 50 >>> x = x + 1 >>> x 6 >>> x*y 60 interactive session
Variables and Assignment
Variables A variable is a name for a spot in memory that can hold exactly one python value at a time. The exact name used is an identifier: can contain letters, digits, and underscores _ can't start with a digit
Poll 1.3 Identifiers
Assignment Statement An assignment statement is a command to Python to evaluate an expression (on the right-hand side of =), and store the result to a variable (provided on the left-hand side of =). var_name = expression "equals" is misleading think "assign" instead. "assign expression's result to var_name." each assignment throws out any previous value and replaces with the new value.
Remember: always evaluate the right-hand side first, and then perform the variable assignment. Assignment: Examples Programming variables are not math variables they are just assignable boxes. >>> counter = 0 >>> counter #interactive mode prints every result it calculates. 0 >>> counter = counter + 1 >>> counter 1 >>> counter = counter + 1 >>> counter 2 interactive session
Assignment: augmented versions Writing x = x + (expr) gets tedious. An equivalent alternative is x += expr More exist, including: += -= *= /= //= %= Examples: x = x+1 radiation /= 2 score *= multiplier
Poll 1.4 Assignment.
Types: conversion some built-in functions help us convert values between types in predictable ways: int(2.3) 2 float("3.45") 3.45 str(2+3) "5" function(arg) int(x) float(x) str(x) <many more exist> meaning convert string/number to int convert string/number to float convert anything to a string
Type conversion: use case >>> print("i have " + 3 + " apples.") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly >>> print("i have " + str(3) + " apples.") I have 3 apples. >>> Python doesn't convert types automatically we convert as needed Note the traceback: Python is telling us everything it knew when the program crashed. Learn to read them for valuable debugging info!
python documentation Language Reference https://docs.python.org/3/reference/index.html describes the syntax and "core semantics" of the language it is terse, but attempts to be exact and complete Library Reference https://docs.python.org/3/library/index.html describes the "built-in" functions and other commonly included modules
Syntax Examples C++ Program K #include <iostream> int main() { std::cout << "Game Over!" << std::endl; return 0; } Java Program K public class GameOver { public static void main (String[] args) { System.out.println("So verbose!"); } } Python Program J print("python rocks!")