In [2]:
print "Hello World"
In [5]:
a = 3
a + 2
Out[5]:
In [6]:
print "Hello World"
In [12]:
import requests
from bs4 import BeautifulSoup as bs
import jieba
res = requests.get('https://www.ptt.cc/bbs/Soft_Job/index.html', verify=False)
soup = bs(res.text)
dic = {}
for ent in soup.select('.r-ent'):
for w in jieba.cut(ent.select('.title')[0].text.strip()):
if w not in dic:
dic[w] = 1
else:
dic[w] = dic[w] + 1
#for ele in dic:
# print ele, dic[ele]
In [13]:
# this is a comment
'''
multiple
comments
'''
Out[13]:
In [16]:
# int a = 3;
a = 3
print type(a)
b = "hello world"
print type(b)
a + b
In [19]:
import sys
# This is a single line comment
def main():
print 'Hello World'
In [20]:
main()
In [24]:
import sys
#help(sys)
#?sys
#dir(sys)
help(sys.exit)
In [25]:
print ("Hello from python")
In [24]:
input("How are you?")
Out[24]:
In [30]:
answer = input("How are you?")
In [5]:
answer = raw_input("How are you?")
In [6]:
print answer
In [10]:
name = raw_input("What is your name? ")
if name == "David":
print "Nice to mee you! " + name
elif name == "John":
print "Hi John"
else:
print ("Your name again?")
In [17]:
name = raw_input("What is your name? ")
age = raw_input("How old are you? ")
# Method 1: concat phrases with +
#print "My name is "+ name + ", and I am " + age + " years old"
# Method 2: {} best
#print "My name is {}, and I am {} years old".format(name, age)
# Method 3: {} with index best
#print "My name is {0}, and I am {1} years old".format(name, age)
#print "My name is {1}, and I am {1} years old".format(name, age)
# Method 4: %s => str, %d => int
#print "My name is %s, and I am %d years old"%(name, int(age))
In [20]:
print "http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/{}".format('1')
print "http://www.appledaily.com.tw/realtimenews/article/finance/20150908/687086/%E5%93%80%E9%B3%B3%E5%8F%B2%E4%B8%8A%E6%9C%80%E8%96%84%E3%80%80%E6%98%8E%E5%B9%B4i7%E5%83%856mm/%s"%('1')
In [32]:
a = 3
b = 2
print a + b
print a - b
c = 1.5
d = 2.5
print c + d
print c - d
print type(a + b)
print type(c + d)
In [35]:
s = '2'
print type(s)
int(s)
print type(int(s))
print s + '34567'
print int(s) + 34567
In [42]:
print float(2)
print float(3.2)
print 2/3
print float(2/3)
# print numeric after period
print float(2)/3
print 2.0/3
print 2 /3.0
In [45]:
print 'qoo'
print 'qoo' * 3
print '?' * 8
In [46]:
times = raw_input("Repeat Times: ")
print("Qoo " * int(times))
In [49]:
print 1/3
print 1.0 /3
# print with comma
print 1/3,
print 1/3.0
In [52]:
print 1/3
print 3/3
In [53]:
3/0
In [54]:
try:
3/0
except ZeroDivisionError:
print "three divides to 0 shows zero devision error"
In [60]:
dividend = raw_input("Dividend: ")
divisor = raw_input("Divisor: ")
try:
print float(dividend) / float(divisor)
except ZeroDivisionError as detail:
print "ZeroDvisionError", detail
In [61]:
dividend = raw_input("Dividend: ")
divisor = raw_input("Divisor: ")
try:
print float(dividend) / float(divisor)
except ValueError as detail:
print "ValueError", detail
except ZeroDivisionError as detail:
print "ZeroDvisionError", detail
In [63]:
dividend = raw_input("Dividend: ")
divisor = raw_input("Divisor: ")
try:
print float(dividend) / float(divisor)
except:
print "error"
In [66]:
print "hello world"
print 'hello world'
print "this is a 'book' "
print 'this is a "book"'
In [68]:
a = 'hi this is a l\
ong text'
print a
a = '''hi this is a l
ong text'''
print a
In [78]:
s = 'hello world'
print s[0]
print s[1]
print s[-1]
print s[-2]
In [81]:
print len(s)
print s + ' yoyo'
In [77]:
import os
for f in os.listdir('../'):
if f[0] == '.':
print f
In [84]:
s = '30'
print s + 'yoyo'
print int(s) + 50
age = 30
print "my age is " + str(age)
In [85]:
# \t => tab, \n => new line
raw = '\n\t this is a \t line with format \t\n'
print raw
In [86]:
raw = r'\n\t this is a \t line with format \t\n'
print raw
In [87]:
raw = repr('\n\t this is a \t line with format \t\n')
print raw
In [92]:
a = 'Qoo loves OOP'
print a.split()
print a.upper()
print a.lower()
print dir(a)
print a.title()
In [93]:
a = 'Qoo loves OOP'
print a.isdigit()
In [98]:
import os
for f in os.listdir('../'):
if f.split('.')[-1] == 'txt':
print f
In [107]:
import requests
from bs4 import BeautifulSoup as bs
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.262 Safari/537.36'}
res = requests.get('http://ck101.com/', headers = headers)
soup = bs(res.text)
for img in soup.select('img'):
if 'png' in img.get('src') or 'jpg' in img.get('src') or 'gif' in img.get('src'):
print img.get('src').split('/')[-1]
In [115]:
import requests
import shutil
from bs4 import BeautifulSoup as bs
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.262 Safari/537.36'}
res = requests.get('http://ck101.com/', headers = headers)
soup = bs(res.text)
for img in soup.select('img'):
fname = img.get('src').split('/')[-1]
extension = fname.split('.')[1]
if extension in ['png', 'gif', 'jpg']:
#print fname
response = requests.get(img.get('src'), headers = headers, stream=True)
with open(fname, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
In [117]:
import string
a = 'Qoo loves OOP'
print a.split()
string.join(a.split(), '-') # 'Qoo-loves-OOP'
a = 'Qoo loves OOP'
'-'.join(a.split())
Out[117]:
In [121]:
a = 'Qoo loves OOP'
print a.split()
print '@'.join(a.split())
a = 'adsf df sdf sdf'
print a.split()
print ' '.join(a.split())
In [122]:
s = 'hello'
s[1:4] , \
s[1:] , \
s[:] , \
s[1:100] , \
Out[122]:
In [123]:
s = 'hello'
s[-1] , \
s[-4] , \
s[:-3] , \
s[-3:] , \
Out[123]:
In [125]:
s = 'hello'
# for(i = len(s); i> 0 ; i--)
print s[::-1]
a = 'abcdedcba'
print a==a[::-1]
In [128]:
#String Formatting
print 'The results are {} and {}'.format(3.14159, 5)
# str => %s int => %d float => %f
print 'The results are %.02f and %d' % (3.14159, 5)
In [132]:
a = '123'
#print dir(a)
print a.__str__
In [133]:
import os
for f in os.listdir('./'):
print f
In [137]:
ary = ['hello', 'world' , 3]
print ary[0] + ' yoyo'
print ary[2] + 5
In [138]:
print list("word")
In [144]:
ary = [['list'], ['of', 'lists']]
print ary[0]
print ary[1]
print ary[1][0]
print list(('a', 1))
a = ['heterogeneous', 3]
a[1] + 5
Out[144]:
In [146]:
a = [5, 6, 7, 's'] # a = [5 6 7 ‘s’]
print a[0] # 5
print a[2:4] # [7, ‘s’]
print a[-1] # ‘s’
print a[-2] # 7
print a[2:] # [7, ‘s’]
print a[::2] # [5, 7]
print a[::-1] # [‘s’, 7, 6, 5]
print len(a) # 4
print [min(a), max(a)] # [5, ‘s’]
In [150]:
a = [5, 6, 7, 8]
print a
a.pop()
print a
a.append(2) # a = [5, 6, 7, 2]
print a
a.sort() # a = [2, 5, 6, 7]
print a
In [151]:
print a[::-1]
print a
a.reverse() # a = [7, 6, 5, 2]
print a
In [154]:
a.remove(6)
In [155]:
print a
In [156]:
print dir(a)
In [157]:
a= [1,23,2,4,1,2,3,1,4,5]
print a.count(1)
In [158]:
print help(a.insert)
In [160]:
print a
a.insert(3,'qoo')
print a
In [164]:
for qoo in os.listdir('../'):
if 'txt' in qoo:
print qoo
In [168]:
import requests
from bs4 import BeautifulSoup as bs
res = requests.get('https://www.ptt.cc/bbs/Soft_Job/index.html', verify=False)
soup = bs(res.text)
for title in soup.select('.r-ent'):
if '新鮮人'.decode('utf-8') in title.select('.title')[0].text:
print title.select('.title')[0].text.strip()
In [170]:
list('a')
hello = list('hello world')
print hello
print 'e' in hello
print 'a' in hello
In [171]:
a = [1, 2, 3]
print "a:", a
b = a
print "a:", a
print "b:", b
a[1] = 2000
print "a:", a
print "b:", b
In [172]:
a = [1, 2, 3]
import copy
b = copy.deepcopy(a) # Deep Copy
a[1] = 2000
print "a:", a
print "b:", b
In [173]:
nums = [1, 2, 3, 4]
square = []
for n in nums:
square.append(n * n)
print square
In [174]:
nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ]
print squares
In [175]:
nums = [2, 8, 1, 6]
small = []
for n in nums:
if n <= 2:
small.append(n)
print small
In [176]:
small = [ n for n in nums if n <= 2 ] ## [2, 1]
print small
In [178]:
fruits = ['apple', 'cherry', 'bannana', 'lemon']
afruits = []
for s in fruits:
if 'a' in s:
afruits.append(s.upper())
print afruits
In [179]:
afruits = [ s.upper() for s in fruits if 'a' in s ]
print afruits
In [ ]:
In [ ]:
In [7]:
contact_list = []
while True:
contact = raw_input("Add Contact: ")
if contact == "Done":
break
else:
contact_list.append(contact)
print "now, you have {} contacts".format(len(contact_list))
print "Your contacts are: " + ', '.join(contact_list)
In [9]:
# for(int i = 1; i< 10 ; i ++)
print range(1,10)
for i in range(1,10):
print i + 5
In [11]:
#if - else
a = 9
b = 8
for i in range(1,200):
if i == a:
print(str(a) + ' found!')
break
elif i == b:
print str(b) + ' found'
else:
print(str(a) + ' was not in the list')
In [12]:
# from 1 to 10
for i in range(1,10):
print i,
print
In [22]:
# step by 2
for i in range(1,10,2):
print i,
print
print range(1,10,2)
print range(1,10,3)
print range(10,1,-1) # for(i = 10; i> 1; i--)
print range(-1, -5, -1)
In [14]:
# Iterate over list
a = [1,2,3,4,5]
for i in a:
print i,
In [15]:
# Iterate over list
a = [1,2,3,4,5]
for qoo in a:
print qoo,
In [32]:
i =0
suma = 0
while(i < 101):
suma += i
i +=1
print suma
In [1]:
sum(range(1,101))
Out[1]:
In [2]:
# dry => do not repeat yourself
def say_hello():
print "hello world"
In [3]:
say_hello()
In [4]:
def addNum(a, b):#Define Function
return a+b #Return function
print addNum(1,4)
In [5]:
import math
a = math.ceil(3.6)
print a
In [7]:
import math #Importing Modules
print math #Print Content
In [8]:
import sys #Importing Modules
print(sys.argv) #Print Argument
In [9]:
print len(sys.argv)
In [10]:
def add_contact(name):
contact_list.append(name)
print "You have %d contacts" % (len(contact_list))
def get_contact():
return "Your Contacts: %s"%(contact_list)
In [12]:
contact_list = []
def main():
while True:
contact = raw_input("Add Contact: ")
if contact == 'Done':
break
else:
add_contact(contact)
print get_contact()
main()
In [ ]: