十个小型Python程序 [英] ten small Python programs

查看:84
本文介绍了十个小型Python程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为将新的

程序员引入Python的最佳方法是向他们展示小代码

例子。

当你去教程时,你必须通过相当多的英语跋涉

才能看到任何

Python示例。


以下是我尝试生成十个相当简单的,b $ b代表性的Python程序,它们向新用户展示了大多数基本概念的
,以及总体语法。


这是一个有趣的练习。我限制自己

到十行或更少,并且很容易

合并循环,条件,打印,打开(),列表,

元组,词典和导入的模块。


显示类很难,而我的ShoppingCart

类只不过是一个列表的封装,

具有可疑的价值(虽然它是

更有用的开头)。


无论如何,这里去:


------

打印''hello world''


--- ---

中的名字(''peter'',''paul'',''mary''):

打印名称


------

#这是一条Python评论。 \ n是换行符

name = raw_input(''你叫什么名字?\ n'')

打印''你好',名字


------

parentRabbits,babyRabbits =(1,1)

而babyRabbits< 100:

打印''这一代有%d兔子''%

babyRabbits

parentRabbits,babyRabbits =(babyRabbits,

parentRabbits + babyRabbits)

------

#def定义Python中的方法

def tax(itemCharge, taxRate = 0.05):

返回itemCharge * taxRate

打印''%。2f''%税(11.35)

打印''% .2f''%tax(40.00,0.08)

------

导入re

for test_string in [''555 -1212'',''ILL-EGAL'']:

if re.match('\\\\\\\\\\\\\\ d $'',test_string):

print test_string,''是一个有效的美国本地

电话号码''

else:

打印test_string,''拒绝''


------

price = {''apple'':0.40 ,''banana'':0.50}

myPurchase = {

''apple'':1,

''banana'': 6}

groceryBill =总和([价格[水果] *

myPurchase [水果]

for myPurchase中的水果])

print' 我欠杂货商$%。2f''%groceryBill

------

class ShoppingCart:

def __init __(self ):self.items = []

def buy(self,item):self.items.append(item)

def buyItems(self):return self.items

myCart = ShoppingCart()

myCart.buy(''apple'')

myCart.buy(''banana'')

打印myCart.boughtItems()

------

#缩进你的Python代码放入电子邮件

import glob

pythonFiles = glob.glob(''*。py'')

pythonFiles.sort()

for fn在python文件中:

打印''------''

for line in open(fn):

print''' '+ line.rstrip()

打印


------

导入时间

now = time.localtime()

hour = now.tm_hour

如果小时< 8:打印''睡觉''

elif hour< 9:打印''通勤''

elif hour< 17:打印''正在工作''

elif hour< 18:打印''通勤''

elif hour< 20:打印''吃''

elif hour< 22:打印''休息''

其他:打印''睡觉''

__________________________________________________ __________________________________

期待?通过电子邮件自动检查立即获得好消息。

试试Yahoo!邮件测试版。
http://advision.webevents.yahoo .com / ... ail_tools.html

I''ve always thought that the best way to introduce new
programmers to Python is to show them small code
examples.

When you go to the tutorial, though, you have to wade
through quite a bit of English before seeing any
Python examples.

Below is my attempt at generating ten fairly simple,
representative Python programs that expose new users
to most basic concepts, as well as the overall syntax.

It was an interesting exercise. I constrained myself
to ten lines or less, and it was pretty easy to
incorporate loops, conditionals, print, open(), lists,
tuples, dictionaries, and imported modules.

It was harder to show classes, and my ShoppingCart
class is nothing more than an encapsulation of a list,
which has dubious value (although it''s the start of
something more useful).

Anyway, here goes:

------
print ''hello world''

------
for name in (''peter'', ''paul'', ''mary''):
print name

------
# This is a Python comment. \n is a newline
name = raw_input(''What is your name?\n'')
print ''Hi'', name

------
parentRabbits, babyRabbits = (1, 1)
while babyRabbits < 100:
print ''This generation has %d rabbits'' %
babyRabbits
parentRabbits, babyRabbits = (babyRabbits,
parentRabbits + babyRabbits)
------
# def defines a method in Python
def tax(itemCharge, taxRate = 0.05):
return itemCharge * taxRate
print ''%.2f'' % tax(11.35)
print ''%.2f'' % tax(40.00, 0.08)
------
import re
for test_string in [ ''555-1212'', ''ILL-EGAL'']:
if re.match(''\d\d\d-\d\d\d\d$'', test_string):
print test_string, ''is a valid US local
phone number''
else:
print test_string, ''rejected''

------
prices = {''apple'': 0.40, ''banana'': 0.50}
myPurchase = {
''apple'': 1,
''banana'': 6}
groceryBill = sum([prices[fruit] *
myPurchase[fruit]
for fruit in myPurchase])
print ''I owe the grocer $%.2f'' % groceryBill
------
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy(''apple'')
myCart.buy(''banana'')
print myCart.boughtItems()
------
# indent your Python code to put into an email
import glob
pythonFiles = glob.glob(''*.py'')
pythonFiles.sort()
for fn in pythonFiles:
print '' ------''
for line in open(fn):
print '' '' + line.rstrip()
print

------
import time
now = time.localtime()
hour = now.tm_hour
if hour < 8: print ''sleeping''
elif hour < 9: print ''commuting''
elif hour < 17: print ''working''
elif hour < 18: print ''commuting''
elif hour < 20: print ''eating''
elif hour < 22: print ''resting''
else: print ''sleeping''

__________________________________________________ __________________________________
Expecting? Get great news right away with email Auto-Check.
Try the Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/...ail_tools.html

推荐答案

'',test_string):

print test_string ,''是有效的美国本地

电话号码''

否则:

打印test_string,''拒绝''


------

price = {''apple'':0.40,''banana'':0.50}

myPurchase = {

''apple'':1,

''banana'':6}

groceryBill = sum([价格[水果] ] *

myPurchase [水果]
我的购买水果
])

print''我欠杂货店
'', test_string):
print test_string, ''is a valid US local
phone number''
else:
print test_string, ''rejected''

------
prices = {''apple'': 0.40, ''banana'': 0.50}
myPurchase = {
''apple'': 1,
''banana'': 6}
groceryBill = sum([prices[fruit] *
myPurchase[fruit]
for fruit in myPurchase])
print ''I owe the grocer

%。2f''%groceryBill

------

class ShoppingCart:

def __init __(self): self.items = []

def buy(self,item):self.items.append(item)

def buyItems(self):retur n self.items

myCart = ShoppingCart()

myCart.buy(''apple'')

myCart.buy('''banana '')

