Python learning-Python short tutorial
Preface
This tutorial combines Stanford CS231N and UC Berkerley CS188 Python tutorials.
The tutorial is short, but it is suitable for children's shoes who have learned other languages based on certain programming basics.
Start Python Interpreter
Python can be used in two ways, one is to use the interpreter, similar to Matlab, input a line of code, run a line; the other is to write a document with the py suffix, called a script, then python xxx. run the script in py. Here we use the interpreter.
If Python has been installed, input python in Terminal to start Python:
FloodSurges-MacBook-Pro:~ FloodSurge$ pythonPython 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "help", "copyright", "credits" or "license" for more information.>>>
Here I use Python 2.7.9
Operator
In the Python interpreter, >>> is used to represent a line of code, similar to Matlab (use <)
First, the most basic operators + ,-,*,/:
>>> 1 + 12>>> 2 * 36>>> 2 / 30>>> 2 / 3.10.6451612903225806
Next we will also use common power operations, using **
>>> 2 ** 24>>> 2 ** 38
Data Type
A big difference between Python and other languages is that Python does not need to define data types. The data types are determined based on data conditions.
For example, input 3 is an integer and input 3.1 is a floating point number.
Number
x=3??print type(x) # Prints "
"print x # Prints "3"print x + 1 # Addition; prints "4"print x - 1 # Subtraction; prints "2"print x * 2 # Multiplication; prints "6"print x ** 2 # Exponentiation; prints "9"x += 1print x # Prints "4"
Note that Python does not support x ++ or x-operations.
Boolean
Use True or False
f = Falseprint type(t) # Prints "
"print t and f # Logical AND; prints "False"print t or f # Logical OR; prints "True"print not t # Logical NOT; prints "False"
Note that &, |,! Is not used in Python ,! Or, not
Instead, they use English and, or, not
>>> 1==0False>>> not (1==0)True>>> (2==2) and (2==3)False>>> (2==2) or (2==3)True
String
?hello = 'hello' # String literals can use single quotes?world = "world" # or double quotes; it does not matter.?print hello # Prints "hello"print len(hello) # String length; prints "5"?hw = hello + ' ' + world # String concatenation?print hw # prints "hello world"?hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formatin?print hw12 # prints "hello world 12
There are many ready-made methods to operate strings:
??print s.capitalize() # Capitalize a string; prints "Hello"print s.upper() # Convert a string to uppercase; prints "HELLO"print s.rjust(7) # Right-justify a string, padding with spaces;print s.center(7) # Center a string, padding with spaces; printsprint s.replace('l', '(ell)') # Replace all instances of one substri# prints "he(ell)(ell)o"
>>> 'artificial' + "intelligence"'artificialintelligence'
In fact, both single quotes and double quotes are the same.
>>> a = 'hello'>>> a'hello'>>> b = "hello">>> b'hello'>>> a == bTrue
Then, we can use dir and help to view the corresponding methods of a type.
>>> a = 'hello'>>> dir(a)['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']>>> help(a.find)Help on built-in function find:find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
Press Q to view the help.
List of data structures
>>> fruits = ['apple','orange','pear','banana']>>> fruits[0]'apple'
You can connect to the list through +.
>>> otherFruits = ['kiwi','strawberry']>>> fruits + otherFruits>>> ['apple', 'orange', 'pear', 'banana', 'kiwi', 'strawberry']
Python supports negative index. For example, fruits [-1] is the last of the list.
>>> fruits[-2]'pear'>>> fruits.pop()'banana'>>> fruits['apple', 'orange', 'pear']>>> fruits.append('grapefruit')>>> fruits['apple', 'orange', 'pear', 'grapefruit']>>> fruits[-1] = 'pineapple'>>> fruits['apple', 'orange', 'pear', 'pineapple']
Next we can use: To retrieve multiple data:
>>> fruits[0:2]['apple', 'orange']>>> fruits[:3]['apple', 'orange', 'pear']>>> fruits[2:]['pear', 'pineapple']>>> len(fruits)4
Then, the lists can also be nested:
>>> lstOfLsts = [['a','b','c'],[1,2,3],['one','two','three']]>>> lstOfLsts[1][2]3>>> lstOfLsts[0].pop()'c'>>> lstOfLsts[['a', 'b'],[1, 2, 3],['one', 'two', 'three']]
Loop Loops:
???animals = ['cat', 'dog', 'monkey']?for animal in animals:? print animal# Prints "cat", "dog", "monkey", each on its own line.
To obtain the index value for each element, use the Enumerate enumeration:
animals = ['cat', 'dog', 'monkey']?for idx, animal in enumerate(animals):? print '#%d: %s' % (idx + 1, animal)# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
List Comprehension converts one data to another:
>>> nums = [0,1,2,3,4]>>> squares = []>>> for x in nums:... squares.append(x ** 2)... >>> print squares[0, 1, 4, 9, 16]
You can also write this statement:
>>> nums = [0,1,2,3,4]>>> squares = [x**2 for x in nums]>>> print squares[0, 1, 4, 9, 16]
You can also include the following conditions:
nums = [0, 1, 2, 3, 4]even_squares = [x ** 2 for x in nums if x % 2 == 0] print even_squares # Prints "[0, 4, 16]"
Tuple
Similar to List, but cannot be changed after Initialization
>>> pair = (3,5)>>> pair[0]3>>> x,y = pair>>> x3>>> y5>>> pair[1] = 6TypeError: object does not support item assignment
Set
Set has no order
>>> shapes = ['circle','square','triangle','circle']>>> setOfShapes = set(shapes)>>> setOfShapesset(['circle','square','triangle'])>>> setOfShapes.add('polygon')>>> setOfShapesset(['circle','square','triangle','polygon'])>>> 'circle' in setOfShapesTrue>>> 'rhombus' in setOfShapesFalse>>> favoriteShapes = ['circle','triangle','hexagon']>>> setOfFavoriteShapes = set(favoriteShapes)>>> setOfShapes - setOfFavoriteShapesset(['square','polyon'])>>> setOfShapes & setOfFavoriteShapesset(['circle','triangle'])>>> setOfShapes | setOfFavoriteShapesset(['circle','square','triangle','polygon','hexagon'])
Dictionary
Similar to java Map, a Key corresponds to a Value.
>>> studentIds = {'knuth': 42.0, 'turing': 56.0, 'nash': 92.0 }>>> studentIds['turing']56.0>>> studentIds['nash'] = 'ninety-two'>>> studentIds{'knuth': 42.0, 'turing': 56.0, 'nash': 'ninety-two'}>>> del studentIds['knuth']>>> studentIds{'turing': 56.0, 'nash': 'ninety-two'}>>> studentIds['knuth'] = [42.0,'forty-two']>>> studentIds{'knuth': [42.0, 'forty-two'], 'turing': 56.0, 'nash': 'ninety-two'}>>> studentIds.keys()['knuth', 'turing', 'nash']>>> studentIds.values()[[42.0, 'forty-two'], 56.0, 'ninety-two']>>> studentIds.items()[('knuth',[42.0, 'forty-two']), ('turing',56.0), ('nash','ninety-two')]>>> len(studentIds)3
Write Script
Is to create a new file, and then change the suffix to py. Then enter the code in it, such as foreach. py:
# This is what a comment looks likefruits = ['apples','oranges','pears','bananas']for fruit in fruits: print fruit + ' for sale'fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75}for fruit, price in fruitPrices.items(): if price < 2.00: print '%s cost %f a pound' % (fruit, price) else: print fruit + ' are too expensive!'
Then run terminal in the corresponding path (remember not to run it in the Python Interpreter)
python foreach.pyapples for saleoranges for salepears for salebananas for saleoranges cost 1.500000 a poundpears cost 1.750000 a poundapples are too expensive!
There are two useful map and filter methods:
>>> map(lambda x: x * x, [1,2,3])[1, 4, 9]>>> filter(lambda x: x > 3, [1,2,3,4,5,4,3,2,1])[4, 5, 4]
Note Space
Python has high syntax requirements. for example, if a space is required for the next statement of the for statement, an error may be reported.
>>> for x in nums:... squares.append(x ** 2) File "
", line 2 squares.append(x ** 2) ^IndentationError: expected an indented block>>> for x in nums:... squares.append(x ** 2)
Function
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75}def buyFruit(fruit, numPounds): if fruit not in fruitPrices: print "Sorry we don't have %s" % (fruit) else: cost = fruitPrices[fruit] * numPounds print "That'll be %f please" % (cost)# Main Functionif __name__ == '__main__': buyFruit('apples',2.4) buyFruit('coconuts',2)
Class
class FruitShop: def __init__(self, name, fruitPrices): """ name: Name of the fruit shop fruitPrices: Dictionary with keys as fruit strings and prices for values e.g. {'apples':2.00, 'oranges': 1.50, 'pears': 1.75} """ self.fruitPrices = fruitPrices self.name = name print 'Welcome to the %s fruit shop' % (name) def getCostPerPound(self, fruit): """ fruit: Fruit string Returns cost of 'fruit', assuming 'fruit' is in our inventory or None otherwise """ if fruit not in self.fruitPrices: print "Sorry we don't have %s" % (fruit) return None return self.fruitPrices[fruit] def getPriceOfOrder(self, orderList): """orderList: List of (fruit, numPounds) tuplesReturns cost of orderList. If any of the fruit are """ totalCost = 0.0 for fruit, numPounds in orderList: costPerPound = self.getCostPerPound(fruit) if costPerPound != None: totalCost += numPounds * costPerPound return totalCost def getName(self): return self.name
Use Object
We have defined the FruitShop class in shop. py. Next we can use this class in another script:
Use import
mport shopshopName = 'the Berkeley Bowl'fruitPrices = {'apples': 1.00, 'oranges': 1.50, 'pears': 1.75}berkeleyShop = shop.FruitShop(shopName, fruitPrices)applePrice = berkeleyShop.getCostPerPound('apples')print applePriceprint('Apples cost $%.2f at %s.' % (applePrice, shopName))otherName = 'the Stanford Mall'otherFruitPrices = {'kiwis':6.00, 'apples': 4.50, 'peaches': 8.75}otherFruitShop = shop.FruitShop(otherName, otherFruitPrices)otherPrice = otherFruitShop.getCostPerPound('apples')print otherPriceprint('Apples cost $%.2f at %s.' % (otherPrice, otherName))print("My, that's expensive!")
Static and instance variables
In person_class.py, enter:
class Person: population = 0 def __init__(self, myAge): self.age = myAge Person.population += 1 def get_population(self): return Person.population def get_age(self): return self.age
Here population is a static variable, or a global variable.
Run the following command:
>>> import person_class>>> p1 = person_class.Person(12)>>> p1.get_population()1>>> p2 = person_class.Person(63)>>> p1.get_population()2>>> p2.get_population()2>>> p1.get_age()12>>> p2.get_age()63
Others
Use range to loop:
for index in range(3): print lst[index]