程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

《笨办法学python3》习题0-36与部分笔记

发布于2020-03-31 14:44     阅读(1561)     评论(0)     点赞(5)     收藏(1)


笔记目的

最近刚开始从python最基础的学起来,本文内容主要是为了记录一些书上遇到的问题,但主要注释在了代码中,以供自己学习,目录大部分是会按照书上目录来记录,内容或许对大家新学python的有所帮助,使用系统是windows。

习题0

由于我不完全是代码小白,所以在编辑器我直接使用了Visual Studio Code,如果大家为了多接触一些不同的代码(C, C++, JS, Java),或者单纯码一些代码,可以使用这个编辑器,它通过下载不同插件、扩展来实现同一编辑器上编写不同代码。

习题5

有一些代码行我没有输入,但如果是初学者练习的话我建议反复敲打是可以加快你对基础代码的熟悉程度。

# some basic details
name = 'Ivan Don'
age = 22 
height = 168 #cm
my_eyes = 'black'

print(f"Let's talk about {name}.")

total = age + height
print(f"If I add my age {age} and my height {height}, and I will get ${total}")

目前,总结出五种比较基础的文字和字符串(或者整数等)混合输出的方法,根据喜好、需求使用。

# 五种方法打印字符串与变量
#1
print(f"Let's talk about {name}.")
#2
print("Let's talk about",name,".")
#3
print("Let's talk about"+name+".")
#4
x = "Let's talk about {}."
print(x.format(name))
#5
print("Let's talk about %s" %name)

习题7

print("Mary had a little lamb.")
print("Its fleece was white as {}.".format("snow"))
print("And everywhere that Mary went.")
print("."*10) #what'd that do

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "b"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

print(end1+end2+end3+end4+end5+end6,end=' ') 
print(end7+end8+end9+end10+end11+end12)

在python中,print是默认结尾换行,相当于java中的println,加了end=’ '就相当于结尾不换行,且‘ ’可以加入任何你想让它在结尾输出的内容。

习题8

formatter = "{} {} {} {}"
print(formatter.format(1,2,3,4))

print(formatter.format("one","two","three","four"))
print(formatter.format(True,False,False,True))
print(formatter.format(formatter,formatter,formatter,formatter))
print(formatter.format(
    "Try your",
    "Own text here",
    "Maybe a poem",
    "Or a song about fear"
    ))

在这里,有几个{}就必须给几个内容,且使用format会被新的内容替代。

习题9

# Here's some new strange stuff, remeber type it exactly.

days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

print("Here are the days: ", days)
print("Here are the months: ", months)

print('''
There is something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
''')

三个’不仅可以做注释,还可以在print的时候自动换行,或者使用三个"代替。

习题10

tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line"
backslash_cat = "I'm \\ a \\ cat"

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)

这一习题中介绍了一些转义字符(列了三个看名字没懂的):

print("I'm a bs\ba")    #\b退格符,在后面还有字符的时候,会删除其前面一个的符号
print("I'm a bs\faa")    #退纸符,会将其后面的字符转到下一行并接着上一行字符结束的地方继续
print("\a")     #响铃符,执行之后电脑会发出声响,可以打开电脑声音试一试

习题11-13

#--------------------No.11--------------------
print("How old are you?", end=' ') #end是为了结尾不换行,里面可以使用任何字符串
age = input()
print(f"So you're {age} years old.")

#------------------No.12------------------------
age = input("How old are you?") # input里面可以直接放出想要打印的字符串,并继续输入
print(f"So you're {age} years old.")

#-------------------No.13-------------------------------
from sys import argv
script, first, second, third = argv
print("The script is called:",script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

如果有不会的问题 终端输入 python -m pydoc xxx (xxx可以是input等)

习题15

from sys import argv

script, filename = argv
txt = open(filename)

print(f"Here is your file {filename}:")
print(txt.read())

print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())

这里你可以在你VScode中python运行的文件位置新建一个txt文件,如果py脚本的不在终端显示文件位置下,可以参考下图中的输入方法(exercise拼错了对不起)。
cmd输入

习题16

from sys import argv
script, filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C")
print("If you do want that, hit RETURN.")

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 = input("line1:")
line2 = input("line2:")
line3 = input("line3:")

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")

#---第二种
target.write(line1+'\n'+line2+'\n'+line3+'\n')

print("And finally we close it.")
target.close()

打开文件读取的步骤简单的梳理一下就是:

