笨办法学python3pdf完整版,笨办法学python3进阶篇pdf

大家好,本文将围绕笨办法学python 3电子书下载展开说明,笨办法学python3pdf完整版是一个很多人都想弄明白的事情,想搞清楚笨办法学python3进阶篇pdf需要先了解以下几个事情。


习题11:提问

age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?")
print ("So, you're %r old, %r tall and %r heavy." %(age, height, weight))

输出结果为

How old are you?35
How tall are you?180
How much do you weigh?140
So, you're '35' old, '180' tall and '140' heavy.

问题15、16、17:文件的读写操作

问题20:函数和文件

from sys import argv

, input_file = argv

def print_all(f):
	print (f.read())
	
def rewind(f):
	f.seek(0)
	
def print_a_line(line_count, f):
	print (line_count, f.readline())

#打开文件	
current_file = open(input_file,encoding = 'utf-8')

#展示文件全部内容
print ("First let's print the whole file:\n")
print_all(current_file)

#重新定义展示文章行号
print ("Now let's rewind, kind of like a tape.")
rewind(current_file)

#展示文件的前三行内容
print ("Let's print three lines:")
current_line = 1 #设置开始行行号
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)

输出结果为

First let's print the whole file:
To all the people out there.
I say I don't like my hair.
I need to shave it off.

Now let's rewind, kind of like a tape.

Let's print three lines:
1 To all the people out there.
2 I say I don't like my hair.
3 I need to shave it off.

习题21:函数可以返回东西

def add(a, b):
    print ("ADDING %d + %d" % (a, b))
    return a + b

def subtract(a, b):
    print ("SUBTRACTING %d - %d" % (a, b))
    return a - b

def multiply(a, b):
    print ("MULTIPLYING %d * %d" % (a, b))
    return a * b

def divide(a, b):
    print ("DIVIDING %d / %d" % (a, b))
    return a / b

print ("Let's do some math with just functions!")
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print ("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height,weight, iq))

print('\n')#换行符

# A puzzle for the extra credit, type it in anyway.
print ("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq,2))))
print ("That becomes: ", what, "\n  Can you do it by hand?")

输出结果为

Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50

Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes:  -4391.0 
  Can you do it by hand?

问题24:转译字符,格式化字符串

  • 区分\、\、\n、\t
print ("Let's practice everything.")
poem = '''\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
'''
print ("--------------")
print (poem)
print ("--------------")

输出结果为

Let's practice everything.
--------------
	The lovely world
with logic so firmly planted
cannot discern 
 the needs of love
nor comprehend passion from intuition
and requires an explanation

		where there is none.

--------------

其中:
\表转译,可以用于区分双引号、单引号同句中混用情况
\\表转移,显示结果为\
\n表换行
\t表缩进

  • 区分%s、%d
five = 10 - 2 + 3 - 6
print ("This should be five: %s" % five)

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)

print ("With a starting point of: %d" % start_point)
print ("We'd have %d beans, %d jars, and %d crates." % (beans,jars, crates))

start_point = start_point / 10
print ("We can also do that this way:")
print ("We'd have %d beans, %d jars, and %d crates." %secret_formula(start_point))

输出结果为

This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.

其中:
%s代表文本
%d代表数字

问题25:分词、单词排序、删除单词

建立一个.py文档,文档内容如下,文档名称为temp.py

#文档内容分词,空格为分隔符
def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

#单词排序
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

#删除分词后的第一个单词,并打印该单词
def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print (word)

#删除分词后的最后一个单词,并打印该单词
def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print (word)
 
 #调用分词和排序函数
def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

#调用分词、打印分此后的第一和最后一个单词函数
def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

#调用排序句子和打印第一和最后一个单词的函数
def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)
  • 调用函数break_words
#调用文档
import temp

sentence = "All good things come to those who wait."
#调用函数
words = temp.break_words(sentence)
#打印结果
words

   输出结果为

