Python Basic
Python Basic
• Interpreted
• Not compiled like Java
• This means: type commands and see
results
• Targeted towards short to medium
sized projects
• Useful as a scripting language
A whaa?
script – short Compile Runtime Compute
program meant for Code
r Env r
one-time use.
Compute
Code Interpreter
r
>>> Getting it Going
Windows Mac OSX Linux
Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 System.out.println("Hello world!");
4 }
5 } Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 hello();
4 }
5 public static void hello(){
6 System.out.println("Hello world!");
7 }
8 }
>>> Missing Main
Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 System.out.println("Hello world!");
4 }
5 }
hello.py
1 def hello():
2 print
3 "Hello \"world\"!"
4
hello()
>>> Example 1
Example: Write a method that
produces the following
output.
e are the Knights Who Say... "Nee!"
Nee! Nee! Nee!)
def knights():
print "We are the Knights Who Say... \"Nee!\""
print "(Nee! Nee! Nee!)"
print
def poorSouls():
print "NO!\t Not the Knights Who Say \"Nee\"..."
print
knights()
poorSouls()
knights()
>>> Example 2
Example: Write a method that
produces the following
output.
______
/ \
/ \
\ /
\______/
\ /
\______/
+--------+
______
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+
>>> Example 2
Example: Write a method that def egg(): def top():
produces the following top() print " ______"
output.
______ bottom() print " / \
/ \ print print "/
/ \
\ /
\______/ def cup(): def bottom():
bottom() print "\\
\ / line() print " \\______
\______/ print
+--------+
def line():
______ def stop(): print "+--------
/ \ top()
/ \ print "| STOP |"
egg()
| STOP | bottom() cup()
\ /
\______/ print stop()
hat()
______ def hat():
/ \ top()
/ \ line()
+--------+
print
>>> Types
Python cares very little about types.
Java pytho
In Java, one must declare a variable
with a particular type and maintain 178 int n
int
that type throughout the existence of 175.0 double float
that variable. In other words, ints “wow” String str
can be only stored in places 'w' char str
designated for ints, same for doubles True boolean bool
etc.
+ - * / %
Integer division – rounds down to
nearest int
Precedence – same rules
Mixing types – numbers change to
keep precision
Real numbers are kept as “floats”
or floating point numbers
>>> Differences in expressions
There are a few things that
differ between Python and
Java, such as: >>> "Hello!"*3
'Hello!Hello!Hello!'
You can multiply strings in >>> x = 1
>>> x += 1
python! >>> print x
2
There are no increment
operators in python (++, --)
so we have to use -= and +=
>>> Variables
As we said earlier, Python cares
less about types. When we create
a variable in Python, the type of
the variable doesn’t matter. As a expressions.py
result, in Python, creating a 1 x = 2
variable has the same syntax as 2 x += 1
setting a value to a variable. 3 print( x)
Variables.java
1 ... 4 x = x * 8
2 5 print (x)
int x = 2; 6
3 x++;
4 7 d = 3.0
System.out.println(x); 8 d /= 2
5 x = x * 8;
6 9 print (d)
System.out.println(x); 10
7
11 s = "wow"
8 double d = 3.0; 12 print (s)
9 d /= 2;
10 13
System.out.println(d); 14
11
15
16
>>> Constants
Continuing Python's free spirited
ways, it has much less restrictions constants.py
than Java. Because of this, 1 SIZE = 2
constants are possible but not in a 2 x = 10 * SIZE
commonly used manner. Instead, 3 print x
we'll designate constants in Python 4
solely by the variable 5 # main
capitalization. 6 …
We do need to write the constants
at the top of our program so that
every function can see them!
>>> print 123
Fixed values such as numbers, 123
letters, and strings are called >>> print 98.6
“constants” - because their value 98.6
does not change >>> print 'Hello world'
Numeric constants are as you Hello world
expect
String constants use single-
quotes (')
or double-quotes (")
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
x = 12.2 x 12.2100
y = 14
x = 100 y 14
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores
• Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
Reserved Words
x = 3.9 * x * ( 1 - x
A variable is a memory
location used to store a
x 0.6
value (0.6).
0.6
0.6
x = 3.9 * x * ( 1
0.4
x = 3.9 * x * ( 1
Right side is an
expression. Once
expression is evaluated, 0.93
% Remainder
Numeric Expressions
>>> xx = 2 >>> jj = 23
>>> xx = xx + 2>>> kk = jj % 5 Operato Operatio
r n
>>> print xx >>> print kk
+ Addition
4 3
Subtractio
>>> print 4 ** 3
>>> yy = 440 * 12 -
n
64
>>> print yy *
Multiplica
tion
5280
/ Division
>>> zz = yy / 1000 4 R 3
>>> print zz 5 23
** Power
5 20 %
Remainde
r
3
Order of Evaluation
x = 1 + 2 * 3 - 4 / 5 ** 6
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
• Left to right Parenthesis
Power
Multiplicatio
Addition
Left to Right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11 1 + 8 / 4 * 5
>>>
Parenthesis 1 + 2 * 5
Power
Multiplication
Addition 1 + 10
Left to Right
11
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11 1 + 8 / 4 * 5
>>>
Parenthesis 1 + 10
Power
Multiplication
Addition 11
Left to Right
Operator Precedence
Parenthesis
Power
• Remember the rules top to bottom Multiplication
• When writing code - use parenthesis Addition
Left to Right
• When writing code - keep mathematical expressions
simple enough that they are easy to understand
• Break long series of mathematical operations up to
make them more clear
Exam Question: x = 1 + 2 * 3 - 4 / 5
Python Integer Division is Weird!
>>> print 10 / 2
• Integer division truncates
5
• Floating point division >>> print 9 / 2
produces floating point 4
numbers >>> print 99 / 100
0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
This changes in Python 3.0
Mixing Integer and Floating
>>> print 99 / 100
• When you perform an 0
operation where one
operand is an integer
>>> print 99 / 100.0
and the other operand0.99
is a floating point the>>> print 99.0 / 100
result is a floating 0.99
point >>> print 1 + 2 * 3 / 4.0
• The integer is -2.5
converted to a floating>>>
point before the
operation
What does “Type” Mean?
In Python variables,
literals, and constants
have a “type”
Python knows the >>> ddd = 1 + 4
difference between >>>an print ddd
integer number and a5
string >>> eee = 'hello ' + 'th
For example “+” means >>> print eee
hello
“addition” if something is there
a number and
“concatenate” if
something is a string concatenate = put together
>>> eee = 'hello ' +
'there'
Type Matters >>> eee = eee + 1
Traceback (most recent
Python knows what “type” call last):
File "<stdin>", line
everything is 1, in <module>
Some operations are TypeError: cannot
concatenate 'str' and
prohibited 'int' objects
You cannot “add 1” to a >>> type(eee)
<type 'str'>
string >>> type('hello')
We can ask Python what <type 'str'>
type something is by >>> type(1)
<type 'int'>
using the type() function. >>>
Several Types of Numbers
>>> xx = 1
• Numbers have two main types >>> type (xx)
• Integers are whole numbers: - <type 'int'>
14, -2, 0, 1, 100, 401233 >>> temp = 98.6
• Floating Point Numbers have >>> type(temp)
decimal parts: -2.5 , 0.0, 98.6, <type 'float'>
14.0 >>> type(1)
• There are other number types <type 'int'>
- they are variations on float >>> type(1.0)
and integer <type 'float'>
>>>
Type Conversions
>>> print float(99) / 100
0.99
• When you put an
>>> i = 42
integer and floating
>>> type(i)
point in an expression
<type 'int'>
the integer is implicitly
>>> f = float(i)
converted to a float
>>> print f
• You can control42.0
this
with the built in>>> type(f)
<type 'float'>
functions int() and
float() >>> print 1 + 2 * float(3) / 4
-2.5
>>>
>>> type(sval)
<type 'str'>
String >>> print sval + 1
Traceback (most recent
Conversions call last):
File "<stdin>", line
1, in <module>
• You can also use TypeError: cannot
int() and float() to concatenate 'str' and
convert between 'int'
>>> ival = int(sval)
strings and integers >>> type(ival)
• You will get an error <type 'int'>
if the string does not >>> print ival + 1
124
contain numeric >>> nsv = 'hello bob'
characters >>> niv = int(nsv)
Traceback (most recent
call last):
File "<stdin>", line
1, in <module>
ValueError: invalid
User Input
• We can instruct
Python to pause and
read data from the
user using the
raw_input function
• The raw_input nam = raw_input(‘Who are you?
print 'Welcome', nam
function returns a
string
# All done
print bigword, bigcount
String Operations
http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print x1q3p9afd print c
hours = 35.0
What is rate = 12.50
this code pay = hours * rate
doing? print pay
Exercise
• Integer Division
• Conversion between types
• User input
• Comments (#)
n = 5
Repeated Steps
No Yes
Program:
n > 0 Output:
? n = 5
5
while n > 0 :
4
print n
print n n = n – 1
3
2
print 'Blastoff!'
1
print n
Blastoff!
n = n -1 0
No
n > 0
Yes
An Infinite Loop
?
print
'Lather' n = 5
print
while n > 0 :
'Rinse' print 'Lather’
print 'Rinse'
print print 'Dry off!'
'Dry
off!'
What is wrong with this loop?
n = 0
No
n > 0
Yes
Another Loop
?
print
'Lather' n = 0
print while n > 0 :
'Rinse'
print 'Lather’
print 'Rinse'
print
'Dry
print 'Dry off!'
off!' What does this loop do?
Breaking Out of a Loop
The break statement ends the current loop and jumps
to the statement immediately following the loop
It is like a loop test that can happen anywhere in the
body of the loop
while True: > hello there
line = raw_input('> hello
') there
if line == 'done' : > finished
break finished
> done
print line Done!
print 'Done!'
Breaking Out of a Loop
The break statement ends the current loop and jumps
to the statement immediately following the loop
It is like a loop test that can happen anywhere in the
body of the loop
while True:
line = raw_input('> ') > hello there
if line == 'done' : hello there
> finished
break Finished
print line > done
print 'Done!' Done!
while True: No Yes
line = raw_input('> ') True
if line == 'done' : ?
break
print line ....
print 'Done!'
break
...
print
://en.wikipedia.org/wiki/Transporter_(Star_Trek)
'Done'
Finishing an Iteration with continue
The continue statement ends the current iteration and
jumps to the top of the loop and starts the next
iteration
while True:
line = raw_input('> ')
> hello there
if line[0] == '#' hello
: there
continue > # don't print thi
if line == 'done' > print this!
: break print this!
print line > done
print 'Done!' Done!
Finishing an Iteration with continue
The continue statement ends the current iteration and
jumps to the top of the loop and starts the next
iteration
while True:
line = raw_input('> ') > hello there
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print line > done
print 'Done!' Done!
No
True Yes
?
while True:
line = raw_input('> ’) ....
if line[0] == '#' :
continue
if line == 'done' : continu
break e
print line
print 'Done!'
...
print
'Done'
Indefinite Loops
While loops are called "indefinite loops" because
they keep going until a logical condition becomes
False
The loops we have seen so far are pretty easy to
examine to see if they will terminate or if they will
be "infinite loops"
Sometimes it is a little harder to be sure if a loop
will terminate
Definite Loops
Quite often we have a list of items of the lines in a
file - effectively a finite set of things
We can write a loop to run the loop once for each of
the items in a set using the Python for construct
These loops are called "definite loops" because they
execute an exact number of times
We say that "definite loops iterate through the
members of a set"
A Simple Definite Loop
5
4
or i in [5, 4, 3, 2, 3 1] :
print i 2
rint 'Blastoff!' 1
Blastoff!
A Definite Loop with Strings
ends = ['Joseph', 'Glenn', 'Sally']
friend in friends :
print 'Happy New Year:', friend
nt 'Done!'
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
No A Simple Definite Loop
Yes
Done Move i 5
? ahead 4
3
for i in [5, 4, 3, 2, 2 1] :
1
print i print i Blastoff!
print 'Blastoff!'
print
'Blast
off!' Definite loops (for loops) have explicit
iteration variables that change each time
through a loop. These iteration variables
move through the sequence or set.
Looking at In...
The iteration variable
“iterates” though the
sequence (ordered Five-element sequence
Iteration variable
set)
The block (body) of
code is executed
once for each valuefor i in [5, 4, 3, 2, 1] :
in the sequence print i
The iteration variable
moves through all of
the values in the
sequence
No
Yes
Done Move i
? ahead
• The iteration variable
“iterates” though the sequence
print i (ordered set)
for i in [5, 4, 3, 2, 1]
: print i
i = 5
No
print i
Yes
Done Move i i = 4
? ahead
print i
print i
i = 3
print i
i = 2
for i in [5, 4, 3, 2, 1] :
print i print i
i = 1
print i
Definite Loops
Quite often we have a list of items of the lines
in a file - effectively a finite set of things
We can write a loop to run the loop once for
each of the items in a set using the Python for
construct
These loops are called "definite loops"
because they execute an exact number of times
We say that "definite loops iterate through the
members of a set"
Making “smart” loops
$ python basicloop.
Before
'Before' 9
41 15] :
hing in [9, 41, 12, 3, 74,
rint thing 12
'After' 3
74
15
After
Counting in a Loop
zork = 0 $ python countloop.p
print 'Before', zork Before 0
for thing in [9, 41, 12, 1 9
3, 74, 15] : 2 41
zork = zork + 1 3 12
print zork, thing 4 3
print 'After', zork 5 74
6 15
After 6
nt 'Before’
value in [9, 41, 12, 3, 74,$ 15]
python
: search1.py
if value > 20: Before
print 'Large number',value
Large number 41
nt 'After'
Large number 74
After
Hello.java
1 System.out.print("Hello world! ")
2 System.out.print("This will all be")
3 System.out.println(" on the same line.")
4
hello2.py
1 import sys
2
3 sys.stdout.write("Hello world! "),
4 print "This will all be",
5 print " on the same line."
>>> Nested loops
In Python, a lot of the time we
can do nested loops in a much 5
more straightforward way using 44
string multiplication. 333
2222
11111
Nested.java
nested1.py
1 for (int i = 1; i <= 5; i++) {
2 for (int j = 1; j <= (5 - 1 for i in range(5,0,-1):
3 i); j++) { 2 print " " * (i-1)
4 System.out.print(" "); 3 + str(i)*(6-i)
5 }
6 for (int k = 1; k <= i; k+
7 +) { nested2.py
8 System.out.print(i);
9 1 import sys
}
2 for i in range(5,0,-
System.out.println();
3 1):
}
4 sys.stdout.write("
5 " * (i-1))
sys.stdout.write(str(i)*(6-
>>> Mirror
// Marty Stepp, CSE 142, Autumn 2007
// This program prints an ASCII text figure that
// looks like a mirror.
// This version uses a class constant to make the figure resizable.
public class Mirror2 {
scott @ yossarian ~ $ python public static final int SIZE = 4; // constant to change the figure size
mirror.py
#================#
line();
topHalf();
bottomHalf();
line();
| <><> | }
| <>........<> |
// pipe
System.out.print("|");
|<>............<>| // spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
|<>............<>| }
// <>
| <>........<> | System.out.print("<>");
// dots .
| <>....<> | for (int j = 1; j <= 4 * line - 4; j++) {
}
System.out.print(".");
| <><> | // <>
#================#
System.out.print("<>");
// spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
}
// pipe
System.out.println("|");
}
}
// spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
}
// <>
System.out.print("<>");
// dots .
for (int j = 1; j <= 4 * line - 4; j++) {
System.out.print(".");
}
// <>
System.out.print("<>");
// spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
>>> Parameters
Parameters are easy in
Python once you know Java's.
Simply remove all types
from the method header and
do the normal conversion.
PrintSum.java
1 public static void printSum(int x, int y)
2 {
3 System.out.println(x + y);
4 }
print_sum.py
1 def print_sum(x, y):
2 print(str(x + y))
3
4 print_sum(2, 3)
>>> Parameters Example
*************
*******
***********************************
**********
* *
**********
*****
* *
* *
*****
>>> Example Solution
def draw_line(num):
print "*" * num
print_range.py
1 def print_range(start=1, end=1, interval=1, sep="
2 "):
3 for i in range(start, end, interval):
4 print str(i) + sep,
5 print end
6
7 print range(0,7)
print_range(1,7,1,“ ")
>>> Keywords
When calling a function with a number of
parameters with defaults you can modify particular
parameters with a keyword so that you do not need
to specify all preceding parameters.
print_range.py
1 def print_range(start=1,end=1,interval=1,sep=" "):
2 for i in range(start,end,interval):
3 print str(i) + sep,
4 print end
5
6 print range(0,7)
7 print_range(1,7,1,“ ")
8
9 print_range(end=7,sep=“ ")
>>> str1 = "Hello”
>>> str2 = 'there'
>>> bob = str1 +
String Data Type str2
>>> print bob
A string is a sequence of Hellothere
characters >>> str3 = '123'
A string literal uses >>> str3 = str3 + 1
quotes 'Hello' or “Hello” Traceback (most
recent call last):
For strings, + means
File "<stdin>", line
“concatenate” 1, in
When a string contains <module>TypeError:
numbers, it is still a string cannot concatenate
We can convert numbers 'str' and 'int'
objects
in a string into a number >>> x = int(str3) +
using int() 1
>>> print x
raw_input('Enter:')
Enter:Chuck
Reading and >>> print name
Chuck
Converting >>> apple =
• We prefer to read
raw_input('Enter:')
data in using strings Enter:100
and then parse and >>> x = apple – 10
convert the data as Traceback (most
we need recent call last):
• This gives us more File "<stdin>", line
control over error 1, in
situations and/or bad <module>TypeError:
user input unsupported operand
• Raw input numbers type(s) for -: 'str'
must be converted and 'int'
from strings >>> x = int(apple) –
10
>>> print x
Looking Inside Strings
'banana'
len() 6
(a string)
functi (a number)
on
def
len(inp):
'banana' blah 6
(a string) blah (a number)
for x in
y:
blah
blah
Looping Through Strings
• Using a while
statement and an
iteration variable,fruit
and = 'banana' 0 b
the len function, index
we = 0
while
can construct a loop index < 1
len(fruit) a:
2 n
to look at each of the letter = fruit[index]
letters in a string 3 a
print index, letter
individually index = index + 1 4 n
5 a
Looping Through Strings
• A definite loop
fruit = 'banana'
using a for for letter in fruit :
statement is much print letter b
more elegant a
• The iteration
index = 0 n
variable is while index < len(fruit) :
completely taken
a
letter = fruit[index]
care of by the for print letter n
index = index + 1
loop a
Looping and Counting
print
letter
Slicing Strings
String Concatenation
>>> a = 'Hello'
• When the +
>>> b = a + 'There'
operator is>>> print b
applied to HelloThere
strings, it >>> c = a + ' ' + 'Th
means >>> print c
Hello There
"concatenatio
n" >>>
Using in as an Operator
>>> fruit = 'banana’
• The in keyword can >>> 'n' in fruit
also be used to check True
to see if one string is >>> 'm' in fruit
"in" another string False
• The in expression is a >>> 'nan' in fruit
logical expression True
and returns True or >>> if 'a' in fruit :
False and can be used ... print 'Found it!’
in an if statement
...
Found it!
>>>
String Comparison
if word == 'banana':
print 'All right, bananas.'
http://docs.python.org/lib/string-methods.html
Searching a
String
• We use the find() b a n a n a
function to search for a
0 1 2 3 4 5
substring within
another string
>>> fruit = 'banana'
• find() finds the first
>>> pos = fruit.find('na
occurance of the >>> print pos
substring 2
• If the substring is not >>> aa = fruit.find('z')
found, find() returns -1 >>> print aa
• Remember that string -1
position starts at zero
Making everything UPPER CASE
• Sometimes we want to
>>> greet = ' Hello Bob
take a string and >>> greet.lstrip()
remove whitespace at'Hello Bob '
the beginning and/or >>> greet.rstrip()
end ' Hello Bob'
• lstrip() and rstrip() to >>> greet.strip()
'Hello Bob'
the left and right only>>>
• strip() Removes both
begin and ending
whitespace
Prefixes
Java
1 DrawingPanel panel = new
2 DrawingPanel(300, 200);
3 Graphics g = panel.getGraphics();
4 panel.setBackground(Color.YELLOW);
Python
1 panel = DrawingPanel(300, 200)
2 g = panel.get_graphics()
3 g["bg"] = "yellow"
4
>>> Graphics
• What about...?
• g.setColor()
• g.fillRect(), g.fillOval()
Python
1 from drawingpanel import *
2 panel = DrawingPanel(100,100)
3 g = panel.get_graphics()
4 g.create_polygon(50, 50, 100, 0, 100, 100,
5 fill="green")
panel.mainloop()
>>> Graphics Example 2
string methods
s = "wow" s.capitalize() => "Wow"
s = "wow" s.endswith("w") => True
s = "wow" s.find("o") => 1
s = "wow" s.islower() => True
s = "wOw" s.isupper() => False
s = "wOw" s.lower() => "wow"
s = "hmmm" s.startswith("hm") => True
s = " ack " s.strip() => "ack"
s = "wOw" s.swapcase() => "WoW"
s = "wow" s.upper() => "WOW"
>>> strings as sequences
Like arrays in Java, sequence operations
strings have zero-based
indexes, and we can s[<index>] s[3] => "c"
access parts of them s[-1] =>
with square brackets "g"
instead of using Java's s[<start>:<end>] s[4:] => "king"
substring() and charAt() s[3:5] =>
methods. "ck"
s[-3:] =>
Lets look at things we "ing"
can do if we have the len(s) len(s) => 8
string Indexing
from the front
0 1 2 3 4 5 6 7
s = "shocking"
"shocking"
from the back
-8 -7 -6 -5 -4 -3 -2 -
example: s[2:-4] => "oc"
>>> return
Returns in python are straightforward. Simply "return <value>"
instead of "return <value>;" and forget about the types.
degrees.py
1 def f_to_c(degreesF):
2 degreesC = 5.0 / 9.0 * (degreesF – 32)
3 return degreesC
4
5 #main
6 temp = f_to_c(68)
7 print ("Temperature is: " + str(temp))
slope.py
1 def slope(x1, y1, x2, y2):
2 return (y2 - y1) / (x2 - x1)
3
4 #main
5 slope = slope(0, 0, 5, 5)
6 print ("Slope is: " + str(slope))
7
>>> math in python
Most of the math functions
are the same in python. Here math functions
is a list with a short
description. ceil(x)
fabs(x)
In order to use them, we floor(x)
have to exp(x)
import math
log(x,[base])
The constants are the same log10(x)
as Java, except lower case. pow(x, y)
sqrt(x)
math.pi = 3.1415926...
cos(x)
math.e = 2.7182818..
hypot(x, y)
sin(x)
Random comes from its own tan(x)
class:
degrees(x)
import random
random.random() radians(x)
>>> input() vs. raw_input()
There are two ways of getting The second way is to use
input. The first is input(). It raw_input() which returns The
takes in input until enter is hit raw_input()` function doesn't
and then tries to interpret it evaluate, it will just read
into python. However, this way whatever you enter.
only
>>> xworks well for ")
= input("yes? numbers.
yes? y
inputs.py
Traceback (most recent call last): 1 name = input("what is your
File "<stdin>", line 1, in 2 name?")
<module> 3 print(name)
File "<string>", line 1, in 4 name = raw_input("what is your
<module> 5 name ?")
NameError: name 'y' is not defined 6
>>> x = input("yes? ") 7
yes? 2 8
>>> print x 9
2 10
>>> x = input("num? ")
num? 2.0
>>> print x
2.0
>>> Overview
* boolean
* while
* random
* tuples
>>> boolean
Just like Java, there are
>>> True
boolean values. These values
True
are True and False.
True >>> False
False
False
>>> 2==3
False
< >>> "this"=="this"
> True
<= >>> 2==3 and 4==4
>= False
== >>> x = not 1 == 2
!= >>> x
or True
and
not
>>> while
The while loop translates sentinel.py
nicely from Java to 1 n = 10
Python. 2 # initialize sum and counter
3 sum = 0
4 i = 1
5 while i <= n:
6 sum = sum + i
7 i = i+1 # update counter
8 # print the sum
9 print("The sum is", sum)
Sentinel.java
1 Scanner console = new Scanner(System.in);
2 int sum = 0;
3 System.out.print("Enter a number (-1 to
4 quit): ");
5 int number = console.nextInt();
6
7 while (number != -1) {
8 sum = sum + number;
9 System.out.print("Enter a number (-1
10 to quit): ");
number = console.nextInt();
}
random.randint(a,b)
returns an int between a and b inclusive
random.choice(seq)
returns a random element of the sequence
>>> tuples as points
Python does not have Point Objects. Instead we use tuples.
A tuple is able to hold multiple values. These values can
correspond to the x and y coordinates of a point.
>>> p = (3, 5)
>>> p
(3, 5)
Creates a tuple where the first value is 3 and the second
value is 5. This can represent a 2D point where the “x”
value is 3 and the “y” value is 5.
>>> retrieving tuple values
If we wish to use the values in a
tuple, we can assign each value to a
vairable.
>>> p = (3, 5)
>>> p
(3, 5)
>>> (x, y) = p
>>> x
3
>>> y
5
Example:
def equal(p1, p2):
(x1, y1) = p1
(x2, y2) = p2
return x1==x2 and y1==y2