#先告诉他要看什么文件
script, filename = argv
#接着要打开这个文件
txt = open(filename,'r')
#再是显示这个文件
print(txt.read())

习题问题:“如果用了‘w’参数,truncate()还是必须得吗?”
答案:是,我们可以了解一下涉及到truncate的流程图(下图所示),这个在网上也可以查到有人写过,看懂了之后就知道为什么答案为是。
流程图
关于open()函数中第二个参数解读(只读,只写,读写),可以参考以下链接,每一个都列举了例子:
https://blog.csdn.net/jiruiYang/article/details/53887455

r+与w+的主要区别应该在于:使用前者,在写入的时候,写多少才覆盖原文件内容多少,比如原文是abcdef,使用r+输入123,结果为123def;使用后者,写一点就把原本的都覆盖,结果则为123。

习题17

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}") 

indata = open(from_file).read()

print(f"The input file is {len(indata)} bytes long.")
print(f"Does the output file exist? {exists(to_file)}")

print("Ready, hit RETURN to continue, CTRL-C to abort.")
input(">")

out_file = open(to_file,'w')
out_file.write(indata)

print("Done!")
out_file.close()

cmd中也可以使用echo “Test” > test.txt 创建新文件且写入,在linux中的cat操作相当于windows中的ype。
习题问题:“将上述代码写成一行。”
答案:

outfile = open('test_out.txt','w').write(open('test.txt').read())

习题18、19

这两个题目没有太值的注意的地方。

#-----------------No.18-------
# *args pointless 属于list
def print_two(*args):
    arg1, arg2 = args #将参数进行解包
    print(f"arg1:{arg1}, arg2:{arg2}")
def print_two_again(arg1,arg2):
    print(f"arg1:{arg1}, arg2:{arg2}")

def print_one(arg1):
    print(f"arg1:{arg1}")

def print_nothing():
    print("print it directly")

print_two("ivan1","slyvia1")
print_two_again("ivan1","slyvia1")
print_one("onlyOne")
print_nothing()

#----------------No.19------------------------
def  cheese_cracker(cheese_count, boxes_of_cracker):
    print(f"""
    You have {cheese_count} cheeses!
    You have {boxes_of_cracker} boxes of crackers!
    Man that's enough for a party!
    Get a blanket!
    """)
print("First method\n")
cheese_cracker(20,30)

print("sec\n")
x = 10
y = 50
cheese_cracker(x,y)

print("third\n")
cheese_cracker(10+20,5+6)

print("please enter:")

cheese_cracker(int(input('cheese count:')),int(input('crackers count:')))

习题20

from sys import argv

input_file = input('输入要打开的文件:')

# 打印文件中所有内容
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(),end='') # readline中原本包含\n, 如果想要消除,可在最后增加end=''

# 打开当前文件
current_file = open(input_file)
print("the whole content:")
print_all(current_file) # 输出当前文件中所有内容
print("\n")

print("rewind the file, let the pointer go to the beginning.\n")
rewind(current_file)
print("Print two lines:\n")
current_line = 1
print_a_line(current_line,current_file)
current_line+=1
print_a_line(current_line,current_file)

readline()会从头读到“\n”,然后停住,下次再被调用的时候,文件指针仍在那里,所以会接着第二行开始。

习题21

# add two number
def add(a,b):
    print(f"ADDING {a} + {b}")
    return a+b
    
#substract two number
def substract(a,b):
    print(f"SUBSTRACT {a} - {b}")
    return a-b
def divide(a,b):
    print(f"DIVIDE {a} / {b}")
    return a/b
def multiply(a,b):
    print(f"MULTIPLY {a} * {b}")
    return a*b

age = add(30,5)
height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)

print(f"age = {age},height = {height}, weight = {weight}, iq = {iq}")
print("A puzzle")
what = add(age,substract(height,multiply(weight,divide(iq,2))))
print("It is what equals to ",what)

习题23

#之前是import argv from sys
import sys
script, encoding, error = sys.argv

def main(language_file, encoding, errors):
    line = language_file.readline()
    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
    next_lang = line.strip()
    raw_bytes = next_lang.encode(encoding, errors = errors)
    cooked_string = raw_bytes.decode(encoding,errors = errors)
    print(raw_bytes,"<==>",cooked_string)

languages = open("execise/languages.txt",encoding = "utf-8")
main(languages, encoding, error)

