每次都以Python入门开始。
因为自己毕竟没有正规学习Python,所以每次都瞄一眼。
这次尝试把例子压缩紧凑地放在一起,方便“瞄一眼”,假如都熟悉了就略过,假如看到生疏的,再进一步去找详细的语法说明。
# This is a one line comment
print('Hello World!')
print(firstVariable.lower())
print(firstVariable.upper())
print(firstVariable.title())
# Can also use help
help(firstVariable.lower)
a = firstVariable.split(' ');
' '.join(a) ; "0" * 3 ; 2**3 ; 9%3 ;
if True:
print("This was True");
if num > 0 and num < 15:
print(num);
elif:
print("Hi");
else:
print(str(num));
pass;
z[0] ; z[-2] ; z[0:2] ; z[:3] ; z[1:] ;
print(min(z), max(z), len(z), sum(z));
random_list = [4, 1, 5, 4, 10, 4];
random_list.count(4);
random_list.index(4);
# you can specify where you start your search
random_list.index(4, 3);
# random_list.index(value, [start, stop])
random_list.index(4, 5, 6);
# Sorting and Altering original list
# low to high
x.sort(); print(x);
x.sort(reverse = True); print(x);
# sorting list WITHOUT altering original list
new_list = sorted(y);
new_list;
x.append(3); print(x);
x.remove(10); print(x);
# Remove item at the index
# this function will also return the item you removed from the list
# Default is the last index
x.pop(3);
# Concatenating Lists
print('x+y=',x+y);
x.insert(4, [4, 5]);
webstersDict = {'aa': '11', 'bb': '22', 'cc': '33', 'dd': '44'};
webstersDict['aa'];
webstersDict['aa'] = '99';
webstersDict.update({'aa': 88', 'bb': '77'});
del webstersDict['bb'];
storyCount.get('Michael', 0);
print(storyCount.get('run'));
count = storyCount.pop('the');
print(storyCount.keys());
print(storyCount.values());
for key in storyCount:
print(key);
for key, value in webstersDict.items():
print(key, value);
emptyTuple = ();
emptyTuple = tuple();
z = (3, 7, 4, 2);
# tuple with one value
tup1 = ('Michael',)
# tuple with one value
tup2 = 'Michael',
# This is a string, NOT a tuple.
notTuple = ('Michael')
# Access the first item of a tuple at index 0
print(z[0])
print(z[0:2])
# 元组是不可改变的
print(animals.index('lama'));
print(animals.count('lama'));
for item in ('lama', 'sheep', 'lama', 48):
print(item);
x, y = (7, 10);
friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):
print(index,friend)
(0, 'Steve')
(1, 'Rachel')
(2, 'Michael')
(3, 'Monica')
# 元组可以用作字典键
bigramsTupleDict = {('this', 'is'): 23,
('is', 'a'): 12,
('a', 'sentence'): 2}
a,b = 1,1
for i in range(10):
print("Fib(a): ", a, "b is: ", b)
a,b = b,a+b
for number in [23, 41, 12, 16, 7]:
print(number)
print('Hi')
friends = ['steve', 'rachel', 'michael', 'adam', 'monica']
for index, friend in enumerate(friends):
print(index,friend)
for char in '-.,;\n"\'':
text = text.replace(char,' ')
print(text)
text.split(' ')[0:20]
# for break; continue;
count = 0
while count <= 5:
print(count)
count = count + 1
count = 0
while count <= 5:
if count == 2:
break
count += 1
print (count)
def function_name(parameters):
"""docstring"""
statement(s)
print(greet.__doc__)
return [expression_list]
def greet(name, msg = "Good morning!"):
print("Hello",name + ', ' + msg)
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
def remove_duplicates(duplicate):
uniques = []
for num in duplicate:
if num not in uniques:
uniques.append(num)
return(uniques)
class Dog:
pass
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# Instantiate the Dog object
philo = Dog("Philo", 5)
mikey = Dog("Mikey", 6)
# Access the instance attributes
print("{} is {} and {} is {}.".format(
philo.name, philo.age, mikey.name, mikey.age))
# Child class (inherits from Dog class)
class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)
# Child class (inherits from Dog class)
class Bulldog(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)