Website for the UCSB Data Science Capstone Preparation Workshop
print and assignment statementsprint statement: https://docs.python.org/3/library/functions.html#print= to create a new variable/object/ performs division; subtraction operator - is also the operator for negation (e.g., -val + rate).See additional bolded terms below.
Python creates a new variable, which is actually a new Python object, each time you use an assignment statement.
= is not “equals”!
Thus, num = 11 is read as “num is assigned with 11” (or “11 is assigned to num”) instead of “num equals 11”.
A print statement allows you to display the value of an object/variable or a result of running an expression.
Take a look at the documentation to see the optional parameters sep and end and their default values:
https://docs.python.org/3/library/functions.html#print.
Play around with them to get a sense of what they do and how to change them.
Boolean (True / False)
1 == True
0 == False
Technically, anything that’s != 0 is True.
Comparison Operators
> , >= , < , <=
and , or , not
== # equal
!= # not equal
Comparison Statements
42 == 42 # True
“cat” == “cat” # True
“cat” == “dog” # False
“cat” != “dog” # True
+ - * /
** # power, e.g., 2^3 is 2**3 in Python
Increasing a variable’s value by 1, as in num = num + 1, is known as incrementing the variable.
A shorthand for it is num += 1 (same for the other basic operators).
These are special, compound operators and include -=, *=, /=, and %=.
Play around with them and test the order of operations:
print(6 * 7) # 42
print(2**3) # 8
Which one of the following lines is this statement print(2**3**4) equivalent to?
print((2**3)**4)
print(2**(3**4))
The division operator / performs division and returns a floating-point number.
The floored division operator // rounds down the result of a floating-point division to the closest whole number. The result is an integer if both operands are integers; otherwise, if either operand is a float, a float is returned.
% - modulo, i.e., remainder
The modulo operator is commonly used to determine if the number is even or odd. (If you have a variable num, how would you determine if it’s even or odd?)
print(11 / 8)
print(11 // 8)
print(11 % 8) # 3
Given a credit card number stored as an integer, % and // can be used to get any part, such as the prefix.
789 // 10 is 78 and 789 // 100 is …789 % 10 is … and 789 % 100 is …An expression is evaluated using the order of standard mathematics, known in programming as precedence rules. The PEMDAS (pronounced “pem-dass”) acronym stands for the following standard mathematical order of operations:
PEMDAS applies in Python programming as well and if more than one operator of equal precedence could be evaluated, evaluation occurs left to right (except that the ** operator is evaluated from right-to-left).
Good practice is to use parentheses to make order of evaluation explicit, rather than relying on precedence rules.
=?sep and end?/, //, and %?print('Name' user_name)? Why?