2016年5月12日 星期四

Python Programming Tutorial

Nice Python Programming Tutorial
IDE use Pythom for 30 days free


https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_

All my videos - https://thenewboston.com/videos.php
Support my tutorials - https://www.patreon.com/thenewboston
Forum - https://thenewboston.com/forum/

Bucky Roberts - https://thenewboston.com/profile.php?...
Facebook - https://www.facebook.com/TheNewBoston...
GitHub - https://github.com/buckyroberts
Google+ - https://plus.google.com/+BuckyRoberts
LinkedIn - https://www.linkedin.com/in/bucky-rob...
Reddit - https://www.reddit.com/r/thenewboston/
Twitter - https://twitter.com/bucky_roberts

**

buttrack = 25while buttrack < 35:
    print (buttrack)
    buttrack += 1 

**

magicNumber =26for n in range(101):
    if n is magicNumber:
        print (n,"This is MagicNumber")
        break    else:
        print (n , "Next")

**

def beef():
    print ("This is Beef function")

def count(btm=10):
    sum_num = btm * 555    print ("Sum is " , sum_num)

for x in  range(10):
    beef()
    count(15)
    count()

**

def add_number(*args):
    total = 0    for a in args:
        total += a
    print (total)

add_number(10,55,555555555555)

**

def health_calulator(age, tall, weigth):
    answer = age*2 + (tall+2) + (weigth/5)
    print answer

array_Peter = [10,30,60]

health_calulator(*array_Peter)
health_calulator(array_Peter[0], array_Peter[1], array_Peter[2])

**

classmate = {'Tony':' is handsome and nice', 'Emma':' sits behind me', 'Peter':' asks too many questions'}
print (classmate)

for k, v in classmate.items():
    print k + " - " + v

**
版本中無法使用urllib.request
import random
import urllib.request

def download_url(url):
    name = random.randrange(1,100)
    full_name = str(name) + ".jpg"    urllib.request.urlretrieve(url,full_name)

download_url("https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg")

**

fw = open("sample.txt", "w")
fw.write("Hello world\n")
fw.write("second line")
fw.close()

fr = open("sample.txt", "r")
text = fr.read()
print (text)
fr.close()

**

while True:
    try:
        number = int(input("What's your favor number?\n"))
        print (10/number)
        break    except ValueError:
        print ("Make sure and enter a number.")
    except NameError:
        print ("Make sure and enter a number.")
    except ZeroDivisionError:
        print ("Make sure and enter a number.")
    except :
        break    finally:
        print ("loop complete")

**

class Enemy:
    life = 4
    def attack(self):
        self.life -= 1
    def checklife(self):
        if self.life <= 0:
            print ("I am dead")
        else:
            print (str(self.life) + " life life")

enemy = Enemy()
enemy.attack()
enemy.checklife()

**

 31 - Class vs Instance Variables


class Girl:
    gender = "Female"
    def __init__(self,name):
        self.name = name

r = Girl("Rachel")
print (r.gender)
print (r.name)

**

32 - Inheritance

class parents():
    def print_last_name(self):
        print ("Roberts")

class child(parents):
    def print_first_name(self):
        print ("Bucky")

    def print_last_name(self):
        print ("James")

Bucky = child()
Bucky.print_first_name()
Bucky.print_last_name()
**

33 - Multiple Inheritance

class mario():

    def move(self):
        print ("I am moving")

class shroom():

    def eat_shroom(self):
        print ("I am Big!")

class big_mario(mario, shroom):
    pass
bm = big_mario()
bm.eat_shroom()
bm.move()
**

34 - threading

import threading

class BuckysMessager(threading.Thread):

    def run(self):
        for _ in range(10):
            print (threading.current_thread().getName())


x = BuckysMessager(name="Send out messages")
y = BuckysMessager(name="Receive messages")
x.start()
y.start()
**

38 - Unpack List or Tuples

def drop_first_last(grades):
    first, *middle, last = grades
    avg = sum(middle) / len(middle)
    print (avg)