['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
  • 调用函数sorted_words
#调用函数
sorted_words = temp.sort_words(words)
#打印结果
sorted_words

   输出结果为

['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
  • 调用函数print_first_words
#调用函数
temp.print_first_word(words)

   输出结果为

All
  • 调用函数print_last_words
#调用函数
temp.print_last_word(words)

   输出结果为

wait.
  • 输出此时的words
#words
['good', 'things', 'come', 'to', 'those', 'who']

问题31:通过input信息,进行if···else···判断

建立一个.py文档,文档内容如下,文档名称为temp.py

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

door = 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 = 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 probably better. Bear runsaway." % bear)
        
elif door == "2":
    print ("You stare into the endless abyss at Cthulhu's retina.")
    print ("1. Blueberries.")
    print ("2. Yellow jacket clothespins.")
    print ("3. Understanding revolvers yelling melodies.")
    
    insanity = 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 around and fall on a knife and die. Good job!")

输出结果为

  • 调用思路一
#调用文档
import temp

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

> 1
There's a giant bear here eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.

> 2
The bear eats your legs off. Good job!
  • 调用思路二
You enter a dark room with two doors. Do you go through door #1 or door #2?

> 1
There's a giant bear here eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.

> 1
The bear eats your face off. Good job!

习题32: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)

输出结果为

#while循环
At the top i is 0
Numbers now:  [0]
At the bottom i is 1#循环执行1次
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2#循环执行2次

At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3#循环执行3次

At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4#循环执行4次

At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5#循环执行5次

At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6#循环执行6次

The numbers:
#for循环 
0
1
2
3
4
5

习题35:分支和函数

from sys import exit
#定义函数一
def gold_room():
    print ("This room is full of gold. How much do you take?")
    
    next = input("> ")
    
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")
        
    if how_much < 50:
        print ("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")

#定义函数二        
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 = 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 ("The 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 means.")

#定义函数三
def cthulhu_room():
    print ("Here you see the great evil Cthulhu.")
    print ("He, it, whatever stares at you and you go insane.")
    
    next = 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 left.")
    print ("Which one do you take?")
    
    next = input("> ")
    
    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")

#调用函数五
start()

输出结果为
执行过程:调用函数五–输入left–调用函数二–输入taunt bear–输入open door–调用函数一–输入asf–执行结束

You are in a dark room.
There is a door to your right and left.
Which one do you take?

> left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?

> taunt bear
The bear has moved from the door. You can go through it now.

> open door
This room is full of gold. How much do you take?

> asf
Man, learn to type a number. Good job!

习题39:列表的操作

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(' ')  #将ten_things已空格为分隔符进行分词

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

#以stuff长度为循环条件,不等于10时继续循环,等于10时循环结束
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)  #打印循环结束后的stuff
print ("Let's do some things with stuff.")
print (stuff[1]) #打印stuff列表中的位置为1的元素,起始位置为0
print (stuff[-1])  #打印stuff列表最后一个元素
print (stuff.pop()) #删除stuff列表最后一个元素,并打印该元素
print (' '.join(stuff)) #用空格间隔stuff中的元素
print ('-'.join(stuff[3:5])) #选中stuff中位置为3.4的元素,并用-间隔符间隔

输出结果为

Wait there's not 10 things in that list, let's fix that.
Adding:  Boy
There's 7 items now.
Adding:  Girl
There's 8 items now.
Adding:  Banana
There's 9 items now.
Adding:  Corn
There's 10 items now.

There we go:  ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']

Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone-Light

习题40:字典

cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city(themap, state):
    if state in themap:
        return themap[state]
    else:
        return "Not found."
        
#将函数写入字典中
cities['_find'] = find_city

while True:
    print ("State? (ENTER to quit)")
    state = input("> ")
    if not state: 
        break
    city_found = cities['_find'](cities, state)
    print (city_found)

其中:

  • cities['_find'] = find_city
    find_city函数写入cities字典中_find的位置,_findfind_city函数形成键值对
  • city_found = cities['_find'](cities, state)
    cities['_find']找出cities字典中_find的位置的值,为find_city函数,调用函数,函数的参数为(cities, state),并将最终结果赋值给city_found

输出结尾为

State? (ENTER to quit)

> CA
San Francisco
State? (ENTER to quit)

> FL
Jacksonville
State? (ENTER to quit)

> O
Not found.
State? (ENTER to quit)

> OR
Portland
State? (ENTER to quit)

> YT
Not found.
State? (ENTER to quit)

附录

提示:这里提供一些代码网站
例如:
1、bitbucket.org
2、github.com
3、launchpad.net
4、koders.com
阅读这些网站中以.py结尾的文件

《笨办法学 Python》(Learn Python The Hard Way,简称 LPTHW)是 Zed Shaw 编写的一本 Python 入门书籍

  • 18
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值