Difference between revisions of "Python - Operators, Expressions"

From Computer Science
Jump to: navigation, search
(Assignment)
(Data Types and Literals)
Line 63: Line 63:
 
* '''Integer''' - literals are numbers that do not have decimal points and are not contained in quotes. Note that integer arithmetic in Python is ''arbitrary precision'', meaning that Python integers have no maximum value (a very nice feature). Examples of integer literals: <code>1234</code>, <code>-1234</code>
 
* '''Integer''' - literals are numbers that do not have decimal points and are not contained in quotes. Note that integer arithmetic in Python is ''arbitrary precision'', meaning that Python integers have no maximum value (a very nice feature). Examples of integer literals: <code>1234</code>, <code>-1234</code>
 
* '''Floating point''' - literals are numbers that have a decimal point. Python does ''not'' use arbitrary precision with floating point arithmetic (meaning that there are limits to how large floating point numbers can be, and how many digits of precision). Examples of integer literals: <code>1234.0</code>, <code>3.14159</code>
 
* '''Floating point''' - literals are numbers that have a decimal point. Python does ''not'' use arbitrary precision with floating point arithmetic (meaning that there are limits to how large floating point numbers can be, and how many digits of precision). Examples of integer literals: <code>1234.0</code>, <code>3.14159</code>
* '''String''' - text data, which is between matching <code>'single quotes'</code>, <code>"double quotes"</code>, <code>'''triple single quotes'''</code>, or <code>"""triple double quotes"""</code>. Other examples of string literals: <code>'1234'</code>, <code>'True'</code>, <code>'x = 3'</code>  
+
* '''String''' - text data, which is between matching <code>'single quotes'</code>, <code>"double quotes"</code>, <code>\'\'\'triple single quotes\'\'\'</code>, or <code>"""triple double quotes"""</code>. Other examples of string literals: <code>'1234'</code>, <code>'True'</code>, <code>'x = 3'</code>  
 
* '''Boolean''' - literals are <code>True</code> and <code>False</code>
 
* '''Boolean''' - literals are <code>True</code> and <code>False</code>
 
* '''None''' - <code>None</code> is a special value in Python that is its own type.
 
* '''None''' - <code>None</code> is a special value in Python that is its own type.
Line 70: Line 70:
 
* '''Dictionary''' - a container type where each item has a ''key'' used for looking up the item and a ''value'' that is stored with the key, specified with matching {} where each item is given as key:value.  Examples: <code>{'name': 'Alice', 'age': 42}</code>, <code>{'h1': 97, 'h2': 100, 'exams': [95, 34, 77]}</code>
 
* '''Dictionary''' - a container type where each item has a ''key'' used for looking up the item and a ''value'' that is stored with the key, specified with matching {} where each item is given as key:value.  Examples: <code>{'name': 'Alice', 'age': 42}</code>, <code>{'h1': 97, 'h2': 100, 'exams': [95, 34, 77]}</code>
 
* '''Set''' - a container type where there are no duplicates of items, specified with matching {} where each item is just a value (not a key:value as in dictionaries).  Examples: <code>{'orange', 'apple', 'banana'}</code>, <code>{99, 98, 96}</code>
 
* '''Set''' - a container type where there are no duplicates of items, specified with matching {} where each item is just a value (not a key:value as in dictionaries).  Examples: <code>{'orange', 'apple', 'banana'}</code>, <code>{99, 98, 96}</code>
+
 
 
==Assignment==
 
==Assignment==
 
A typical "assignment" is to require a student to be able to correctly evaluate arbitrary expressions involving the operators.  You can think of this building up in complexity.
 
A typical "assignment" is to require a student to be able to correctly evaluate arbitrary expressions involving the operators.  You can think of this building up in complexity.
 
* Literal expressions - you should be able to identify the data type and value of any literal expression. The basic data types in Python are - integer, floating point, string, Boolean, tuple, list, dictionary, set, None.
 
* Literal expressions - you should be able to identify the data type and value of any literal expression. The basic data types in Python are - integer, floating point, string, Boolean, tuple, list, dictionary, set, None.

Revision as of 20:30, 20 August 2022

Following are terse descriptions for Python3 operators. For more information, see your Python reading material.

Operators

The following are a basic set of operators that most will intuitively know what they do.

  • Arithmetic operators: + - * / //
    • Note that / is floating point division (3/2 is 1.5), while // is integer division (3//2 is rounded down to 1).
  • Assignment operators: =
  • Comparison operators: < <= == != >= >
    • Note that == tests if two values are equal, != tests if they are not equal (3 != 2 will be True, 3 == 2 will be False).
  • Logical operators: and or not
  • Membership operators: in, not in

More Operators

