Download Fun with Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Fun with Python
Learning a new language in several easy steps.
What does a computer language have to do?
Data Representation, storage, and Recall: There has to be a way to set variables
and to refer to the values they contain. Python has the regular set of things like
characters, integers, floating point numbers and strings. It doesn’t have a
declaration statement (no int i; like java) nor does it have implicit values like
FORTRAN. It doesn’t have arrays, as such. It has lists, tuples and dictionaries.
It also uses garbage collection to remove data space that is no longer used –
which can have some interesting effects on performance.
i= 1
defines an integer i as one.
[0,1,2,3] is a list of 4 integers
[“CA”, 1., 1.1, 3.] is a list with a string and three floating point numbers
(“CA”, 1., 1.1, 3.) is the same data as a tuple
[(“CA”,1., 1.1, 3.), (“CA”, 4.8, 1.1,3.)] is a list of tuples
{ ‘atom1’:”CA”, ‘atom2’:”CB”} is a dictionary
“ABC” and ‘XYZ’ are strings
Lists, tuples and dictionaries can be indexed and assigned.
a = [1,2,3] means a is a list of numbers
a[1] is 2 because indexing starts with 0
a[1:] is [2,3]
Conditional Operations There has to be a way to check if a logical condition is
true or false and use that result to control the operation of the program.
if x < 0 :
do something
elif x == 1:
do something else
else:
do yet another thing
Python has continue, pass and break statements but not GOTO’s
Basic Numerical and Logical Operations
+-*/ // % ** >= == <= > < != and more.
Iterative Control Structures
Python has for and while loops
for a in iterable : # an iterable is something like a list that can be iterated on
print a
x=0
while x < 100 :
x += 1
Input and Output:
print x prints the value of x
print “x equals “ + x prints “x equals “ followed by the value of x
input requires knowing how to open a file (in general) but can work from a
standard input (i.e. the terminal)
for line in sys.stdin :
reads every line in from the terminal
line = readline (sys.stdin) reads a line from the terminal
Libraries:
import sys imports the system library
from sys import stdin only imports stdin
Methods :
Objects -how to extend the things the language knows about