Python
Python
1
FUNDEMENTALS OF COMPUTER SCIENCE
Lecture 7
2
PYTHON
3
Installing Python
Windows: Mac OS X:
• Download Python from • Python is already installed.
http://www.python.org
• Open a terminal and run python or
• Install Python. run Idle from Finder.
• Run Idle from the Start Menu.
Linux:
• Chances are you already have Python
installed. To check, run python from
the terminal.
• If not, install from your distribution's
package system.
Note: For step by step installation
instructions, see the course web site.
4
Interpreted Languages
• interpreted
• Not compiled like Java
• Code is written and then directly executed by an interpreter
• Type commands into interpreter and see immediate results
Java: Runtime
Code Compiler Computer
Environment
5
The Python Interpreter
• Allows you to type commands one-at-a-time and see results
• A great way to explore Python's syntax
• Repeat previous command: Alt+P
6
Our First Python Program
• Python does not have a main method like Java
• The program's main code is just written directly in the file
• Python statements do not end with semicolons
hello.py
1 print("Hello, world!")
7
The print Statement
print("text")
print() (a blank line)
• Escape sequences such as \" are the same as in Java
• Strings can also start/end with '
swallows.py
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it together.")
4 print('African or "European" swallows?')
8
Comments
• Syntax:
# comment text (one line)
swallows2.py
1 # Suzy Student, CSE 142, Fall 2097
2 # This program prints important messages.
3 print("Hello, world!")
4 print() # blank line
5 print("Suppose two swallows \"carry\" it together.")
6 print('African or "European" swallows?')
9
Constants
• Fixed values such as numbers, letters, and strings are called
“constants” - because their value does not change
• 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 10
Variables
• A variable is a named place in the memory where a programmer
can store data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement
12
Variables in Python
•
Variables need not be declared first in python. They can be used
directly. Variables in python are case sensitive as most of the other
programming languages.
• Examples
• A=3
• a=4
• Print(A)
•3
13
Numeric Expressions
Operator Operation
• Because of the lack of mathematical
+ Addition
symbols on computer keyboards - we
use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication
• Asterisk is multiplication
/ Division
• Exponentiation (raise to a power)
looks different from in math. Integer
//
division
** Power
% Remainder
14
Numeric Expressions
5280 ** Power
x = 1 + 2 * 3 - 4 / 5 ** 6
16
Operator Precedence Rules
• Highest precedence rule to lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and Remainder
• Addition and Subtraction Parenthesis
• Left to right Power
Multiplication
Addition
Left to Right
17
Operator Precedence Rules
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print x
11 1+8/4*5
>>>
1+2*5
Parenthesis
Power 1 + 10
Multiplication
Addition 11
Left to Right
18
Numeric Expressions
• 10 // 3 produces 3
• while 10 % 3 produces 1
19
Comparison Operators
Python also has comparison operators, such as Less-
Than (<), Greater-Than (>), Less-Than-or-
Equal(<=), Greater-Than-or-Equal (>=), and
Equality-Test (==). These operators produce a True
or False value.
20
DANGER! Operator Overloading!
NOTE! Some operators will work in a different way depending upon
what their operands are.
For example, when you add two numbers you get the expected result:
3 + 3 produces 6.
But if you “add” two or more strings, the + operator produces a
concatenated version of the strings: “Hi” + “Jay” produces “HiJay”
Multiplying strings by a number repeats the string!
“Hi Jay” * 3 produces “Hi JayHi JayHiJay”
21
Data Types
In Python, all data has an associated data “Type”.
You can find the “Type” of any piece of data by using the type()
function:
type( “Hi!”) produces <type 'str'>
type( True ) produces <type 'bool'>
type( 5) produces <type 'int'>
type(5.0) produces <type 'float'>
Note that python supports two different types of numbers, Integers
(int) and Floating point numbers (float). Floating Point numbers have a
fractional part (digits after the decimal place), while Integers do not!
22
Type Conversion
Data can sometimes be converted from one type to another.
For example, the string “3.0” is equivalent to the floating point number
3.0, which is equivalent to the integer number 3
Functions exist which will take data in one type and return data in
another type.
int() - Converts compatible data into an integer. This function will truncate
floating point numbers
float() - Converts compatible data into a float.
str() - Converts compatible data into a string.
Examples:
int(3.3) produces 3 str(3.3) produces “3.3”
float(3) produces 3.0 float(“3.5”) produces 3.5
int(“7”) produces 7
int(“7.1”) throws an ERROR!
float(“Test”) Throws an ERROR!
23
Assignment Statements
• Syntax: Assignment → variable = expression
• A variable’s type is determined by the type of the value assigned to it.
• Multiple_assign →var{, var} = expr{, expr)
>>> x, y = 4, 7
>>> x
4
>>> y
7
>>> x, y = y, x
>>> x
7
>>> y
4
>>>
24
Interactive Input
• Syntax: input → variable = input(string)
The string is used as a prompt.
Inputs a string
>>> y = input("enter a name --> ")
enter a name --> max
>>> y
'max'
>>> number = input("Enter an integer ")
Enter an integer 32
>>> number
’32’
• input() reads input from the keyboard as a string;
25
Input
• To get numeric data use a cast :
>>> number = int(input("enter an integer: "))
enter an integer: 87
>>> number
87
• If types don’t match (e.g., if you type 4.5 and try
to cast it as an integer) you will get an error:
ValueError: invalid literal for int() with base 10:
26
Input
• Multiple inputs:
>>> x, y = int(input("enter an integer: ")),
float(input("enter a float: "))
enter an integer: 3
enter a float: 4.5
>>> print("x is", x, " y is ", y)
x is 3 y is 4.5
• Instead of the cast you can use the eval( ) function and Python
choose the correct types:
>>> x, y = eval(input("Enter two numbers: "))
Enter two numbers: 3.7, 98
>>> x, y
(3.7, 98)
27
Program Example
• Find the area of a circle given the radius:
• Radius = 10
• pi = 3.14159
• area = pi * Radius * Radius
• print( area )
28
Code Abstraction & Reuse Functions
If you want to do something (like calculate the area of a circle)
multiple times, you can encapsulate the code inside of a Function.
A Function is a named sequence of statements that perform some
useful operation. Functions may or may not take parameters, and
may or may not return results.
Syntax:
def NAME( LIST OF PARAMETERS):
STATEMENTS
STATEMENTS
29
How to use a function
You can cause a function to execute by “calling” it as follows:
functionName( Parameters)
You can optionally assign any result that the function returns to a variable
using the assignment operator:
returnResult = functionName(Parameters)
30
Indentation is IMPORTANT!
A function is made up of two main parts, the Header, and the Body.
The function header consists of:
def funcName(param1,param2):
def keyword
function name
zero or more parameters, comma separated, inside of parenthesis ()
A colon :
The function body consists of all statements in the block that
directly follows the header.
A block is made up of statements that are at the same indentation
level.
31
findArea function naive example
• def findArea( ):
• Radius = 10
• pi = 3.1459
• area = pi * Radius * Radius
• print(area)
33
findArea function best example
• def findArea( Radius ):
• pi = 3.1459
• area = pi * Radius * Radius
• return area
34
Reserved Words
• You can not use reserved words as variable names / identifiers
38