Sie sind auf Seite 1von 4

Running Python:

To start interactive programming run


1. $python---------------unix/Linux
2. $python%--------------Unix/Linux
3. >python---------------Windows/Dos
Command options:
1. -d------------provide debug output
2. -O------------generate optimized bytecode (resulting in .pyo files)
3. -S------------do not run site to look for python paths on startup
4. -v------------ verbose output
5. -X------------ disable class based built in exceptions (just use strings)
6. -c cmd -------- run python script sent in as cmd string
7. file ---------- run pythin script from given file
Note: python scripts ends with .py extension
First python program:
1. >>>print "hello, Python!";
eg2:
>>>print ("hello world");
Note: in python the statements whould always end with semicolon ;
Note: a python script should always run as "python file_name"
Python Identifiers:
A python identifiers are used to identify a variable, function, class, module or
other object
An identifier starts with a litter A to Z or a to z or an underscore followed by
zero or more letters, underscores and digits(0 to 9).
Note: python doesn't allow punctuation characters such as @, $ and % within iden
tifiers
rules:
class name starts with a uppercase letter and all other identifiers with a lower
case letter
starting an identifier witha single leading underscore indicates by convention t
hat the identifier is meant to be private
starting an identifier with two leading underscores indicates a strongly private
identifier
if the identifier also ends with two trailing underscores, the identifier is a l
anguage defined spl name
Lines of indentation"
in python blocks of code is denoted by lines of indentation (three spaces)
eg:
if True:
print "True"
else:
print "False"
Multi-line statements:

In python the line continuation is denoted as (\)


eg:
total = item_one + \
item_two + \
item_three
statements contained within [], {}, or () do not need line continuation characte
r (\)
eg:
days = ['monday','tuesday','wednesday','thrusday',
'friday','saturday','sunday']
Quotation in python:
python accepts single (') (") (""") quotes to denote string literals, as long as
same type of
quote starts and ends the string
triple quotes can be used to span the string across multiple lines.
eg:
word = 'love'
sentence = "hard work is a gift"
paragraph = """This is a paragraph. It is
made up of multiple lines"""
Waiting for the user:
raw_input("\n\nPress the enter key to exit")
\n\n is used to create two new lines
Multiple statements on a single line:
semicolon ; allows multiple statements on single line given that neither stateme
nts starts a new line of code
eg:
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple statement groups as suites
Header line beginthe statement with a keyword and terminate with colon(:)
Accessing command line arguments:
python provides a getopt module that helps you aprse command line options and ar
guments
python sys module provides access to any command line arguments via the sys.argv
. Thie serves two purpose:
1. sys.argv is the list of cmd line arguments
2. len(sys.argv) is the number of command line arguments
Parsing command line arguements:
python provides a getopt module that helps programmers to parse cmd-line options
and arguments.
getopt.getopt method:
this method parses cmd line options and parameter list.
syntax = getopt,getopt(args, options[, long_options])

args: argument list to be parsed


options:

Variables:
variablea are reserved memory space to store values.
based on the data type of the variable, the interpreter allocate memory and deci
des what can be stored in the reserved memory.
python variables do not have to be explicitly declared to reserve memory space.
The declaration happens automatically when you assign a value
to a variable.
The equal sign (=) is used to assign values to variables.
eg:
counter = 100
miles = 1000.02
name = "Ranjit"
print counter
print miles
print name
Data Types:
Python has 5 data types:
Numbers
string
list
tuple
dictionary
Numbers: store numeric value, they are immutable data typeswhich means that chan
ging the
value of a number data type results in a newly allocated object
number objects are created when you assign a value to them
eg:
var1 = 1
var2 = 10
to delete a number object use del stmt
del var1[,var2[,var3[....,varN]]]
also
del var
del var_a, var_b
python supports 4 different types of numerical values
1.
2.
3.
4.

int(signed integers)
long(long integers)
float(floating point real values)
complex(complex numbers)

Python strings:
strings = set of contiguous characters btw quotation marks.
eg:
str = 'Hello World!'
print str = prints 'Hello World!'
print str[0] = prints first character of the string = H
print str[2:5] = prints chars starting from 3rd to 5th = llo
print str[2:] = prints chars starting from 3rd char = llo World!
print str * 2 = prints string two times = Hello World!Hello World!
print str + "TEST" = prints concatenated string Hello World!TEST
python lists:
list contains items seperated by commas and enclosed within []
items in lists can be of different data types
eg:
list = ['abcd', 786, 2.43, 'Kumar', 10.2]
Python tuples:
Is same like a list but the tuples are enclosed in paranthesis ()
Lists size can be changed while tuples can not be updated.
eg:
tuple = ('abcd', 786, 10.2, 'Kumar')
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
python dictionaries:
A dictionary key can be almost any python type, but are usually
numbers or strings values.
Dictionaries are enclosed in {}, values can be assigned and accessed using []
eg:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

Das könnte Ihnen auch gefallen