1、strip()函数的用法:去除行中首尾所要去除的内容
传递参数为空值,则是去除行中首尾的空格,以strip(0)为例子,line=“003210a012300”,则line.strip(0) == “3210a0123”.

2、encode和decode:代码中 next_lang其实与cooked_string是相等的,均为字符串。对于编码(encode)和解码(decode),可以理解为编码是为了让机器知道我们在说什么,所以编码之后输出是字节串,因此解码之后输出的就是字符串,为了让我们懂得机器在说什么。函数中的第二个error参数主要有五种:strict, replace, ignore, xmlcharrefreplace, backslashreplace,除此之外还可以使用codecs.regsiter_error注册自己的错误处理程序。

3、为什么使用Unicode:解决ASCII不同能同时编码多个国家的语言。

习题24

print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')

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("-----------")

five = 10-2+3-6
print(f"This should be five:{five}")

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

start_point = 10000

# let these three variables be the value of the function that returns
beans, jars, crates= secret_formula(start_point)

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

start_point = start_point / 10
# formula is an array of numbers
formula = secret_formula(start_point)
print("We'd have {} beans, {} jars, and {} crates".format(*formula))

这个习题在书中的结果感觉有个小问题,结果的第二三行中间应该会空开一行,因为print自带换行,且后面又有“\n”,按理是回车了两行。

习题25

# stuff is a sentence, which is also a list of string with space in it
def break_word(stuff):
    """This function will break up words for us."""
    # words is an array of strings
    words = stuff.split(' ')
    return words

#words is an array of strings (short strings without any space)
def sort_words(words):
    """Sort 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_word(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_word(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

这个习题需要在终端进行交互操作,自己安装其他编辑器的可能会出现无法import自己写的脚本,我们可以通过在终端输入:

>>>import sys #先导入一个最基础的sys
>>>sys.path #查看这些库和包都被放在哪里
>>>sys.path.append(r"H:\VScode") #把你自己写的脚本所在目录加进去,就可以了!

但这种方法只适用于一次性,如果脚本需要反复多人多次使用的话,就直接把它们放在库和包所在的默认目录底下。

习题26

考试内容网上都可以找到,我就直接把答案贴出来,但我没有注释。
现在编辑器都直接把大部分问题给你直接提示出来了,而且运行出错之后问题也很好修改。

from sys import argv
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()

print(f"So, you're {age} old, {height} tall and {weight} heavy.")

script, filename = argv

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

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

txt_again = open(file_again)

print(txt_again.read())


print('Let\'s practice everything.')
print('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

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("--------------")


five = 10 - 2 + 3 - 6
print(f"This should be five: {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)

# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
# it's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10

print("We can also do that this way:")
formula = secret_formula(start_point)
# this is an easy way to apply a list to a format string
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))



people = 20
cats = 30
dogs = 15


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

if people > cats:
    print("Not many cats! The world is saved!")

if people < dogs:
    print("The world is drooled on!")

if people > dogs:
    print("The world is dry!")


dogs += 5

if people >= dogs:
    print("People are greater than or equal to dogs.")

if people <= dogs:
    print("People are less than or equal to dogs.")


if people == dogs:
    print("People are dogs.")

习题29、31

没什么问题看书就可以了。

----------------No.29------------
people = 30
cars = 40
trucks = 15

if cars > people:
    print("We should take the cars.")
elif cars < people:
    print("We should not take the cars.")
else:
    print("We can't decide.")

if trucks > cars:
    print("That's too many trucks.")
elif trucks < cars:
    print("May be we could take the trucks.")
else:
    print("We still can't decide.")

if people > trucks:
    print("Alright, let's just take the trucks.")
else:
    print("Fine,let's stay home then.")

#-----------No.31------------
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 gaint bear here eating a cheese cake.
    What do you do?
    1. Take the cake.
    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 leg off. Good job!")
    else:
        print(f"""Well, doing {bear} is probably better.
        The bear runs away""")

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 in range(1,3):
        print("Your body survives powered by a mind of jello.")
        print("Good job!")
    else:
        print("The insanity rots your eyes into a pool of muck.")
        print("Good job!")

else:
    print("You stumble around and fall on a knife and die. Good job!")

习题32

the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']

#this first kind of for-loop goes through a list
for number in the_count:
    print(f"This is count {number}")

for fruit in fruits:
    print(f"A fruit of type: {fruit}")

#also we can go through mixed lists too
for i in change:
    print(f"I got {i}")

elements =[]
for i in range(0,6):
    print(f"Adding {i} to the list.")
    elements.append(i)

for i in elements:
    print(f"Element was :{i}")

1、list:上述代码中,像the_count, fruits, change这类都属于list,它和array数组又不太一样,list可以将不同数据类型的变量都放在里面比如change,array不仅在numpy包中,而且只允许一类数据类型的变量在里面。

2、list一些最基本使用
list[-1] : 读取列表中倒数第一个元素
list[1:] : 读取第二个及以后的元素
del list[1] : 删除列表中第二个位置的元素
len(list) : list的长度
list1+list2 : 将两个列表合并
list * 4 : 重复输出四次list中的内容
3 in list : 判断list中有没有“3”这个元素

习题33

没什么问题,可直接看书。

i = 0
numbers = []

while i <6:     #for i in range(0,6):
    print(f"At the top i is {i}.")
    numbers.append(i)

    i+=1
    print("Numbers now:",numbers)
    print(f"At the bottom i is {i}.")

print("The numbers:")
for num in numbers:
    print(num,end='')

习题35

from sys import exit

# a function that
def gold_room():
    print("This room is full of gold. How much do you take?")

    choice = input(">")

    # if I enter 2 what'll happen??
    if choice.isdigit():
        how_much = int(choice)
    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.
    The bear has a bunch of honey.
    The fat bear is in front of another door.
    How are you going to move the bear?
    """)
    bear_moved = False

    while True:
        choice = input(">")

        if choice == "take honey":
            dead("The bear looks at you then slaps your face off.")
        
        # see if the bear is moved
        elif choice == "taunt bear" and not bear_moved:
            print("The bear has moved from the door.")
            print("You can go through it now.")
            bear_moved = True
        elif choice == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif choice == "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.
    He, it, whatever stares at you and you go insane.
    Do you flee for your life or eat your head?
    """)

    choice = input(">")

    if "flee" in choice:
        start()
    elif "head" in choice:
        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.
    There is a door to your right and left.
    Which one do you take?
    """)
    choice = input(">")
    
    if choice == "left":
        bear_room()
    elif choice == "right":
        cthulhu_room()
    else:
        print("You stumble around the room until you starve.")

