Difference between revisions of "Python - Operators, Expressions"
(→More Operators) |
(→Assignment) |
||
(21 intermediate revisions by the same user not shown) | |||
Line 3: | Line 3: | ||
=Operators= | =Operators= | ||
The following are a basic set of operators that most will intuitively know what they do. | The following are a basic set of operators that most will intuitively know what they do. | ||
+ | * '''Comments:''' <code>#</code> is used to demarcate comments - anything after a # on a line is ignored by the python interpreter. | ||
* '''Arithmetic operators:''' <code>+ - * / //</code> | * '''Arithmetic operators:''' <code>+ - * / //</code> | ||
** Note that / is floating point division (3/2 is 1.5), while // is integer division (3//2 is rounded down to 1). | ** Note that / is floating point division (3/2 is 1.5), while // is integer division (3//2 is rounded down to 1). | ||
Line 23: | Line 24: | ||
* '''Brackets:''' <code>[ : ]</code> | * '''Brackets:''' <code>[ : ]</code> | ||
** Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries. If <code>A = (1, 2, 'hello', 'hi', 10, 5)</code> then <code>A[0]</code> is the first item (which is 1) and <code>A[1]</code> is the second (which is 2). The : is used inside of square brackets to obtain a ''slice'' of elements (some chunk of them). <code>A[2:4]</code> would be a tuple that starts with the third element of A and include 2 of the elements (so it would be ('hello', 'hi')). | ** Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries. If <code>A = (1, 2, 'hello', 'hi', 10, 5)</code> then <code>A[0]</code> is the first item (which is 1) and <code>A[1]</code> is the second (which is 2). The : is used inside of square brackets to obtain a ''slice'' of elements (some chunk of them). <code>A[2:4]</code> 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:'' <code> ( , )</code> | + | * '''Parenthesis:''' <code> ( , )</code> |
** Parenthesis as part of math expressions are used for enforcing a desired order of operations. | ** 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 <code>,</code> is used to separate parameters. | ** Parenthesis immediately after a function name are used for either defining or calling a function. In both cases, the <code>,</code> is used to separate parameters. | ||
Line 39: | Line 40: | ||
** <code>'hello'[1:3]</code> | ** <code>'hello'[1:3]</code> | ||
** <code>[1, 2, 3, 4, 5][2:4]</code> | ** <code>[1, 2, 3, 4, 5][2:4]</code> | ||
− | * '''String constants''' - anything inside of quotes, and + for strings is concatenation | + | * '''String constants''' - anything inside of single quotes or double quotes, and + for strings is concatenation |
** <code>'hi' + ' there'</code> | ** <code>'hi' + ' there'</code> | ||
− | ** <code> | + | ** <code>"2" + '3'</code> |
** <code>str(2) + str(3)</code> | ** <code>str(2) + str(3)</code> | ||
** <code>2 + 3</code> | ** <code>2 + 3</code> | ||
+ | ** Triple single or double quotes can also be used, mainly to easily give string constants that are multiple lines long - | ||
+ | <pre> | ||
+ | message = ''' | ||
+ | This message is more than one | ||
+ | line long. | ||
+ | ''' | ||
+ | </pre> | ||
* '''Boolean operators''' - note that <code>and</code> is higher precedence than <code>or</code> 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 <code>if x == 'a' or x == 'A':</code>. If you tried using <code>if x == 'a' or 'A':</code> 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]). | * '''Boolean operators''' - note that <code>and</code> is higher precedence than <code>or</code> 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 <code>if x == 'a' or x == 'A':</code>. If you tried using <code>if x == 'a' or 'A':</code> 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. | * '''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. | ||
Line 51: | Line 59: | ||
x = x.upper() | x = x.upper() | ||
print(x)</code> | print(x)</code> | ||
+ | |||
+ | ==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). Integers can be given in binary, octal, or hexadecimal using a leading <code>0b</code>, <code>0o</code>, or <code>0x</code>. <code>_</code> can be used within the digits to make grouping of digits easier to read. Examples of integer literals: <code>1234</code>, <code>-1234</code>, <code>16</code>, <code>0b10000</code>, <code>0o20</code>, <code>0x10</code>, <code>1_000_000_000</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). Scientific notation can be used. Examples of integer literals: <code>1234.0</code>, <code>3.14159</code>, <code>1_000_000.0</code>, <code>1e6</code> | ||
+ | * '''String''' - text data, which is between matching <code>'single quotes'</code>, <code>"double quotes"</code>, <code><nowiki>'''triple single quotes'''</nowiki></code>, or <code>"""triple double quotes"""</code>. Optionally, a <code>r</code> or <code>f</code> can be given before the quotes, to give a ''raw string'' or ''format string''. raw strings treat escape characters literally, and format strings evaluate python expressions inside of <code>{ }</code>. Other examples of string literals: <code>'1234'</code>, <code>'True'</code>, <code>'x = 3'</code>, <code>r'\n is normally a newline but not in raw strings'</code>, <code>f'5*5 = {5*5}'</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. | ||
+ | * '''Tuple''' - a ''container type'', specified with matching (), that is ''immutable''. Examples: <code>('a', 'b', 'c')</code>, <code>('a', )</code> | ||
+ | * '''List''' - a container type, specified with matching [], that ''is'' mutable. Examples: <code>['a', 'b', 'c']</code>, <code>['a', ]</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> | ||
+ | |||
+ | ==Other== | ||
+ | Here we give additional operators and punctuation that have meaning in python, but which we don't go into here because they are not commonly used in beginning python. For each of these you should just know that they exist and remember the description of what they mean. If you need to use them or need to understand code that uses them, you should ask the internet for examples and explanation. | ||
+ | * <code>\</code> can be used to break a long line into multiple lines while having python still regard them as a single logical line. | ||
+ | * <code>@</code> is used to make decorator functions. | ||
+ | * <code>:</code> and <code>-></code> can be used to annotate function definitions. | ||
+ | * <code>:=</code> can be used to assign a value within an expression. | ||
+ | |||
+ | ==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. | ||
+ | * Binary operators - you should be able to evaluate an expression that has just two operands (e.g., 'hello' + 'cat'). | ||
+ | * Larger expressions - you should be able to evaluate larger expressions using the python rules for order of operations (e.g., '3' + '5' * 4) | ||
+ | |||
+ | A practice quiz that you can take is here - '''[https://indstate.instructure.com/courses/12565/quizzes/228160?module_item_id=1145792 Python Operators and Expressions Quiz]'''. | ||
+ | |||
+ | '''Pass rating check''' If you are assigned this quiz in a course, you should be able to score 100% on the quiz. |
Latest revision as of 18:01, 7 September 2022
Following are terse descriptions for Python3 operators. For more information, see your Python reading material.
Contents
Operators
The following are a basic set of operators that most will intuitively know what they do.
- Comments:
#
is used to demarcate comments - anything after a # on a line is ignored by the python interpreter. - 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 forx = x + 3
- Each of these is shorthand. For example,
- 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/dictionariesis
only gives True if the two things being compared are actually the same object (not just the same values).
- Tests whether two objects are the same, not just whether the values are the same. For simple variables/expressions,
- 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)
thenA[0]
is the first item (which is 1) andA[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')).
- Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries. If
- 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 thanor
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 needif x == 'a' or x == 'A':
. If you tried usingif 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). Integers can be given in binary, octal, or hexadecimal using a leading
0b
,0o
, or0x
._
can be used within the digits to make grouping of digits easier to read. Examples of integer literals:1234
,-1234
,16
,0b10000
,0o20
,0x10
,1_000_000_000
- 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). Scientific notation can be used. Examples of integer literals:
1234.0
,3.14159
,1_000_000.0
,1e6
- String - text data, which is between matching
'single quotes'
,"double quotes"
,'''triple single quotes'''
, or"""triple double quotes"""
. Optionally, ar
orf
can be given before the quotes, to give a raw string or format string. raw strings treat escape characters literally, and format strings evaluate python expressions inside of{ }
. Other examples of string literals:'1234'
,'True'
,'x = 3'
,r'\n is normally a newline but not in raw strings'
,f'5*5 = {5*5}'
- Boolean - literals are
True
andFalse
- 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}
Other
Here we give additional operators and punctuation that have meaning in python, but which we don't go into here because they are not commonly used in beginning python. For each of these you should just know that they exist and remember the description of what they mean. If you need to use them or need to understand code that uses them, you should ask the internet for examples and explanation.
\
can be used to break a long line into multiple lines while having python still regard them as a single logical line.@
is used to make decorator functions.:
and->
can be used to annotate function definitions.:=
can be used to assign a value within an expression.
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.
- Binary operators - you should be able to evaluate an expression that has just two operands (e.g., 'hello' + 'cat').
- Larger expressions - you should be able to evaluate larger expressions using the python rules for order of operations (e.g., '3' + '5' * 4)
A practice quiz that you can take is here - Python Operators and Expressions Quiz.
Pass rating check If you are assigned this quiz in a course, you should be able to score 100% on the quiz.