Another Simple Program


#***************************************
# File: Camus.py
# Author: Mary Eberlein
#
# A simple first Python program
#***************************************

# print a Camus quote

def main():
    print "Camus said:"  # print text and then go to next line

    # The escape sequence \n does a carriage return.
    # If we want to include double quotes in the text we are displaying, we can
    # enclose the text in single quotes.
    print '"Some people talk in their sleep. \nLecturers talk while other people sleep." '
   
main()


Output

Camus said:
"Some people talk in their sleep.
Lecturers talk while other people sleep."




What's In Our Program?




Another function example

def add(num1, num2):
    sum = num1+num2
    print "sum = ", sum

# call the add function
add(5, 7)
add(2, 9)

Output:
sum = 12
sum = 11









Nuts and Bolts for Python Programs



Printing made nicer:
Escape Sequences - Two character sequences that represent other characters
Note: If we want to print text that appears on multiple lines, we can surround the text by triple quotes:

print """One
Two
Three"""

Ouput:
One
Two
Three


Identifiers and Keywords






Variables




Operators

+       addition
 -       subtraction
 *       multiplication
 /        division
**       exponentiation
%       remainder
abs()  absolute value


Examples:
15 + 2 is 17
3 - 1 is 2
15/4 is 3  <----- If you divide one integer by another, the result is an integer (the remainder is lost).
11.0/4 is 2.75
15%2 is 1
25%5 is 0
21% 6 is 3
2**3 is 8


Example:
>>>abs(-3)
3
>>> abs(-2.3)
2.29999999999999998

Note: Not all floating point numbers can be stored exactly, as you see in the above example.


Example: Write a program that assigns values to 2 variables that represent the length and width of a rectangle, and then prints the rectangle's area.

Example: Write a program that assigns integer values to 3 variables that represent test scores, and then computes and prints the average score to the screen.




Conversions between Numeric Types

Numbers which are integers, like 150 or 2, are of type int.
Numbers with fractional parts, like 3.75 or 2.111, are of type float.

Example:
>>> type(3)
<type 'int'>
>>> type(3.5)
<type 'float'>
>>> type(3.0)
<type 'float'>

For binary operations on numeric values of different types:
The operand of type int is converted to float.

Example:
>>>3+4
7
>>>3.0+4
7.0


Otherwise, the result of a binary operation has the same type as the operands.



Operator Precedence

1. **
2. * / %
3. + -

Given multiple operators of the same precedence, those operators are executed in order from left to right.

We can always change this precedence using parentheses.

Example:
>>> 2*10%5
0
>>>5.0 + 6/2
8.0




Arithmetic Operator Examples