Week 2 Python Introduction¶
Copyright By PowCoder代写 加微信 powcoder
# define a string s
s = ‘First line.\nSecond line.’
# print the string, \n means a new line
print(len(s)) # print the length of the string
First line.
Second line.
# get elements or sub-string of the string
# test string methods
s.split(sep=’\n’, maxsplit=-1)
[‘First line.’, ‘Second line.’]
s.istitle()
s.isalpha()
s1=’first’
s1.isalpha()
s1.istitle()
s2=’First Second’
s2.isalpha()
spam = ‘Hello world!’
spam.istitle()
spam = ‘Hello World!’
spam.istitle()
s=’-‘.join([‘My’, ‘Name’, ‘is’, ‘John’])
s.split(sep=’-‘, maxsplit=-1)
[‘My’, ‘Name’, ‘is’, ‘John’]
s.strip(‘n’)
‘My-Name-is-Joh’
s = ‘## My # name is #’
s.strip(‘#’)
‘ My # name is ‘
s.replace(‘#’, ‘%’, 3)
‘%% My % name is #’
spam = ‘HellO WOrld!’
spam.replace(‘O’, ‘o’, 1)
‘Hello WOrld!’
mystr = ‘ ?’
mappingtbl = mystr.maketrans(‘M?’,’H!’)
newstr = mystr.translate(mappingtbl) # pass mapping table in translate()
print(newstr)
Hello World!
# simple program
print(‘Hello’)
print(‘What\’s your name?’)
yourName=input()
print(‘It is good to meet you,’ + yourName) #yourName must be a string?
print(‘The length of your name is\n’)
print(len(yourName))
What’s your name?
It is good to meet you,”Yuefeng”
The length of your name is
# if statements
x = int(input(“Please enter an integer: “))
print(‘Negative changed to zero’)
elif x == 0:
print(‘Zero’)
elif x == 1:
print(‘Single’)
print(‘More’)
Please enter an integer: 1
# for loops
words = [‘cat’, ‘window’, ‘defenestrate’]
for w in words:
print(w, len(w))
defenestrate 12
# use range
a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]
for i in range(len(a)): # or range(0, len(a))
print(i, a[i])
# write Fibonacci series up to 100
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print('the_end')
# break statement
your_pwd = 'qut2020'
while True:
print('Enter your password:')
input_pwd = input()
if input_pwd == your_pwd:
print('I got it!')
0 1 1 2 3 5 8 13 21 34 55 89 the_end
Enter your password:
# for loops cont.
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
'__builtin__',
'__builtins__',
'__doc__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'get_ipython',
'input_pwd',
'mappingtbl',
'yourName',
'your_pwd']
# import random in two ways
print('The 1st:')
import random
x = random.randint(1,10)
print('The 2nd:')
from random import randint
y = randint(1,10)
def fib(n): # Fibonacci function
x, y = 0, 1
fib_list = []
while x < n:
fib_list.append(x)
x, y = y, x+y
return(fib_list)
# test the function
print(fib(0))
print(fib(100))
print(fib(2000))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
# use except
def spam(divideBy):
return 100/ divideBy
except ZeroDivisionError:
print('Error: invalid denominator')
# test spam function
Error: invalid denominator
8.333333333333334
# list comprehension
[(x,y) for x in [1,2,3] for y in [3,1,4] if x!=y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
# python dictionary (dict)
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127 #insert
{'jack': 4098, 'sape': 4139, 'guido': 4127}
['jack', 'sape', 'guido']
sorted(tel)
['guido', 'jack', 'sape']
'jack' not in tel
'sape' in tel
# list to dict
dict([('John', 4130), ('lee', 5212)])
{'John': 4130, 'lee': 5212}
# dict comprehension
nd = {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
nd[8] = 64
{2: 4, 4: 16, 6: 36, 8: 64}
tel['jack']
{'jack': 4098, 'sape': 4139, 'guido': 4127}
# loop to access dictionary
for (k, v) in tel.items():
print(k,v)
guido 4127
for v in tel.values():
for k in tel.keys():
# define class
class MyClass:
"""A simple example class"""
def __init__(self, myList):
self.data = myList
def f(self):
return 'hello world'
# test the define class
mc = MyClass([2,3,0])
print(mc.i)
print(mc.f())
print(mc.data)
mc.data = [1,2,3,4]
print(mc.data)
hello world
[1, 2, 3, 4]
# class cont.
class Node:
def __init__(self, data, next=None):
self.data=data
self.next=next
class Linkedlist:
def __init__(self, hnode):
self.head=hnode
def insert(self, nnode):
if self.head != None:
p = self.head
while p.next != None:
p.next=nnode
def lprint(self):
if self.head != None:
p = self.head
while p!= None:
print(p.data,end =" " )
if p.next != None:
print ('-->‘, end=” “)
print(‘The list is empty!’)
myList = Linkedlist(Node(“A”, None))
myList.insert(Node(‘B’, None))
myList.insert(Node(‘C’, None))
myList.lprint()
A –> B –> C
# test os package
os.path.join(‘usr’, ‘bin’, ‘spam’)
‘usr/bin/spam’
myFiles = [‘acounts.txt’, ‘details.csv’, ‘invite.doc’]
for fn in myFiles:
print(os.path.join(‘/users/li’, fn))
/users/li/acounts.txt
/users/li/details.csv
/users/li/invite.doc
# get your current working folder
os.getcwd()
‘/Users/li3/Desktop/QUT2020_22/teaching/Sem1_2022/IFN647/wk2_lec’
# open a file and read its contents
xmlFile = open(‘6146.xml’)
xmlContent = xmlFile.read() # also check readlines()
words = xmlContent.split(‘\n’)
# print each paragraphs separated by newline
for w in words:
#print all paragraphs that start with ‘'
for w in words:
if w.startswith(''):
Argentine bonds were slightly higher in a small technical bounce Wednesday amid low volume.
A trader at a large foreign bank said there was a slight technical bounce at the opening, and he did not expect prices to change much during the session as no market-moving news is expected.
The 5.5 percent dollar-denominated 2 due 2001 rose $0.15 to 115.15. Argentina’s FRB due 2005 rose 1/8 to 77-3/8.
"There is general uncertainty," said the trader, pointing to all the events the market is waiting for, including the passage of the government’s new economic measures through Congress, which is now not expected until early October.
In addition, traders are awaiting a meeting Friday between Economy Minister and an International Monetary Fund delegation on Argentina’s fiscal deficit.
— , Buenos Aires Newsroom, 541 318-0668
# test webbrowser package
import webbrowser
webbrowser.open('http://inventwithpython.com/')
# Test requests package for opening online text files
import requests
res = requests.get('https://automatetheboringstuff.com/files/rj.txt')
#type(res)
res.status_code == requests.codes.ok
print(len(res.text))
print(res.text[:334])
The Project Gutenberg EBook of Romeo and Juliet, by
This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever. You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.org/license
# check the output by open it using webbrowser
webbrowser.open('https://automatetheboringstuff.com/files/rj.txt')
import requests, bs4
res = requests.get('https://nostarch.com/')
res.raise_for_status()
noStarchSoup = bs4.BeautifulSoup(res.text)
metas = noStarchSoup.select('meta')
titles = noStarchSoup.select('title')
print(titles)
#print(metas)
[
type(noStarchSoup)
bs4.BeautifulSoup
print(res.text[:200])
Y Li ]
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com