一、前言
Python语法简单,大多数情况下,根据单词的意思就可以猜测出程序的功能。在介绍Python语法之前,先看一些Pyhton代码的案例,这些案例都很简单,可以在PyChram中运行。(PyCharm的安装见上一篇,Python基础-0 Python简介及PyCharm安装 (qq.com))
打开PyCharm,我们直接新建一个Python文件,(右键工程文件夹(pythonProject)-->New-->Python File)
然后弹出窗口,给文件命名,这里命名为test,按回车创建。
于是工程文件夹下就多了一个test.py文件,我们就在这里写代码。
编写完成后,右键test.py运行。
二、从一行代码开始运行Python程序
代码来自:https://wiki.python.org/moin/SimplePrograms
1行:输出信息
代码:
print('Hello, world!')
运行结果:
Hello, world!
2行:输入信息
代码:
name = input('What is your name?\n') print('Hi, %s.' % name)
运行后,PyCharm下面的控制台会打印提示消息,What is your name?
我们点一下这句话的下面,然后就可以输入名字了。
(输入完,按回车表示输入结束)
程序得到信息,并将该信息输出:
3行:for循环
代码:
friends = ['john', 'pat', 'gary', 'michael'] for i, name in enumerate(friends): print(f"friend {i} is {name}")
运行结果:
friend 0 is john
friend 1 is pat
friend 2 is gary
friend 3 is michael
4行:实现斐波那契数
代码:
parents, babies = (1, 1) while babies < 100: print(f'This generation has {babies} babies') parents, babies = (babies, parents + babies)
运行结果:
This generation has 1 babies This generation has 2 babies This generation has 3 babies This generation has 5 babies This generation has 8 babies This generation has 13 babies This generation has 21 babies This generation has 34 babies This generation has 55 babies This generation has 89 babies
5行:函数(Functions)(或者翻译为方法,功能)
代码:
def greet(name): print('Hello', name) greet('Jack') greet('Jill') greet('Bob')
运行结果:
Hello Jack
Hello Jill
Hello Bob
6行:导入库,使用库的函数进行字符串匹配。
代码:
import re for test_string in ['555-1212', 'ILL-EGAL']: if re.match(r'^\d{3}-\d{4}$', test_string): print(test_string, 'is a valid US local phone number') else: print(test_string, 'rejected')
运行结果:
555-1212 is a valid US local phone number
ILL-EGAL rejected
7行:字典,生成器表达式
代码:
prices = {'apple': 0.40, 'banana': 0.50} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum(prices[fruit] * my_purchase[fruit] for fruit in my_purchase) print(f'I owe the grocer {grocery_bill:.2f}$')
运行结果:
I owe the grocer 3.40$
8行:从命令行读入。程序实现了一个加法器
# This program adds up integers that have been passed as arguments in the command line import sys try: total = sum(int(arg) for arg in sys.argv[1:]) print ('sum =', total) except ValueError: print ('Please supply integer arguments')
为什么只有7行呢,因为第8行在命令行中输入:
python test.py 1 2 3 4
点击下面的Terminal,进入命令行,输入代码。执行test.py程序。
9行(#开头的注释不算,11-2=9):读取文件
代码:
# indent your Python code to put into an email import glob # glob supports Unix style pathname extensions python_files = glob.glob('*.py') for file_name in sorted(python_files): print(' ------' + file_name) with open(file_name) as f: for line in f: print(' ' + line.rstrip()) print()
运行结果:
太长,输出了该目录下py文件内容。
10行:获取当前时间(不算activities及其上下空格,activities相当于是数据)
代码:
from time import localtime activities = {8: 'Sleeping', 9: 'Commuting', 17: 'Working', 18: 'Commuting', 20: 'Eating', 22: 'Resting' } time_now = localtime() hour = time_now.tm_hour for activity_time in sorted(activities.keys()): if hour < activity_time: print (activities[activity_time]) break else: print ('Unknown, AFK or sleeping!')
运行结果:
我运行的时间是上午10:42,所以对应的是:
Working
11行:三引号字符串,while循环
代码:
REFRAIN = ''' %d bottles of beer on the wall, %d bottles of beer, take one down, pass it around, %d bottles of beer on the wall! ''' bottles_of_beer = 9 while bottles_of_beer > 1: print(REFRAIN % (bottles_of_beer, bottles_of_beer, bottles_of_beer - 1)) bottles_of_beer -= 1
运行结果:
太长。每次句子中的bottles_of_beer减一。
12行:类。创建一个银行账户,进行存钱取钱。
代码:
class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def overdrawn(self): return self.balance < 0 my_account = BankAccount(15) my_account.withdraw(50) print (my_account.balance, my_account.overdrawn())
运行结果:
-35 True
13行:使用unittest进行单元测试(Unit testing)。下面代码测试了一个取中位数的功能median。
self.assertEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)语句,是判断函数median的结果是否和预期结果7相同。
代码:
import unittest def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 class TestMedian(unittest.TestCase): def testMedian(self): self.assertEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) if __name__ == '__main__': unittest.main()
运行结果:
D:/PY_TEST/pythonProject/test.py Testing started at 10:49 ... Launching unittests with arguments python -m unittest D:/PY_TEST/pythonProject/test.py in D:\PY_TEST\pythonProject Ran 1 test in 0.002s OK
14行:文档测试( Doctest-based testing)
def median(pool): '''Statistical median to demonstrate doctest. >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 6 #change to 7 in order to pass the test ''' copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 if __name__ == '__main__': import doctest doctest.testmod()
运行结果:错误,预期 6 #change to 7 in order to pass the test,得到值7。
Failure <Click to see difference> ********************************************************************** File "D:\PY_TEST/pythonProject\test.py", line 3, in test.median Failed example: median([2, 9, 9, 7, 9, 2, 4, 5, 8]) Expected: 6 #change to 7 in order to pass the test Got: 7
说明文档错误,修改代码第4行:
def median(pool): '''Statistical median to demonstrate doctest. >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 7 ''' copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[int((size - 1) / 2)] else: return (copy[int(size/2 - 1)] + copy[int(size/2)]) / 2 if __name__ == '__main__': import doctest doctest.testmod()
Testing started at 10:57 ...
Process finished with exit code 0