list = [10,20,50,44,99,77,99,55,33,11]
drop_first_last(list)
**
換python版本
File -> Setting -> Project Interpreter -> python.exe版本
**

39 - Zip (and yeast infection story)

first = ["Peter", "Bucky", "James"]
last = ["Lee", "Switer", "Leborn"]

name = zip(first, last)
for a,b in name:
    print(a,b)
**

40 - Lamdba
answer = lambda x : x*7
print(answer(5))

**

41 - Min, Max, and Sorting Dictionaries
stocks = {
    'GOOG':520.14,    'FB':75.16,    'AMZN':56.81,    'AAPL': 76.55,    'GAMI': 456.16}

print(min(zip(stocks.values(),stocks.keys())))
print(max(zip(stocks.values(),stocks.keys())))
print(sorted(zip(stocks.values(),stocks.keys())))

**

42 - Pillow
can't pip install pillow

**

49 - struct
from struct import  *

packed_data = pack('iif', 4,5,6.5)
print(packed_data)
print(calcsize('i'))
print(calcsize('f'))
print(calcsize('iif'))

original_data = unpack('iif',packed_data)
print(original_data)

**

50 - map
imcome = [10,35,94]

def double_money(dollars):
    return dollars*2
new_list = list(map(double_money,imcome))
print(new_list)

**

51 - Bitwise Operators
a=50   #110010b=25   #011001c=a&b  #010000
print(c)

d=240  #11110000e=d>>2 #00111100
print(e)

**

52 - Finding Largest or Smallest Items
import heapq

grades = [35, 67, 94, 54, 66, 54, 21]
print(heapq.nlargest(3,grades))


stocks = [
    {'ticker': 'AAPL', 'price': 201},    {'ticker': 'GOOG', 'price': 504},    {'ticker': 'FB', 'price': 45},    {'ticker': 'AMZN', 'price': 755},    {'ticker': 'TUNA', 'price': 95}
]

print(heapq.nsmallest(2, stocks, key=lambda  stock: stock['price']))

**

53 - Dictionary Calculations
stocks = {
    'AAPL': 201,     'GOOG': 504,     'FB': 45,     'AMZN': 755,     'TUNA': 95}

min_price = min(zip(stocks.values(), stocks.keys()))
print(min_price)

**

54 - Finding Most Frequent Items
from collections import Counter

text = "Learning proverbs can also help you to understand the way that people in English-speaking cultures think about the world."\
       "Proverbs can also give you good example sentences which you can memorize and use as models for building your own sentences."
words = text.split()

counter = Counter(words)
top_3 = counter.most_common(3)
print(top_3)

**

55 - Dictionary Multiple Key Sort
from operator import itemgetter

users = [
    {'fname': 'Bucky', 'lname': 'Roberts'},    {'fname': 'Tom', 'lname': 'Roberts'},    {'fname': 'Bernie', 'lname': 'Zunks'},    {'fname': 'Jenna', 'lname': 'Hayes'},    {'fname': 'Sally', 'lname': 'Jones'},    {'fname': 'Amanda', 'lname': 'Roberts'},    {'fname': 'Tom', 'lname': 'Williams'},    {'fname': 'Dean', 'lname': 'Hayes'},    {'fname': 'Bernie', 'lname': 'Barbie'},    {'fname': 'Tom', 'lname': 'Roberts'},]

for x in sorted(users, key=itemgetter('lname', 'fname')):
    print(x)

**

56 - Sorting Custom Objects

from operator import attrgetter

class User:

    def __init__(self,x,y):
        self.name=x
        self.user_id=y

    def __repr__(self):
        return self.name + ":" + str(self.user_id)


users = [
    User('Bucky', 43),    User('Sally', 48),    User('Tuna', 34),    User('Tom', 15),    User('Jerry', 55),
]

for user in users:
    print(user)

print('--------')
for user in sorted(users, key=attrgetter('name')):
    print(user)

print('--------')
for user in sorted(users, key=attrgetter('user_id','name')):
    print(user)
**
**
**
**
**
**
**
**

沒有留言:

張貼留言