02-Expressions
Variables, Expressions and Statements
Constants
• Numeric constants are as you expect
• String constants use single quotes (') or double quotes (")
>>> print 123
123
>>> print 98.6
98.6
>>> print 'Hello world'
Hello world
Variables
• You can change the contents of a variable in a later statement
Naming Rules
---------------
1. Must start with a letter or underscore _
2. Must consist of letters and numbers and underscores
3. Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
• You cannot use reserved words as variable names / identifiers
and del for is raise assert elif
Numeric Expressions
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
Operator Precedence Rule
Highest precedence rule to lowest precedence rule:
> Parenthesis are always respected
> Exponentiation (raise to a power)
> Multiplication, Division, and Remainder
> Addition and Subtraction
> Left to right
Integer Division
• Integer division truncates
• Floating point division produces floating point numbers
This changes in Python 3.0
>>> print 10 / 2
5
>>> print 9 / 2
4
>>> print 99 / 100
0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
• When you perform an operation where one operand is an integer and the other operand is a floating point, the result is a floating point
• The integer is converted to a floating point before the operation
>>> print 99 / 100
0
>>> print 99 / 100.0
0.99
>>> print 99.0 / 100
0.99
>>> print 1 + 2 * 3 / 4.0 - 5
-2.5
>>>
What does "Type" Mean?
• In Python variables, literals and constants have a “type”
• Python knows the difference between an integer number and a string
• For example “+” means “addition” if something is a number and “concatenate” if something is a string
>>> ddd = 1 + 4
>>> print ddd
5
>>> eee = 'hello ' + 'there'
>>> print eee
hello there
Type Matters
• Python knows what “type” everything is
• Some operations are prohibited
• You cannot “add 1” to a string
• We can ask Python what type something is by using the type() function
>>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>
TypeError: cannot concatenate
'str' and 'int' objects
>>> type(eee)
<type 'str'>
>>> type('hello')
<type 'str'>
>>> type(1)
<type 'int'>
>>>
def addtwo(a, b):
added = a + b
return added
print(type(None))
<class 'NoneType'>
print(type(addtwo))
<class 'function'>
Several Type of Numbers
• Numbers have two main types
> Integers are whole numbers:
-14, -2, 0, 1, 100, 401233
> Floating Point Numbers have decimal
parts: -2.5 , 0.0, 98.6, 14.0
• There are other number types - they are variations on float and integer
>>> xx = 1
>>> type (xx)
<type 'int'>
>>> temp = 98.6
>>> type(temp)
<type 'float'>
>>> type(1)
<type 'int'>
>>> type(1.0)
<type 'float'>
>>>
Type Conversions
• When you put an integer and floating point in an expression, the integer is implicitly converted to a float
• You can control this with the built-in functions int() and float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
>>>
String Conversions
• You can also use int() and float() to convert between strings and integers
• You will get an error if the string does not contain numeric characters
>>> sval = '123'
>>> type(sval)
<type 'str'>
>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str'
and 'int'
>>> ival = int(sval)
>>> type(ival)
<type 'int'>
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
User Input
• We can instruct Python to pause and read data from the user using the raw_input() function
• The raw_input() function returns a string
nam = raw_input('Who are you?')
print 'Welcome', nam
Who are you? Chuck
Welcome Chuck
Comments
• Anything after a # is ignored by Python
• Why comment?
> Describe what is going to happen in a sequence of code
> Document who wrote the code or other ancillary information
> Turn off a line of code - perhaps temporarily
String Operations
• Some operators apply to strings
> + implies “concatenation”
> * implies “multiple concatenation”
• Python knows when it is dealing with a string or a number and behaves appropriately
>>> print 'abc' + '123’
abc123
>>> print 'Hi' * 5
HiHiHiHiHi
>>>
Mnemonic Variable Names
• Since we programmers are given a choice in how we choose our variable names, there is a bit of “best practice”
• We name variables to help us remember what we intend to store in them (“mnemonic” = “memory aid”)
• This can confuse beginning students because well-named variables often “sound” so good that they must be keywords
http://en.wikipedia.org/wiki/Mnemonic