dengdaiyemanren / python

python知识
8 stars 1 forks source link

hardwaytopython #1

Open dengdaiyemanren opened 8 years ago

dengdaiyemanren commented 8 years ago

http://learnpythonthehardway.org/book/

习题32 循环和列表


the_count = [1,2,3,4,5]

fruits = ['apples','oranges','pears','apricots']

change = [1,'pennies',2,'dimes',3,'quarters']

for number in the_count:
    print "This is count %d" %number

for fruit in  fruits:
     print "A fruit of type:%s" %fruit

for i in change:
    print "I got %r" %i

elements = []

for i in range(0,6):
   print "Adding %d to the list" %i
   elements.append(i)

for i in elements:
    print "Elements was: %d" %i
dengdaiyemanren commented 8 years ago

习题31 做出决定

print "You enter a dark room with two doors. Do you go through door #1 or door #2?"

door = raw_input(">")

if door == "1":
    print "There's a giant bear here eating a cheese cake. What do you do ?"
    print "1. Take the cake."
    print "2. Scream at the bear"
    bear = raw_input(">")

    if bear == "1":
        print "The bear eats your face off. Good job"
    elif bear == "2":
        print "The bear eats your legs off. Good job"
    else:
        print "Well,doing %s is probaly better. Bear runs away." %bear
elif door == "2":          
    print "You stare into the endless abyss at "
    print "1.BlueBerries"
    print "2.Yellow jacket clothespins"
    print "3.Understanding revolvers yelling melodies"

    insanity  = raw_input(">")

    if insanity == "1" or insanity  =="2":
        print "Your body survives powered by a mind of jello. Good job!"
    else:
        print "The insanity rots your eyes into a pool of muck. Good job!"
else:
    print "You stumble aroud and fall on a knife and die. Good job!"
dengdaiyemanren commented 8 years ago

习题30 else 和 if

people = 10
cars = 40
buses = 15

if cars > people:
    print "We should take the cars"
elif cars < people:
    print "We should not task the cars."
else:
    print "We can't decide."
