PYTHON BASIC

Output:


print(3)
print("Hello World")


A = 123
B = 'ABC'
C = 456
D = 'DEF'
print(A, B, C, D)

Calculation:

1 + 1
4 - 2
12 / 3
2 * 3
5 % 2
2 ** 3

Variable:

cash =100 
apple =10
remain = cash – apple
print(remain)

x = 1;
x = x + 1
print(x)

Type:


1---Integer
"1"--- String
True---Boolean
[1, 2, 3]---List
(1, 2, 3)--- Tuple
["name": "Linda"]---Dictionary
two different type cannot operate together

String:


print("Hello World")
print("This is "+"BCIS") #concatenate
print("Over hill, over dale,\n"+"Thorough bush,thoroughbrier")
print(1 + 2)
print(1 + "ss") #wrong
print("1" + "ss")
print(str(1) + "ss")
print("This year is %d"%2016)
print("I am %d years old I have %d brothers"% (12,3))
print("PI is %6.3f"%3.14159)

Input:


print("How old are you?")
age = input()
print("How tall are you?")
height = input()
print("How much do you weigh?")
weight = input()
print("So, you're %s old, %s tall and %s heavy." % (age, height, weight))


name = input("What is your name?")
print("so your name is " + name)


Mad Lib Game

print("MAD LIB GAME")
print("Enter answers to the following prompts\n")

guy = input("Name of a famous man: ")
girl = input("Name of a famous woman: ")
food = input("Your favorite food (plural): ")
ship = input("Name of a space ship: ")
job = input("Name of a profession (plural): ")
planet = input("Name of a planet: ")
drink = input("Your favorite drink: ")
number = input("A number from 1 to 10: ")

story = "\nA famous married couple, GUY and GIRL, went on\n" +
"vacation to the planet PLANET. It took NUMBER\n" +
"weeks to get there travelling by SHIP. They\n" +
"enjoyed a luxurious candlelight dinner over-\n" +
"looking a DRINK ocean while eating FOOD. But,\n" +
"since they were both JOB, they had to cut their\n" +
"vacation short."

story = story.replace("GUY", guy)
story = story.replace("GIRL", girl)
story = story.replace("FOOD", food)
story = story.replace("SHIP", ship)
story = story.replace("JOB", job)
story = story.replace("PLANET", planet)
story = story.replace("DRINK", drink)
story = story.replace("NUMBER", number)

print(story)

List:

lists can contain any sort ofobject: numbers, strings, and even other lists.

classmates = ['Michael','Bob','Tracy','Tony','Cargo']
len(classmates)
classmates[0]
classmates.append('Jason')
classmates.insert(2,'Pony')
classmates.pop()
classmates.remove('Bob')
classmates.pop(2)
classmates.reverse()
classmates.sort()
classmates[2] ="Mike"
classmates[1:3]
classmates[:3]
classmates[-1]
classmates[-3:-1]
classmates[:5:2]
classmates[::-1]
classmates.count('Bob')
L = [
['Apple','Google','Microsoft'],
['Java','Python','Ruby','PHP'],
['Adam','Bart','Lisa']
]
L[0][1]

[1, 2, 3] + [4, 5, 6]
['Ni!'] * 4
3 in [1, 2, 3]

Dictionary:


dict= {'Michael':95,'Bob':75,'Tracy':85}
dict['Michael']
dict['Jack'] =90
dict['Jack']
dict['Jack'] =87
dict['Jack']
dict.get('Jack')
dict.pop('Michael')

Set:


s=set([1,1,2,2,3,3])# it will delete same number
s.add(4)
s.add(4)
print(s)# {1, 2, 3, 4}
s.remove(2)
s1 = {1,3,4}
s2 = {1,2,5}
s1 & s2
s1 | s2

Logic:


True and False
True or False
not True
1!=2
1==1
3>=1
3<=6

If:


age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')

Loop:

names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)

缩进

!/usr/bin/python

-- coding: UTF-8 --

文件名:test.py

if True:
print "Answer"
print "True"
else:
print "Answer"
# 没有严格缩进,在执行时会报错
print "False"

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)

sum = 0
for x in range(10):
sum = sum + x
print(sum)

Functions:


def my_abs(x):
if x >= 0:
return x
else:
return -x

def power(x, n):
s = 1
while n > 0:
n -= 1
s = s * x
return s

def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(1, 2)
nums = [1, 2, 3]
calc(*nums)

Recursion:


def fact(n):
if n==1:
return 1
return n * fact(n - 1)

Iteration:


d = {'a': 1, 'b': 2, 'c': 3}

for key in d:
print("key:" + key + "value:" + str(d[key]) + "\n")
for character in "ABCDEFG":
print(character)

Generator:

g = (x * x for x in range(10))
next(g)
next(g)

f = (x * x for x in range(10))
for n in f:
print(n)

def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
g = fib(10)

for i in g:
print(i)

High Order Function:

def add(a, b):
return a + b

f = add
print(f(1, 2))

Build-in Function:

map:

Map


def f(x):
return x * x

r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))

reduce:

from functools import reduce

def f(a, b):
return a + b

r = reduce(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

print(r)

filter:

def is_odd(n):
return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

sort:


sorted([36, 5, -12, 9, -21])
sorted([36, 5, -12, 9, -21], key=abs)
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)

Exception:


s = input("Enter a number:")
try:
number = float(s)
except:
number = 0

answer = number * number

print(answer)

Module:

test.py
test2.py

OOP:


class Student(object):
def init(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))

bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()

Inheritance:


class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Cat(Animal):
pass
dog = Dog()
dog.run()
cat = Cat()
cat.run()


class Dog(Animal):
def run(self):
print('Dog is running...')

def eat(self):
    print('Eating meat...')

dog = Dog()
dog.run()

a = list()
b = Animal()
c = Dog()

print(isinstance(a,list))
print(isinstance(b, Animal))
print(isinstance(c, Dog))
print(isinstance(c, Dog))

你可能感兴趣的:(PYTHON BASIC)