This article mainly introduces the Python simple Getting Started Tutorial. it analyzes in detail the basic concepts and syntax basics of Python, and helps beginners of Python better understand the basic syntax and usage skills of Python, for more information about how to get started with Python, see the example in this article. Share it with you for your reference. The details are as follows:
I. Basic concepts
1. number
There are four types of numbers in Python: integer, long integer, floating point, and plural.
(1) 2 is an integer example.
(2) a long integer is a larger integer.
(2) 3.23 and 52.3E-4 are floating point numbers. E indicates the power of 10. Here, 52.3E-4 indicates 52.3*10-4.
(4) (-5 + 4j) and (2.3-4.4.7) are complex numbers.
2. string
(1) use single quotes (')
(2) use double quotation marks (")
(3) use three quotation marks (''' or """)
You can use three quotation marks to indicate a multi-line string. You can use single quotes and double quotes freely in three 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 characters
(5) natural string
A natural string is specified by adding the prefix r or R to the string. For example, r "Newlines are indicated by \ n ".
3. logical and physical rows
A physical row uses more than one logical row. a semicolon (;) is required to indicate this usage. A physical row has only one logical row without a semicolon.
II. Control flow
1. if
The block does not contain braces. the condition is followed by a semicolon, which corresponds to elif and else.
if guess == number: print 'Congratulations, you guessed it.' # New block starts hereelif guess < number: print 'No, it is a little higher than that' # Another blockelse: print 'No, it is a little lower than that'
2. while
Use a semicolon to match 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.
Use a semicolon with else
for i in range(1, 5): print ielse: print 'The for loop is over'
4. break and continue
Same as C language
III. Functions
1. definition and call
def sayHello(): print 'Hello World!' # block belonging to the functionsayHello() # call the function
2. function parameters
Class C language
def printMax(a, b): if a > b: print a, 'is maximum' else: print b, 'is maximum'
3. local variables
Add global as a global variable
4. default parameter values
def say(message, times = 1): print message * times
5. key parameters
If a function has many parameters but only wants to specify a part of them, you can assign values to these parameters by name. this is called a key parameter. use the name (keyword) instead of specifying the real parameter for the function. This method has two advantages: 1. it is easier to use functions because you don't have to worry about the order of parameters. 2. if other parameters have default values, you can only assign values to the desired parameters.
def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', cfunc(3, 7)func(25, c=24)func(c=50, a=100)
6. return
IV. Modules
1. use modules
import sysprint 'The command line arguments are:'for i in sys.argv: print i
If you want to directly input the argv variable to the program (avoid using sys. every time you use it), you can use the from sys import argv statement.
2. dir () function
You can use the built-in dir function to list the identifier defined by the module. Identifiers include 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 linefor item in shoplist: print item,print '\nI also have to buy rice.'shoplist.append('rice')print 'My shopping list is now', shoplistprint 'I will sort my list now'shoplist.sort()print 'Sorted shopping list is', shoplistprint 'The first item I will buy is', shoplist[0]olditem = shoplist[0]del shoplist[0]print 'I bought the', olditemprint 'My shopping list is now', shoplist
2. tuples
Tuples are similar to lists, except that tuples and strings are immutable, that is, you cannot modify them.
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_zooprint '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 = 22name = 'Swaroop'print '%s is %d years old' % (name, age)print 'Why is %s playing with that python?' % name
3. dictionary
Similar to hash
ab = { 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' }print "Swaroop's address is %s" % ab['Swaroop']# Adding a key/value pairab['Guido'] = 'guido@python.org'# Deleting a key/value pairdel ab['Spammer']print '\nThere are %d contacts in the address-book\n' % len(ab)for name, address in ab.items(): 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 a sequence are index operators and slice operators.
shoplist = ['apple', 'mango', 'carrot', 'banana']# Indexing or 'Subscription' operationprint '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 listprint '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 stringname = '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, this variable only refers to the object, rather than the object itself! That is to say, the variable name points to the memory of the object stored in your computer. This is called 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', shoplistprint 'mylist is', mylist# notice that both shoplist and mylist both print the same list without# the 'apple' confirming that they point to the same objectprint 'Copy by making a full slice'mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint 'shoplist is', shoplistprint 'mylist is', mylist# notice that now the two lists are different
6. string
Name = 'swaroop '# This is a string objectif name. startswith ('swa'): print 'Yes, the string starts with "Swa" 'If 'A' in name: print 'Yes, it contains the string "a" 'if name. find ('war ')! =-1: print 'Yes, it contains the string "war" 'delimiter = '_ * _' mylist = ['Brazil ', 'Russia', 'India ', 'china'] print delimiter. join (mylist) // use delimiter to connect mylist characters
6. object-oriented programming
1. self
The self in Python is equivalent to the self pointer in C ++ and the this reference in Java and C #.
2. create a class
class Person: pass # An empty blockp = Person()print p
3. object methods
class Person: def sayHi(self): print 'Hello, how are you?'p = Person()p.sayHi()
4. initialization
class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.namep = Person('Swaroop')p.sayHi()
5. Methods of classes and objects
Class variables are shared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances.
The object variables are owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. in different instances of the same class, although the object variables have the same name, however, they are unrelated.
class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1
Population belongs to the Person class, so it is a variable of the class. The name variable belongs to the object (which uses self to assign values). Therefore, it is the variable of the object.
6. Inheritance
class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = nameclass Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary
VII. input and output
1. file
f = file('poem.txt', 'w') # open for 'w'ritingf.write(poem) # write text to filef.close() # close the filef = file('poem.txt')# if no mode is specified, 'r'ead mode is assumed by defaultwhile True: line = f.readline() if len(line) == 0: # Zero length indicates EOF break print line, # Notice comma to avoid automatic newline added by Pythonf.close() # close the file
2. storage
Durability
import cPickle as p#import pickle as pshoplistfile = 'shoplist.data'# the name of the file where we will store the objectshoplist = ['apple', 'mango', 'carrot']# Write to the filef = file(shoplistfile, 'w')p.dump(shoplist, f) # dump the object to a filef.close()del shoplist # remove the shoplist# Read back from the storagef = file(shoplistfile)storedlist = p.load(f)print storedlist
3. enter
Input string nID = raw_input ("Input your id plz ")
Input integer nAge = int (raw_input ("input your age plz: \ n "))
Input float fWeight = float (raw_input ("input your weight \ n "))
Input hexadecimal 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)
8. Exceptions
1. try... try T
import systry: s = raw_input('Enter something --> ')except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() # exit the programexcept: print '\nSome error/exception occurred.' # here, we are not exiting the programprint 'Done'
2. exception
An exception is thrown using the raise statement. You must also specify the error/exception name and the exception object triggered with the exception. The errors or exceptions you can cause should be a direct or indirect export class of the Error or Exception class.
class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleastraise ShortInputException(len(s), 3)
3. try... finnally
import timetry: f = file('poem.txt') while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print line,finally: f.close() print 'Cleaning up...closed the file'
9. Python Standard Library
1. sys database
The sys module includes the system functions. Sys. argv list, which contains command line parameters.
2. OS database
The OS. name string indicates the platform you are using. For example, for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix '.
The OS. getcwd () function obtains the current working directory, that is, the directory path of the current Python script.
The OS. getenv () and OS. putenv () functions are used to read and set environment variables respectively.
OS. listdir () returns all files and directory names in the specified directory.
The OS. remove () function is used to delete an object.
The OS. system () function is used to run shell commands.
The OS. linesep string specifies the row Terminator used by the current platform. For example, in Windows, '\ r \ n' is used, in Linux,' \ n' is used, and in Mac, '\ r' is used '.
The OS. path. split () function returns the directory name and file name of a path.
>>> OS. path. split ('/home/swaroop/byte/code/poem.txt ')
('/Home/swaroop/byte/code', 'poem.txt ')
The OS. path. isfile () and OS. path. isdir () functions verify whether the given path is a file or a directory. Similarly, the OS. path. existe () function is used to check whether the given path actually exists.
I hope this article will help you with Python programming.