python3学习之路(2)简单的代码结构

来源:互联网 发布:柴鸡蛋逆袭网络剧下载 编辑:程序博客网 时间:2024/06/10 20:10

昨天聊了聊python容器,今天我们来聊聊代码结构吧

##这仅仅是个送给闰年出生的人们的!

months=['January','February','March','April','May','June','July','August','September','October','November','December']
fruits =['Banana','Apple','Watermalon','Orange','Ice-cream','Banana','Apple','Watermalon','Orange','Ice-cream','Banana','Apple']
drinks =['Coffee','Tea','Beer','Water','Grape-juice','Black-coffee','Green-tea','Beer','Water','Grape-juice','Coffee','Tea']
days=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
leapyears = int(input("Please input your BirthYear:"))
if leapyears>=1990 and leapyears <=2016:
    if leapyears%4==0:
        for month , fruit , drink inzip(months, fruits, drinks):


            print("You should in ",month,"--drink--",drink,"--eat--",fruit,"every day!")
    else:
        print("ByeBye!")
elif leapyears >2016:
    print("Your birthyear in",leapyears,"year!!!","Are you sure?")
    print("ByeBye......")


elif leapyears<1990:
    leapyears1=int(input("Please confirm your BirthYear:"))
    if leapyears1<=1990 and leapyears1>=1900:
        if leapyears1%4==0:
            print("Old Bastard!")#just play a joke
            for month , fruit , drink, day in zip(months, fruits, drinks, days):
                print("You should in every",month,"every",day,"Pray!" )
    elif leapyears1<1900:
        print("Your birthyear in",leapyears1,"year!!!","Are you sure?")
        print("ByeBye......")
else:
    print("Bye!!!")

if,elif,else仅仅是进行了一些条件判断,所有的逻辑都是自顶向下执行的.(注意对于缩进我们最好用四个空格而不是tap键!)

这里需要注意的是我还用了for来迭代!一般来讲列表,字符串,元组,字典,集合等都是可以迭代的对象,所以尽情的玩耍吧!

上例中我们用zip()实现了并行迭代!zip()函数在最短序列“用完时”就停下来了这一点大家要注意!

我们还可以使用range()来生成自然数序列这也是一件很酷的事情(感觉像入门的雕虫小技)

>>> for x in range(4, -5, -2):
print(x)



4
2
0
-2
-4

使用while可以进行循环,例如:

>>> count = 0
>>> while count <=5:
print(count)
count +=1



0
1
2
3
4
5

关于循环结构还要你自己去多多实践,下面我们来聊聊推导式,使用推导式更像pyhon的风格!

列表推导式:

>>> year_list=[year for year in range(0,2017)]
>>> print(year_list)

>>> year_list=[year for year in range(0,2017) if year %4==0]
>>> print(year_list)

>>> numbers=range(0,5)
>>> years=range(1,2017)
>>> cools=[(number,year) for number in numbers for year in years if number%2==0 and year%4==0]
>>> for cool in cools:
print(cool)

是不是够酷,只有被刺痛才会铭记,其实字典推导式和集合推导式也很好玩!

最后来一个特别好玩的问题,怎样找出一个序列中出现次数最多的元素呢?

>>> words
['hello', 'HELLO', 'see', 'SEE', 'work', 'WORK', 'me', 'ME', 'How', 'are', 'you', 'I', 'am', 'fine', 'thanks', 'what', 'can', 'I', 'do', 'for', 'you', 'I', 'love', 'you']
>>> from collections import Counter

>>> word_counts=Counter(words)

>>> top_three = word_counts.most_common(3)
>>> print(top_three)
[('I', 3), ('you', 3), ('hello', 1)]

Counter 可以在制表计数数据的时候很有用,请听下回分解......

0 0
原创粉丝点击