This article is an example of a concise tutorial on getting started with Python. Shared for your reference. Specifically as follows:
I. Basic concepts
1. Number
There are 4 types of numbers in Python - integers, long integers, floating point numbers and complex numbers.
(1) 2 is an example of an integer.
(2) Long integers are nothing more than larger integers.
(2) 3.23 and 52.3E-4 are examples of floating-point numbers. the E notation denotes a power of 10. Here, 52.3E-4 represents 52.3 * 10-4.
(4) (-5 + 4j) and (2.3 - 4.6j) are examples of complex numbers.
2. String
(1) Use of single quotation marks (')
(2) Use of double quotation marks (")
(3) Use of triple quotation marks (''' or """)
With triple quotes, you can indicate a multi-line string. You are free to use single and double quotes in triple quotes. For example:
'''This is a multi-line string. This is the first line. This is the second line. "What's your name?," I asked. He said "Bond, James Bond." '''
(4) Escape character
(5) Natural strings
Natural strings are specified by prefixing the string with r or R. For example, r "Newlines are indicated by \n".
3. Logical and physical rows
The use of more than one logical line in a physical line requires the use of a semicolon (;) to specifically identify this usage. A physical line with only one logical line can be used without a semicolon.
II. Control flow
1、if
No curly brackets are used in the block, and a semicolon is used after the condition, corresponding to elif and else
if guess == number: print 'Congratulations, you guessed it.' # New block starts here elif guess < number: print 'No, it is a little higher than that' # Another block else: print 'No, it is a little lower than that'
2、while
Use a semicolon, which can be paired with else
while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that' else: print 'No, it is a little lower than that' else: print 'The while loop is over.' # Do anything else you want to do here
3、for
Use a semicolon with else
for i in range(1, 5): print i else: print 'The for loop is over'
4. break and continue
Same as C
III. Functions
1. Definition and invocation
def sayHello(): print 'Hello World!' # block belonging to the function sayHello() # call the function
2、Function Formal Reference
C-like language
def printMax(a, b): if a > b: print a, 'is maximum' else: print b, 'is maximum'
3. Local variables
Add global to declare a global variable.
4. Default parameter values
def say(message, times = 1): print message * times
5. Key parameters
If a function has many arguments and you want to specify only some of them, you can assign values to these arguments by naming them - this is called a key argument - using the name (keyword) rather than the position to assign real parameters to the function. This has two advantages - one, it makes it easier to use the function because you don't have to worry about the order of the parameters. Two, assuming that the other parameters have default values, we can assign values to only those parameters we want.
def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', c func(3, 7) func(25, c=24) func(c=50, a=100)
6、return
IV. Modules
1. Use of modules
import sys print 'The command line arguments are:' for i in : print i
If you want to enter the argv variable directly into the program (and avoid typing sys. every time you use it), you can use the from sys import argv statement
2. dir () function
The built-in dir function can be used to list module-defined identifiers. The identifiers are functions, classes and variables.
V. Data structure
1. List
shoplist = ['apple', 'mango', 'carrot', 'banana'] print 'I have', len(shoplist),'items to purchase.' print 'These items are:', # Notice the comma at end of the line for item in shoplist: print item, print '\nI also have to buy rice.' ('rice') print 'My shopping list is now', shoplist print 'I will sort my list now' () print 'Sorted shopping list is', shoplist print 'The first item I will buy is', shoplist[0] olditem = shoplist[0] del shoplist[0] print 'I bought the', olditem print 'My shopping list is now', shoplist
2. Tuple
Tuples are very similar to lists, except that tuples are immutable like strings, i.e. you can't modify a tuple.
zoo = ('wolf', 'elephant', 'penguin') print 'Number of animals in the zoo is', len(zoo) new_zoo = ('monkey', 'dolphin', zoo) print 'Number of animals in the new zoo is', len(new_zoo) print 'All animals in new zoo are', new_zoo print 'Animals brought from old zoo are', new_zoo[2] print 'Last animal brought from old zoo is', new_zoo[2][2]
Like a tree.
Tuples and Printing
age = 22 name = 'Swaroop' print '%s is %d years old' % (name, age) print 'Why is %s playing with that python?' % name
3. Dictionary
hash-like (computing)
ab = { 'Swaroop' : 'swaroopch@', 'Larry' : 'larry@', 'Matsumoto' : 'matz@', 'Spammer' : 'spammer@' } print "Swaroop's address is %s" % ab['Swaroop'] # Adding a key/value pair ab['Guido'] = 'guido@' # Deleting a key/value pair del ab['Spammer'] print '\nThere are %d contacts in the address-book\n' % len(ab) for name, address in (): print 'Contact %s at %s' % (name, address) if 'Guido' in ab: # OR ab.has_key('Guido') print "\nGuido's address is %s" % ab['Guido']
4. Sequence
Lists, tuples and strings are all sequences. The two main features of sequences are the index operator and the slice operator.
shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation print 'Item 0 is', shoplist[0] print 'Item 1 is', shoplist[1] print 'Item -1 is', shoplist[-1] print 'Item -2 is', shoplist[-2] # Slicing on a list print 'Item 1 to 3 is', shoplist[1:3] print 'Item 2 to end is', shoplist[2:] print 'Item 1 to -1 is', shoplist[1:-1] print 'Item start to end is', shoplist[:] # Slicing on a string name = 'swaroop' print 'characters 1 to 3 is', name[1:3] print 'characters 2 to end is', name[2:] print 'characters 1 to -1 is', name[1:-1] print 'characters start to end is', name[:]
5. Reference
When you create an object and assign it a variable, that variable simply refers to that object, not to the object itself! That is, the variable name points to the memory in your computer that stores that object. This is called a name-to-object binding.
print 'Simple Assignment' shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] print 'shoplist is', shoplist print 'mylist is', mylist # notice that both shoplist and mylist both print the same list without # the 'apple' confirming that they point to the same object print 'Copy by making a full slice' mylist = shoplist[:] # make a copy by doing a full slice del mylist[0] # remove first item print 'shoplist is', shoplist print 'mylist is', mylist # notice that now the two lists are different
6. String
name = 'Swaroop' # This is a string object if ('Swa'): print 'Yes, the string starts with "Swa"' if 'a' in name: print 'Yes, it contains the string "a"' if ('war') != -1: print 'Yes, it contains the string "war"' delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print (mylist) // use delimiter to concatenate mylist characters
VI. Object-oriented programming
1、self
Self in Python is equivalent to the self pointer in C++ and the this reference in Java and C#.
2、Create class
class Person: pass # An empty block p = Person() print p
3. Methods of objects
class Person: def sayHi(self): print 'Hello, how are you?' p = Person() ()
4. Initialization
class Person: def __init__(self, name): = name def sayHi(self): print 'Hello, my name is', p = Person('Swaroop') ()
5. Class and object methods
Class variables are shared for use by all objects (instances) of a class. There is only one copy of a class variable, so when an object makes a change to a class variable, that change is reflected on all other instances.
Object's variables are owned by each object/instance of the class. Thus each object has its own copy of this domain, i.e. they are not shared, and in different instances of the same class the variables of an object are unrelated to each other, although they have the same name.
class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' = name print '(Initializing %s)' % # When this person is created, he/she # adds to the population += 1
population belongs to the Person class and is therefore a class variable. the name variable belongs to the object (it is assigned using self) and is therefore an object variable.
6. Succession
class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): = name class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) = salary
VII. Inputs and outputs
1. Documentation
f = file('', 'w') # open for 'w'riting (poem) # write text to file () # close the file f = file('') # if no mode is specified, 'r'ead mode is assumed by default while True: line = () if len(line) == 0: # Zero length indicates EOF break print line, # Notice comma to avoid automatic newline added by Python () # close the file
2. Memory
durability
import cPickle as p #import pickle as p shoplistfile = '' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = file(shoplistfile, 'w') (shoplist, f) # dump the object to a file () del shoplist # remove the shoplist # Read back from the storage f = file(shoplistfile) storedlist = (f) print storedlist
3. Console input
Input string nID = raw_input("Input your id plz")
Input integer nAge = int(raw_input("input your age plz:\n"))
Input Floating Point fWeight = float(raw_input("input your weight\n"))
Input hex data nHex = int(raw_input('input hex value(like 0x20):\n'),16)
Input octal data nOct = int(raw_input('input oct value(like 020):\n'),8)
VIII. Exceptions
1、try..except
import sys try: s = raw_input('Enter something --> ') except EOFError: print '\nWhy did you do an EOF on me?' () # exit the program except: print '\nSome error/exception occurred.' # here, we are not exiting the program print 'Done'
2、Triggering abnormalities
Use the raise statement to raise the exception. You must also specify the name of the error/exception and the exception object that will accompany the exception. The error or exception you can raise should be a direct or indirect descendant of an Error or Exception class, respectively.
class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) = length = atleast raise ShortInputException(len(s), 3)
3、try..finnally
import time try: f = file('') while True: # our usual file-reading idiom line = () if len(line) == 0: break (2) print line, finally: () print 'Cleaning up...closed the file'
IX. Python Standard Library
1. sys library
The sys module contains the corresponding functions of the system list, which contains command line arguments.
2. os library
The string indicates the platform you are using. For example, for Windows it's 'nt' and for Linux/Unix users it's 'posix'.
() function gets the current working directory, which is the path to the directory where the current Python script is working.
The () and () functions are used to read and set environment variables, respectively.
() returns all files and directory names in the specified directory.
() function is used to delete a file.
() function is used to run shell commands.
The string gives the line terminator used by the current platform. For example, Windows uses '\r\n', Linux uses '\n' and Mac uses '\r'.
The () function returns the directory name and filename of a path.
>>> ('/home/swaroop/byte/code/')
('/home/swaroop/byte/code', '')
The () and () functions test whether the given path is a file or a directory, respectively. Similarly, the () function is used to check whether the given path really exists.
I hope that what I have described in this article will help you in your Python programming.