start()

捋清函数之间的逻辑关系就可以了,画一个流程图,可能内容有误,没有检查过。
题目35

习题36

自己编了一个冗余的、无聊的文字游戏(还有bug,因为对于我自己来说写的繁琐了),初次上手的一定要自己编一编,因为这本书到这里之前基本上都是在练打字速度,可能有的时候就在脑子里理解一下,没有真正自己从构思到编写的过程。

from sys import exit
import time
# the initial fund and share
total = 20000
share_tesla = 0
share_gilide = 0
share_5G = 0
money_tesla = 200
money_gilide = 100
money_5G = 50
first_buy = True
choice_error = 0   #times that the users enter the wrong choice
buy_error = 0   #times that the users enter the wrong stock name

def three_stock():

    # declare that we're using tha variable that defined outside the func
    global total, share_5G, share_gilide, share_tesla, first_buy, choice_error
    print("There are three kinds of stock:")
    print("Tesla, Gilide, 5G")
    print("--------------------------------")
    if first_buy:
        print("And you have initial fundmentation: $20,000.")
        stock = input("Which one do you want to buy?\n>")
        buy(stock)
    else:
        print(f"Your cash is ${total}, you've {share_tesla} shares of Tesla, {share_gilide} shares of Gilide, {share_5G} shares of 5G")
        print("Do you want to buy some more or sell some?")
        choice = input(">")
        if 'buy' in choice:
            print("Which one do you want to buy? Tesla, Gilide, 5G")
            stock = input(">")
            buy(stock)
        elif 'sell' in choice:
            print("Which one do you want to sell? Tesla, Gilide, 5G")
            print(f"You have {share_tesla} shares of Tesla, {share_gilide} shares of Gilide, {share_5G} shares of 5G.")
            print("You can only sell all the shares you have.")
            stock = input(">")
            sell(stock)
        else:
            if choice_error <= 3:
                print("Please enter buy or sell!!")
            else:
                dead("Stupid! I told you three times! ENTER BUY or SELL!")
            choice_error+=1