The following are more operators. These may not be obvious. Some examples are given, but you may need to read through your Python text to understand these.

  • Arithmetic operators: % **
    •  % is remainder (10 % 3 is 1, 17 % 3 is 2), and ** is exponentiation (10**3 is 1000, 2**3 is 8).
  • Assignment operators: += -= *= /= //= %= **= &= |= ^= >>= <<=
    • Each of these is shorthand. For example, x += 3 is a shorthand for x = x + 3
  • Identity operators: is, is not
    • Tests whether two objects are the same, not just whether the values are the same. For simple variables/expressions, is will be the same as ==, but for lists/tuples/dictionaries is only gives True if the two things being compared are actually the same object (not just the same values).
  • Bitwise operators: & | ^ ~ << >>
    • These operate on the bits of a number. You need to understand binary before you can understand these. Examples: 12 & 8 evaluates to 8, 12 | 7 evaluates to 15, 12 ^ 8 evaluates to 4, ~7 evaluates to -8 (same as -7-1), 3 << 2 evaluates to 12, 12 >> 1 evaluates to 6.
  • Brackets: [ : ]
    • Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries. If A = (1, 2, 'hello', 'hi', 10, 5) then A[0] is the first item (which is 1) and A[1] is the second (which is 2). The : is used inside of square brackets to obtain a slice of elements (some chunk of them). A[2:4] would be a tuple that starts with the third element of A and include 2 of the elements (so it would be ('hello', 'hi')).
  • Parenthesis: ( , )
    • Parenthesis as part of math expressions are used for enforcing a desired order of operations.
    • Parenthesis immediately after a function name are used for either defining or calling a function. In both cases, the , is used to separate parameters.

Expressions

There are many rules to keep in mind for how expressions are evaluated by Python. The following are some of the rules you need to remember, and some examples to put into python to see what they evaluate to

  • Operator precedence - inside of parenthesis first, then exponentiation, then multiplication/division/remainder, then addition/subtraction, then assignment. Full list of operator precedence - at python.org.
    • 1 + 2 * 3
    • 1 + 2 * 9 ** 0.5
    • (1 + 2) * 3
  • 0-based indexing - index into string/list/tuple starts at 0
    • 'hello'[0]
    • (1, 2, 3)[1]
  • Slices - x[i:j+1] evaluates to a subsequence of x starting at index i and ending at index j
    • 'hello'[1:3]
    • [1, 2, 3, 4, 5][2:4]
  • String constants - anything inside of single quotes or double quotes, and + for strings is concatenation
    • 'hi' + ' there'
    • "2" + '3'
    • str(2) + str(3)
    • 2 + 3
    • Triple single or double quotes can also be used, mainly to easily give string constants that are multiple lines long -
message = '''
This message is more than one 
line long.
'''
  • Boolean operators - note that and is higher precedence than or and that compound Boolean expression should be made out of complete Boolean expressions that are and'ed, or'ed together. To check whether a variable x is 'a' or 'A', you need if x == 'a' or x == 'A':. If you tried using if x == 'a' or 'A': this always evaluates to True (because the part after the or, 'A', is considered to be True [anything that is not 0, , or None - is True]).
  • Immutability - string and tuple variables are immutable, they cannot be changed. This also means that any string/tuple methods do not change the value of the string but only return a new string/tuple.
x = 'Hello'
x.upper()
print(x)
x = x.upper()
print(x)

Data Types and Literals

A "literal", when used in the context of programming, is a basic value that is contained within a program. The value of the literal is, literally, the value that it seems to be. The following are the basic data types in Python, and examples of literals for each.

  • Integer - literals are numbers that do not have decimal points and are not contained in quotes. Note that integer arithmetic in Python is arbitrary precision, meaning that Python integers have no maximum value (a very nice feature). Examples of integer literals: 1234, -1234
  • Floating point - literals are numbers that have a decimal point. Python does not use arbitrary precision with floating point arithmetic (meaning that there are limits to how large floating point numbers can be, and how many digits of precision). Examples of integer literals: 1234.0, 3.14159
  • String - text data, which is between matching 'single quotes', "double quotes", \'\'\'triple single quotes\'\'\', or """triple double quotes""". Other examples of string literals: '1234', 'True', 'x = 3'
  • Boolean - literals are True and False
  • None - None is a special value in Python that is its own type.
  • Tuple - a container type, specified with matching (), that is immutable. Examples: ('a', 'b', 'c'), ('a', )
  • List - a container type, specified with matching [], that is mutable. Examples: ['a', 'b', 'c'], ['a', ]
  • Dictionary - a container type where each item has a key used for looking up the item and a value that is stored with the key, specified with matching {} where each item is given as key:value. Examples: {'name': 'Alice', 'age': 42}, {'h1': 97, 'h2': 100, 'exams': [95, 34, 77]}
  • Set - a container type where there are no duplicates of items, specified with matching {} where each item is just a value (not a key:value as in dictionaries). Examples: {'orange', 'apple', 'banana'}, {99, 98, 96}

Assignment

A typical "assignment" is to require a student to be able to correctly evaluate arbitrary expressions involving the operators. You can think of this building up in complexity.

  • Literal expressions - you should be able to identify the data type and value of any literal expression. The basic data types in Python are - integer, floating point, string, Boolean, tuple, list, dictionary, set, None.