print myCart.boughtItems()

------

#缩进你的Python代码放入电子邮件

导入glob

pythonFiles = glob.glob(''*。py'')

pythonFiles.sort()
$ b pythonFiles中fn的$ b:

打印''------''

for line in open(fn):

打印''''+ line.rstrip()

打印


------

导入时间

now = time.localtime()

hour = now.tm_hour

if hour< 8:打印''睡觉''

elif hour< 9:打印''通勤''

elif hour< 17:打印''正在工作''

elif hour< 18:打印''通勤''

elif hour< 20:打印''吃''

elif hour< 22:打印''休息''

其他:打印''睡觉''

__________________________________________________ __________________________________

期待?通过电子邮件自动检查立即获得好消息。

试试Yahoo!邮件测试版。
http://advision.webevents.yahoo .com / ... ail_tools.html
%.2f'' % groceryBill
------
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy(''apple'')
myCart.buy(''banana'')
print myCart.boughtItems()
------
# indent your Python code to put into an email
import glob
pythonFiles = glob.glob(''*.py'')
pythonFiles.sort()
for fn in pythonFiles:
print '' ------''
for line in open(fn):
print '' '' + line.rstrip()
print

------
import time
now = time.localtime()
hour = now.tm_hour
if hour < 8: print ''sleeping''
elif hour < 9: print ''commuting''
elif hour < 17: print ''working''
elif hour < 18: print ''commuting''
elif hour < 20: print ''eating''
elif hour < 22: print ''resting''
else: print ''sleeping''

__________________________________________________ __________________________________
Expecting? Get great news right away with email Auto-Check.
Try the Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/...ail_tools.html


Steve Howell写道:
Steve Howell wrote:

我'我一直认为向Python推出新的
程序员的最佳方法是向他们展示小代码

例子。


但是当你去教程时,你必须通过相当多的英语跋涉

才能看到任何

Python的例子。


以下是我尝试生成十个相当简单的,b $ b代表性的Python程序,它们向大多数基本概念以及整体语法公开新用户


I''ve always thought that the best way to introduce new
programmers to Python is to show them small code
examples.

When you go to the tutorial, though, you have to wade
through quite a bit of English before seeing any
Python examples.

Below is my attempt at generating ten fairly simple,
representative Python programs that expose new users
to most basic concepts, as well as the overall syntax.



很酷!你介意把它放在Wiki的某个地方,以便我们可以更容易地链接到它吗?也许是这样的:

http://wiki.python。 org / moin / SimplePrograms


< nitpick>

虽然代码应该遵循PEP 8指南,例如
$ b对于对象和方法名称,$ b under_scores而不是camelCase:

http://www.python.org/dev/peps/pep-0008/

< / nitpick>


Very cool! Do you mind putting this up on the Wiki somewhere so that we
can link to it more easily? Maybe something like:

http://wiki.python.org/moin/SimplePrograms

<nitpick>
Though the code should probably follow PEP 8 guidelines, e.g.
under_scores instead of camelCase for object and method names:

http://www.python.org/dev/peps/pep-0008/
</nitpick>


class ShoppingCart:

def __init __(self):self.items = []

def buy(self,item):self.items.append (项目)

def buyItems(self):return self.items

myCart = ShoppingCart()

myCart.buy('''apple' ')

myCart.buy(''banana'')

print myCart.boughtItems()
class ShoppingCart:
def __init__(self): self.items = []
def buy(self, item): self.items.append(item)
def boughtItems(self): return self.items
myCart = ShoppingCart()
myCart.buy(''apple'')
myCart.buy(''banana'')
print myCart.boughtItems()



我认为buyItems()是可能的不是Python代码的好例子

因为在这种情况下,你应该只写``my_cart.items``。

也许它应该定义``__len__` `而不是?或者类似::


def select_items(self,prefix):

如果item.startswith(前缀)返回[self.items中项目的项目]

STeVe

I think boughtItems() is probably not a good example of Python code
since in this case, you should probably just write ``my_cart.items``.
Maybe it should define ``__len__`` instead? Or maybe something like::

def select_items(self, prefix):
return [item for item in self.items if item.startswith(prefix)]
STeVe


这篇关于十个小型Python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