def buy(stock):
    global total, share_5G, share_gilide, share_tesla, first_buy, buy_error
    global money_tesla, money_gilide, money_5G
    first_buy = False
    if stock == 'Tesla':
        print("Tesla: $200 per share, how many shares do you want to buy?")
        # tell the input I'm going to enter an int type
        share_tesla = int(input(">"))
        if share_tesla*money_tesla > total:
            dead("You don't have enough money to buy it!\n And I don't want who can't do math to play this game!")
        else:
            total = total - share_tesla*200
            if share_tesla > 52:
                print("Crude oil plunged, Tesla dead, and you have lost all the money that invested it.")
                share_tesla = 0
                # set the money to the initial
                money_tesla = 200
                print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
                #continue to play or not
                cont_stop()
            elif share_tesla in range (1,53):
                print(f"You've bought {share_tesla} shares, and your cash now is ${total}.")
                time.sleep(2)
                print("...wait!!")
                time.sleep(4)
                print("Tesla factory in Shanghai begins to produce cars!!!")
                print("Tesla stock is going up to $400 per share!")
                money_tesla = 400
                print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
                cont_stop()
            else:
                dead("Could you enter a NUMBER that greater than 0?")

    elif stock == 'Gilide':
        print("Gilide: $100 per share, how many shares do you want to buy?")
        share_gilide = int(input(">"))
        
        if share_gilide*money_gilide > total:
            dead("You don't have enough money to buy it!\n And I don't want who can't do math to play this game!")
        else:
            total = total - share_gilide*100
            if share_gilide > 41:
                print(f"You've bought {share_gilide} shares, and your cash now is ${total}.")
                time.sleep(2)
                print("2019-nCov is out-break!! OMG!")
                time.sleep(2)
                print("WHAT!!!!!!!!!! Gilide has an effective medicine which can treat it!!")
                time.sleep(4)
                print("Gilide stock is going up to $200 per share!")
                money_gilide = 200
                print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
                cont_stop()
            elif share_gilide in range (1,42):
                print("Gilide is too good to maintain its company, and it closed, everything gone.")
                share_gilide = 0
                money_gilide = 100
                print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
                #continue to play or not
                cont_stop()
            else:
                dead("Could you enter a NUMBER that greater than 0?")
    
    elif stock == '5G':
        print("5G: $50 per share, how many shares do you want to buy?")
        share_5G = int(input(">"))
        if share_5G*money_5G > total:
            dead("You don't have enough money to buy it!\n And I don't want who can't do math to play this game!")
        else:
            total = total - share_5G*money_5G
            if share_5G > 58:
                print(f"You've bought {share_5G} shares, and your cash now is ${total}.")
                time.sleep(2)
                print("HuaWei has invented 5G! Good news!!")
                time.sleep(2)
                print("!!!!!!!!!! US begins to supress HuaWei due to the new technology!")
                time.sleep(2)
                print("5G stock Gone!")
                share_5G = 0
                money_5G = 50
                print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}") 
                cont_stop()
            elif share_5G in range (1,59):
                print("5G is invented. The stock is going up to $100 per share.")
                money_5G = 100
                print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
                #continue to play or not
                cont_stop()
            else:
                dead("Could you enter a NUMBER that greater than 0?")

    else:
        if buy_error <= 3:
            print("Please choose a stock that the game has!!")
        else:
            dead("Stupid! I told you three times! ENTER A STOCK THAT THE GAME HAS!")
        buy_error+=1

def sell(stock):
    global total, share_tesla, share_gilide, share_5G, money_tesla, money_gilide, money_5G
    if stock == 'Tesla':
        total = total + share_tesla*money_tesla
        share_tesla = 0
        print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
        cont_stop()
    elif stock == 'Gilide':
        total = total + share_gilide*money_gilide
        share_gilide = 0
        print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
        cont_stop()
    elif stock == '5G':
        total = total + share_5G*money_5G
        share_5G = 0
        print(f"Now your cash is ${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
        cont_stop()
    else:
        dead("You don't even have that stock!!!")
# continue to play the game or not
def cont_stop():
    choice = input("Do you want to continue? (Y/N) >")
    if choice == 'Y':
        three_stock()
    elif choice == 'N':
        dead("Bye!")
    else:
        dead("Stupid! You can't even enter the Y and N correctly!")

def dead(why):
    print(why,"Game lost!!")
    exit(0)

three_stock()

原文链接:https://blog.csdn.net/qq_41020633/article/details/105196902



所属网站分类: 技术文章 > 博客

作者:紫薇

链接:https://www.pythonheidong.com/blog/article/292487/774f47a6a0ab8a93eb16/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)