Basic Python Programs
Basic Python Programs
2
Python!
● Python is an example of a high-level language
3
Python!
• Created in 1991 by Guido van Rossum (now at Google)
Named for Monty Python
• Useful as a scripting language
script: A small program meant for one-time use
Targeted towards small to medium sized projects
• Used by:
Google, Yahoo!, Youtube
Many Linux distributions
Games and apps (e.g. Eve Online)
4
Python
• “Python is an experiment in how much
freedom program-mers need. Too
much freedom and nobody can read
another's code; too little and
expressive-ness is endangered.”
- Guido van Rossum
5
Installing Python
Windows: Mac OS X:
• Download Python from • Python is already installed.
http://www.python.org • Open a terminal and run python
• Install Python. or 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.
Note: For step by step installation
instructions, see the web site. • If not, install from your
distribution's package system.
6
7
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
8
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
9
Interactive Shell
• Great for learning the language
• Great for experimenting with the library
• Great for testing your own modules
• Two variations:
IDLE (GUI )
python (command line)
10
IDLE Development Environment
• IDLE is an Integrated DeveLopment Environment for
Python, typically used on Windows
• Multi-window text editor with syntax highlighting, auto-
completion, smart indent and other.
11
Python Scripts
• When you call a python program from the command line
the interpreter evaluates each expression in the file
• Python also has mechanisms to allow a python program
to act both as a script and as a module to be imported
and used by another python program
12
Program
• A program is a sequence of instructions that specifies
how to perform a computation.
• The computation might be something mathematical,
such as solvinga system of equations or finding the
roots of a polynomial, but it can also be a symbolic
computation, such as searching and replacing text in a
document or (strangely enough) compiling a program.
13
Program Terminologies
input:
- Get data from the keyboard, a file, or some other device
output:
- Display data on the screen or send data to a file or other
device.
math:
- Perform basic mathematical operations like addition and
multiplication.
conditional execution:
- Check for certain conditions and execute the appropriate
sequence of statements.
repetition:
- Perform some action repeatedly, usually with some variation.14
Programming
Programming is a complex process, and because it is
done by human beings, it often leads to errors.
15
Three Kinds of Error
• Syntax errors
• Runtime errors
• Semantic errors
16
Syntax Error
• Syntax errors - not follow the syntax of the
program
17
Runtime Errors
• occurs once your program runs
18
Semantic Errors
• the program you wrote is not the program you wanted
to write
• If there is a semantic error in your program, it will run
successfully, in the sense that the computer will not
generate any error messages, but it will not do the right
thing.
19
Code in IDLE
>>>x = 34 - 23 # A comment.
>>>y = “Hello” # Another one.
>>>z = 3.45
>>>if z==3.45 or y=="Hello":
x = x + 1
y = y + “ World” # String concat.
print(x)
print(y)
20
Understand the Code
• Indentation matters to code meaning
Block structure indicated by indentation
• First assignment to a variable creates it
Variable types don’t need to be declared.
Python figures out the variable types on its own.
• Assignment is = and comparison is ==
• For numbers + - * / % are as expected
Special use of + for string concatenation and % for string
formatting (as in C’s printf)
• Logical operators are words (and, or, not) not symbols
• The basic printing command is print 21
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!")
22
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?')
23
Basic Datatypes
• Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
• Floats
x = 3.456
• Strings
Can use “” or ‘’ to specify with “abc” == ‘abc’
Unmatched can occur within the string: “matt’s”
Use triple double-quotes for multi-line strings or strings than
contain both ‘ and “ inside of them:
“““a‘b“c”””
24
Whitespace
• Whitespace is meaningful in Python: especially
indentation and placement of newlines
• Use a newline to end a line of code
Use \ when must go to next line prematurely
• No braces {} to mark blocks of code, use consistent
indentation instead
First line with less indentation is outside of the block
First line with more indentation starts a nested bloc
• Colons start of a new block in many constructs, e.g.
function definitions, then clauses 25
Comments
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the first line of
a new function or class you define
• Development environments, debugger, and other tools
use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive integer and
returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
26
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?')
27
Assignment
• Binding a variable in Python means setting a name to hold
a reference to some object
Assignment creates references, not copies
• Names in Python do not have an intrinsic type, objects
have types
Python determines the type of the reference automatically based
on what data is assigned to it
• You create a name the first time it appears on the left side
of an assignment expression:
x = 3
36
Variables
• A variable is a name that represents a value
stored in the computer memory
Used to access and manipulate data stored in
memory
A variable references the value it represents
37
Rules in Naming Variable
• Variable name cannot be a Python key word
• Variable name cannot contain spaces
• First character must be a letter or an
underscore
• After first character may use letters, digits, or
underscores
• Variable names are case sensitive
38
Variables
• Assignment statement: used to create a variable and
make it reference data
General format is variable = expression
Example: age = 29
Assignment operator: the equal sign (=)
In assignment statement, variable receiving value must be on
left side
Variable name should not be enclosed in quote marks
You can only use a variable if a value is assigned to it
39
Variables
• Declaring
no type is written; same syntax as assignment
Java Python
int x = 2; x = 2
x++; x = x + 1
System.out.println(x); print(x)
x = x * 8; x = x * 8
System.out.println(x); print(x)
Assignment Statement
x = 2
x = x + 2 Assignment with expression
print x Assignment Statement
42
Expression
• An expression is a combination of values,
variables, operators, and calls to function
>>> 1 + 1
2
>>> len(“hello”)
5
43
Expressions
• Arithmetic is very similar to Java
Operators: + - * / % (and ** for exponentiation)
Precedence:
()
**
* / %
+ -
Integers vs. real numbers
44
Expressions: Summary of Operators
45
Operators and Operands
• Operators are special symbols that represent
computations like addition and multiplication.
46
Expressions
>>> 1 + 1
2
>>> 1 + 3 * 4 - 2
11
>>> 7/2
3.5
>>> 7//2
3
>>> 10**5
100000 47
Programming
1. Write a program that will computes the area of the
circle
Area = 𝜋𝑅2
2. Write a program to prompt the user for hours
and rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
48
Assigning Input
• How can we let users (not programmers) input values?
• In Python, input is accomplished via an assignment
statement combined with a built-in function called input
<variable> = input(<prompt>)
• When Python encounters a call to input, it prints
<prompt> (which is a string literal) then pauses and
waits for the user to type some text and press the
<Enter> key
49
Assigning Input
52