''''    
dengdaiyemanren commented 8 years ago

习题29 if 语句

people  = 20

cats = 30

dogs = 15

if people < cats:
    print "Too many cats! The world is doomed!"

if people <= cats:
    print "Too many cats! The world is doomed!"

if people >= cats:
    print "Too many cats! The world is doomed!"
dogs += 5
dengdaiyemanren commented 8 years ago

习题 28 布尔表达式练习

print True and True

print False and False

print 1==1 and 2==1

print "Test" == "Test"

print 1==1 or 2 != 1

print "test" == "testing"

print not(True and False)

print not(10 == 1 or 1000 == 1000)

print "test" and "test"
dengdaiyemanren commented 8 years ago

习题15 读取文件

from sys import argv

script,filename = argv

txt = open(filename)

print "Here's your file %r" %filename

print txt.read()

print "Type the filename again:"
file_again = raw_input(">")

txt_again = open(file_again)

print txt_again.read()

from os.path import exists
dengdaiyemanren commented 8 years ago

习题16 读写文件

from sys import argv

script, filename = argv

print "We're going to erase %r" %filename
print "If you don't want that, hit CTRL-C"
print "If you do want that, hit Return"

raw_input("?")

print "Opening the file..."
target = open(filename,"w")

print "Truncating the file. Goodbye"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1:");
line2 = raw_input("line 2:");
line3 = raw_input("line 2:");

print "I'm going to write these to the file"

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close();
dengdaiyemanren commented 8 years ago

17,18,19

dengdaiyemanren commented 8 years ago

习题33 while循环

i = 0
numbers = []

while i<6:
    print "At the top i is %d" %i
    numbers.append(i)

    i = i +1
    print "Numbers now:",numbers
    print "At the bottom i is %d" %i
    print "The numbers:"

    for num in numbers:
        print num  
dengdaiyemanren commented 8 years ago

习题35 分支和函数

from sys import exit

def gold_room():
    print "This room is full of gold. How much do you task?"

    next = raw_input(">")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, lern to type a number") 

    if how_much < 50:
        print "Nice, you're not greedy,you win"
        exit(0)
    else:
        dead("You greedy bastarte!")

def bear_room():
    print "There is a bear here."   
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door"
    print "How are you going to move the bear?"
    bear_moved = False

    while True:
        next = raw_input(">")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off")
        elif next == "taunt bear" and not bear_moved:
            print "This bear has moved from the door. You can go through it now"
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print "I got no idea what that mean"      

def cthulhu_room():
    print "Here you see the great evil cthulhu"
    print "He,it, whatever stares at you and you go insane"
    print "Do you flee for your life or eat your head?"

    next = raw_input(">")

    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulhu_room()

def dead(why):
    print why, "Good job!"
    exit(0)

def start():
    print "You are in a dark room."
    print "There is a door to your right and I left."
    print "Which one do you take?"

    next = raw_input(">")

    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room util you starve.")

start()
dengdaiyemanren commented 8 years ago

习题38 列表的操作

ten_things  = "Apples Oranges Crows Telephone Light Sugar"

print "Wait there's not 10 things in that list, let's fix that"

stuff = ten_things.split(' ')

more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop()
    print "Adding:",next_one
    stuff.append(next_one)
    print "There's %d items now." %len(stuff)

print "There we go:", stuff
print "Let's do some things with stuff."

print stuff[1]
print stuff[-1] # whoa! fancy
print stuff.pop()
print ''.join(stuff) # what ? cool
print '#'.join(stuff[3:5]) # super stellar!
dengdaiyemanren commented 8 years ago

习题39 字典,可爱的字典

# create a mapping of state to abbreviation

states = {
          'Oregon':'OR',
          'Florida':'FL',
          'Calfornia':'CA',
          'New York':'NY',
          'Michigan':'MI'
          }
# create a basic set of states and some  cities in them

cities={
        'CA':'San Francisco',
        'MI':'Detroit',
        'FL':'Jacksonville'
        }

# add som cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

#print out some cities

print '-' * 10
print "NY State has:",cities['NY']
print "OR State has:",cities['OR']

# print some states
print '-' *10
print "Michigan has:",states['Michigan']
print "Florida has:",states['Florida']

# do it by using the state then cities dict
print '-'*10
for state,abbrev in states.items():
    print "%s is abbreviated %s" %(state,abbrev)

#print every city in state
print '-'*10
for abbrev,city in cities.items():
    print "%s has the city %s" %(abbrev,city)

# now do both at the same time
print '-'*10
for state,abbrev in states.items():
    print "%s state is abbreviated %s and has city %s"%(state,abbrev,cities[abbrev])   

print '-' *10

# safely get a abbreviction by state that might not be there 
state = states.get("Texas",None)

if not state:
    print "Sorry,no Texas."
# get a city with a default value
city = cities.get('TX','Does Not Exist')
print "The city for the state 'TX'is %s" %city
dengdaiyemanren commented 8 years ago

习题40 模块,类和对象


class MyStuff(object):

    def __init__(self):
        self.tangerine = "And now a thousand years between"
    def apple(self):
        print "I AM CLASSYS APPLES"

class Song(object):
     def __init__(self,lyrics):
         self.lyrics = lyrics
     def sing_me_a_song(self):
         for line in self.lyrics:
             print line
happy_bday = Song(["Happy birthday to you",
                   "I don't want to get sued",
                   "So I'll stop right there"])
bulls_on_parade = Song(["The rally around the family",
                        "With pockets full of shells"])
happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()                       
dengdaiyemanren commented 8 years ago

习题42 对象类及从属关系

class Animal(object):
    pass

## ??
class Dog(Animal):

    def __init__(self, name):
        ## ??
        self.name = name

## ??
class Cat(Animal):

    def __init__(self, name):
        ## ??
        self.name = name

## ??
class Person(object):

    def __init__(self, name):
        ## ??
        self.name = name

        ## Person has-a pet of some kind
        self.pet = None

## ??
class Employee(Person):

    def __init__(self, name, salary):
        ## ?? hmm what is this strange magic?
        super(Employee, self).__init__(name)
        ## ??
        self.salary = salary

## ??
class Fish(object):
    pass

## ??
class Salmon(Fish):
    pass

## ??
class Halibut(Fish):
    pass

## rover is-a Dog
rover = Dog("Rover")

## ??
satan = Cat("Satan")

## ??
mary = Person("Mary")

## ??
mary.pet = satan

## ??
frank = Employee("Frank", 120000)

## ??
frank.pet = rover

## ??
flipper = Fish()

## ??
crouse = Salmon()

## ??
harry = Halibut()  
dengdaiyemanren commented 8 years ago

习题44 继承和合成

## 隐式继承
class Parent(object):

    def implicit(self):
        print "Parent implicit()"
class Child(Parent):
    pass
dad = Parent()
son = Child()

dad.implicit()
son.implicit()   

## 显式覆盖

class Parent1(object):

    def override(self):
        print "Parent override()"
class Child1(Parent):
    def override(self):
        print "CHILD override()"

dad = Parent1()
son = Child1()

dad.override()
#dad.implicit()

son.override()
#son.implicit()

## 在运行前或运行后替换

class Parent3(object):

    def altered(self):
        print "Parent altered"
class Child3(Parent3):

    def altered(self):
        print "CHILD,BEFORE PARENT altered()"
        super(Child3,self).altered()
        print "Child , After parent altered()"
dad = Parent3()
son = Child3()

dad.altered()
son.altered()

## 组合 
class Other00(object):

    def override(self):
        print "OTHER override()"

    def implicit(self):
        print "OTHER implicit()"

    def altered(self):
        print "OTHER altered()"

class Child00(object):

    def __init__(self):
        self.other = Other00()

    def implicit(self):
        self.other.implicit()

    def override(self):
        print "CHILD override()"

    def altered(self):
        print "CHILD, BEFORE OTHER altered()"
        self.other.altered()
        print "CHILD, AFTER OTHER altered()"

son = Child00()

son.implicit()
son.override()
son.altered() 
dengdaiyemanren commented 8 years ago

习题47 自动化测试

class Room(object):

    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.paths = {}

    def go(self, direction):
        return self.paths.get(direction, None)

    def add_paths(self, paths):
        self.paths.update(paths)       

from numpy.testing import *

def test_room():
    gold = Room("GoldRoom",
                """This room has gold in it you can grab. There's a
                door to the north.""")
    assert_equal(gold.name, "GoldRoom")
    assert_equal(gold.paths, {})

def test_room_paths():
    center = Room("Center", "Test room in the center.")
    north = Room("North", "Test room in the north.")
    south = Room("South", "Test room in the south.")

    center.add_paths({'north': north, 'south': south})
    assert_equal(center.go('north'), north)
    assert_equal(center.go('south'), south)

def test_map():
    start = Room("Start", "You can go west and down a hole.")
    west = Room("Trees", "There are trees here, you can go east.")
    down = Room("Dungeon", "It's dark down here, you can go up.")

    start.add_paths({'west': west, 'down': down})
    west.add_paths({'east': start})
    down.add_paths({'up': start})

    assert_equal(start.go('west'), west)
    assert_equal(start.go('west').go('east'), start)
    assert_equal(start.go('down').go('up'), start)   
dengdaiyemanren commented 7 years ago

json在线编辑

http://www.bejson.com/jsoneditoronline/

dengdaiyemanren commented 5 years ago
# -*- coding: utf-8 -*-

##1、读取文件夹A
##2、读取文件夹B
##比较A,B下面的文件,通过文件名比较

##例举A文件夹下相同的文件名及路径
##A文件夹下存在而B文件夹没有的文件名及路径
##B文件下存在而A文件夹下没有的文件名及路径

#from sys import argv
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QTextEdit
import os

def readFile(filedirpath,listfile,prefix):

    for parent, dirnames, filenames in os.walk(filedirpath,  followlinks=True):

       ## for dirname in dirnames:
         ##   filedir_path = os.path.join(parent, dirname)
          ##  print('文件夹完整路径:%s\n' % filedir_path)
          ##  readFile(filedir_path)

        for filename in filenames:

           print(parent)
           file_path1 = os.path.join(parent, filename)
           print('文件名:%s' % filename)
           print('文件完整路径:%s\n' % file_path1)
           listfile.append(file_path1[len(prefix)+1:])

           ## print('文件夹名:%s' % dirname)
           ## print('文件夹完整路径:%s\n' % filedir_path)

def  show(resulta,reslutb,resulteq):

    app=QApplication(sys.argv)
    widget = QWidget()
    widget.setWindowTitle("QTextEdit控件使用")   
    widget.resize(500,600)
    widget.textEdit=QTextEdit()
    widget.textEdit.setPlainText("Hello PyQT5单击按钮")
    widget.show()
    app.show()

if __name__ == "__main__":

    #filename = argv

   ## print ("We're going to erase %r" %filename)
    filepath1 = input("请输入文件1路径")
    print ("你输入的文件1=" +filepath1)

    filepath2 = input("请输入文件2路径")
    print ("你输入的文件2=" +filepath2)

    list1 = []

    list2 = []
   ## file1 = open(filepath1,"r")
   ## file2 = open(filepath2,"r")

    ##print (file1.__name__)

    readFile(filepath1,list1,filepath1)
    print("list1",list1)
    readFile(filepath2,list2,filepath2)
    print("list2",list2)

    listeq = []
    listacon = []
    listbcon = []

    for i in list1:
        lista = i
        if list2.count(lista) == 0:
          listacon.append(lista)
        if list2.count(lista) > 0:
          listeq.append(lista)

    for j in list2:
        listb = j
        if list1.count(listb) == 0:
          listbcon.append(listb)

    print("listeq:",listeq) 

    print("listacon:",listacon)     

    print("listbcon:",listbcon)

    #show(listacon,listbcon,listeq)

    app=QApplication(sys.argv)
    widget = QWidget()
    widget.setWindowTitle("QTextEdit控件使用")   
    widget.resize(500,600)
    widget.textEdit=QTextEdit()
    widget.textEdit.setPlainText("Hello PyQT5单击按钮")
    widget.show()
    sys.exit(app.exec_())
dengdaiyemanren commented 5 years ago

https://www.cnblogs.com/archisama/p/5444032.html