Coder Social home page Coder Social logo

calthoff / self_taught Goto Github PK

View Code? Open in Web Editor NEW
267.0 267.0 226.0 198 KB

This repository contains the exercises for "The Self-Taught Programmer: The Definitive Guide to Programming Professionally."

Home Page: http://theselftaughtprogrammer.io

Shell 4.10% Python 95.90%

self_taught's People

Contributors

calthoff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

self_taught's Issues

Chapter 12 Rectangle class

class Rectangle():
def _init(self, w, l):
self.width = w
self.len = l

def area(self):
    return self.width * self.len

def change_size(self, w, l):
    self.width = w
    self.len = l

rectangle = Rectangle(10, 20)
print(rectangle.area())
rectangle.change_size(20, 40)
print(rectangle.area())


TypeError Traceback (most recent call last)
in
----> 1 rectangle = Rectangle(10, 20)
2 print(rectangle.area())
3 rectangle.change_size(20, 40)
4 print(rectangle.area())

TypeError: Rectangle() takes no arguments

exception handling

numb1= input("give me a number: ")
numb2=input("give me another number: ")

numb1=int(numb1)
numb2=int(numb2)
try:
print(numb1/numb2)
except (ZeroDivisionError, ValueError):
print("invalid input")

#still failing when strings are entered as input, dont know why. help

Webscraper certificate error

I recently tried creating the webscraper and found that the code gave me a ssl:certificate_verify_failed. Is there a way around this? Is there something I missed when I was coding?

IDLE not working

I have just started lists. The following lines when written and ran no output is generated in shell
fruit = list()
fruit
Expected result

[ ]
Actual result

while-loops with format method...

Hi there,
The while-loop example given executes fine without the format method, I was hoping for some explanation as to why you used the format method here instead of just print(x)? When I use print(x) it returns the same result.

http://tinyurl.com/j2gwlcy

x = 10
while x > 0:
print('{}'.format(x))
x -= 1
print("Happy New Year!")

Thanks- Sam

Console prints 4 instead of nothing

This example says that the console doesn't print anything. But if I input

f(2)

into the console, it prints 4. I'm not understanding what I'm doing differently if the console shouldn't be returning a result.

page 13 typo

You probably already know this and not sure if I should bring this to your attention...
You have a hash character caught up in an <a> tag on page 13. Screen shot here.
p13-typo

Thanks for your work. I appreciate the book.

Notes Chinese playing card war code

from random import shuffle


class Card:
    """
        扑克牌类
        功能:
            1.定义花色
            2.定义扑克牌
            3.比较牌的大小
    """
    # 定义花色
    suits = ["♠", "♥", "♦", "♣"]
    # 定义牌序,None用来占位
    values = [None, None, "2", "3",
              "4", "5", "6", "7",
              "8", "9", "10", "J",
              "Q", "K", "A"]

    # v:传入的牌序
    # s:传入的花色
    def __init__(self, v, s):
        """构造函数,传入牌序和花色"""
        self.value = v
        self.suit = s

    # 当类捕获到<时,会自动执行
    def __lt__(self, c2):
        """比较传入的排序和花色大小"""
        if self.value < c2.value:
            return True
        if self.value == c2.value:
            if self.suit < c2.suit:
                return True
            else:
                return False
        return False

    # 当类捕获到>时,会自动执行
    def __gt__(self, c2):
        """比较传入的排序和花色大小"""
        if self.value > c2.value:
            return True
        if self.value == c2.value:
            if self.suit > c2.suit:
                return True
            else:
                return False
        return False

    # Deck生成牌序时会调用,当类被调用时,返回花色和排序,如黑桃A
    def __repr__(self):
        v = self.suits[self.suit] + self.values[self.value]
        return v


class Deck:
    """
        牌堆类
        功能:
            1.洗牌
            2.减牌
    """

    def __init__(self):
        """构造函数:进行洗牌"""
        # 定义牌列表
        self.cards = []
        for v in range(2, 15):
            for s in range(4):
                # 调用扑克牌类,生成52张牌,添加到牌的列表中
                self.cards.append(Card(v, s))
        # 将牌列表随机打散
        shuffle(self.cards)
        print(f"牌序列表:{self.cards}")

    # 当牌被抽到后,需要从牌堆中删除
    def rm_card(self):
        if len(self.cards) == 0:
            return
        return self.cards.pop()


class Player:
    """
        玩家类
        功能:
            1.赢的次数
            2.手中的牌
            3.玩家名字
    """

    def __init__(self, name):
        """构造函数:初始化玩家"""
        # 玩家赢的次数
        self.wins = 0
        # 玩家手中剩余的牌
        self.cards = None
        # 玩家名字
        self.name = name


class Game:
    """
        游戏类
        功能:
            1.初始化游戏
            2.每次赢得比赛的玩家
            3.抽排
            4.游戏开始
    """

    def __init__(self):
        """构造函数:初始化游戏"""
        p1_name = input("请输入玩家1的名字:")
        p2_name = input("请输入玩家2的名字:")
        # 实例化Deck类,赋值给对象属性self.deck
        self.deck = Deck()
        # 初始化玩家
        self.p1 = Player(p1_name)
        self.p2 = Player(p2_name)

    def wins(self, winner):
        """每次赢得比赛的玩家"""
        w = f"玩家:{winner},赢了这一局"
        print(w)

    def drew(self, p1_name, p1_card, p2_name, p2_card):
        """玩家抽排"""
        d = f"玩家:{p1_name}抽到{p1_card},{p2_name}抽到{p2_card}"
        print(d)

    def play_game(self):
        """开始游戏"""
        # 调用self.deck.cards进行洗牌
        # cards存放的是洗好的牌
        cards = self.deck.cards
        print("--游戏开始--")
        # 每个人一张牌,所以最少剩余两张牌
        while len(cards) >= 2:
            response = input("输入q退出游戏,任意键继续!")
            if response == 'q':
                break
            # p1玩家从牌堆中抽一张牌
            p1_card = self.deck.rm_card()
            # p2玩家从牌堆中抽一张牌
            p2_card = self.deck.rm_card()
            # p1玩家的名字
            p1_name = self.p1.name
            # p2玩家的名字
            p2_name = self.p2.name
            # 开始抽排
            self.drew(p1_name, p1_card, p2_name, p2_card)
            # 比较玩家p1和玩家p2的牌大小
            if p1_card > p2_card:
                # 玩家p1赢了这局,统计玩家胜利次数的变量wins加1
                self.p1.wins += 1
                # 打印玩家p1胜利信息
                self.wins(self.p1.name)
            else:
                # 玩家p2赢了这局,统计玩家胜利次数的变量wins加1
                self.p2.wins += 1
                # 打印玩家p2胜利信息
                self.wins(self.p2.name)

        win = self.winner(self.p1, self.p2)
        print(f"游戏结束:{self.p1.name}赢了{self.p1.wins}局,{self.p2.name}赢了{self.p2.wins}局,{win}")

    def winner(self, p1, p2):
        """判断哪个玩家胜利"""
        if p1.wins > p2.wins:
            return p1.name + "赢了"
        if p1.wins < p2.wins:
            return p2.name + "赢了"
        return "平局"


game = Game()
game.play_game()

Not sure if this is an issue with my computer

Hello World! I'm new here!
I have the following issue...
When i put the following

image

This on my end...
image
it doesn't display the 100
no results

The book shows this...
image

At the end it supposed to display 100
Please advise.

Port is not an integer when it really is

I copied the code just as it says for the website that says "Hello, World!", with
app.run(port='8000')
but it says:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in
app.run(port='8000')
File "C:\Users\aripo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 843, in run
run_simple(host, port, self, **options)
File "C:\Users\aripo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\werkzeug\serving.py", line 748, in run_simple
raise TypeError('port must be an integer')
TypeError: port must be an integer

csv writing

I input the following code from http://tinyurl.com/go8wepf:

import csv
with open("st.csv", "w") as f:
    write = csv.writer(f, delimiter=",")
    write.writerow(["one",
                    "two",
                    "three"])
    write.writerow(["four",
                    "five",
                    "six"])

When I open the st.csv file in Microsoft Excel, one, two and three appear as they should on row 1, but four, five and six appear on row 3, not row 2.

This also happened when I first used the code in the example from the book (Kindle location 3107) that used the syntax w.writerow(["one", . . . etc. instead of the above syntax.

As I barely have a grasp of what I'm coding here, I'm not sure why the output file differs in its description from the book.

Not trying to be a pain, just trying to understand what I'm learning.

Page 20 of book.

In page 20 of my copy of TSTP line 5 of this code is written:
5print("Hello, World!")
It's just an example, but you may have wanted to know.

Issue with python_ex100.py

When copying this into IDLE and/or PowerShell with Python I get an error stating that int_age is not defined. What might be causing this?

Thanks in advance for any feedback!

Error when running code

http://tinyurl.com/go9wepf

I get this error when running the code.

Traceback (most recent call last):
File "/Users/mardirousi/Desktop/Python/Ch 9/csv/csv.py", line 1, in
import csv
File "/Users/mardirousi/Desktop/Python/Ch 9/csv/csv.py", line 5, in
write = csv.writer(f, delimiter=",")
AttributeError: module 'csv' has no attribute 'writer'

Example keeps asking me to save even after I save...

``x = 100
if x == 10:
print("10!")
elif x == 20:
print("20!")
else:
print("I don’t know!")

if x == 100:
print("x is 100!")

if x % 2 == 0:
print("x is even!")
else:
print("x is odd!")

When I use the F5 key to run(in the test editor), I keep getting a message to save. This doesn't happen with other code, just this particular one. Update- I retyped the code myself and it worked fine. I tried repeatedly to be able to save the code above using copy and paste, but for some reason it would not save it.

Code on page 67 doesn't work

Hey there,

I'm learning on Pythong 3.9.2 and in the self-taught programmer book from 2022 the code on the bottom of page 67 does trigger the question about age but it doesn't print the result. Here is the code:

age = input ("Enter your age:")
int_age = int(age)
if int_age <21:
print ("Dude you're young")
else:
print ("Just the right age")

I tried a couple of times and even taking the second line out or replacing in line 3 int_age with int(age) but still nothing. I would greatly appreciate any help :)

Please guide me

n=8
count = 0

for i in range(n):
for j in range(n):
for k in range(n):
if i < j and j < k:
count += 1

print(count)

output
SyntaxError: multiple statements found while compiling a single statement

Webscraping Code Outputted Nothing to Shell

I am really excited about the potential of webscraping! But when I ran the webscraping code from chapter 20, it output nothing to the interactive shell. When I pressed run, the interactive shell window came to the foreground, but there was nothing in it.

In case I had mistyped the code, I decided to copy and paste right from tinyurl. Still nothing.

Please help.

Chapter 4 exception handling... error

I tried running this code and I think I am not supposed to get the error instead it
prints "b can not be zero". This is the code:
a=input("type a number:")
b=input("type anothernumber")
a=int (a)
b=int(b)
try:
print (a/b)
except ZeroDivsionError:
print("b cannot be zero.")

Chapter 19, Installing Git

I installed Git via their website (Windows version). However, typing "git" into Bash continues to tell me git is not installed, although it clearly is and I can run it.

I think the problem I'm experiencing has to do with where bash is installed on my computer. I can't find it so I don't know what part of my PC's directory tree I'm in. I'm completely lost here because I don't know what directory I have to be in to, e.g., download packages as in Chapter 18, or, clone repositories as in Chapter 19.

Chapter 3

Hello,

nice ebook, recently buyed on Amazon-Kindle.

Where is chapter 3 ??

Regards

"print" command missing?

I believe that you forgot to put the "print" in front of the "fruit" list. If I type it like the book shows and ran it, no result....if I ad the "print" command, it works.

edit** nevermind, I realize that you just type straight in the shell....Sorry.

Import module1 not hello?

In the book, you say to create a new file called "module1.py" and import it into a 2nd file called "module2.py", but the code says to "import hello" not "import module1". That could lead to confusion.

No output

Attempting to do the python_ex8.py

in the beginning of the book. It is the example of a "good comment" where the command is supposed to give the diagonal of a rectangle. I have tried typing it, copying it, and saving it and running the module but no matter what I do the command gives me no output. It just produces "RESTART: C:/Users/Censoredfoldername/AppData/Local/Programs/Python/Python36-32/b" and then a new line of >>>

I am getting the same issue with python_ex27.py

I do

  1. b = 100
  2. b

and after running the module I receive no output. If I then enter B alone I will be given the value of 100. So the module gives the information but for some reason the value of b in the module does not prompt it to produce 100. I have to ask for B separate from the module.

Conditional Statements Chpt 3

I recently purchased your book, I'm currently attempting to complete the if-else statements. The first example after I complete the line print ("Hello, America!") the next line of "else:) indents to the same spot as the word print and I get syntax errors if i erase the indentation or if I leave it. Seems like it doesn't start a new line. Not sure what I'm doing wrong. Thanks

home = "America"
if home == "America":
print ("Hello, America.")
else:
print ("Hello, World.")

Chapter 5, page 72 (paperback)

When I try using this code from the book:

colors = ["purple", "orange", "green"]
guess = input("Guess a color:")
if guess in colors:
print("You guessed correctly!")
else:
print("Wrong! Try again.")

I then run the code and try guessing white to see my message for when it is wrong (although this is also happening when I guess a color that is in the list) I get the following error message:

Traceback (most recent call last):
File "", line 2, in
File "", line 1, in
NameError: name 'white' is not defined

Am I doing something wrong? I typed it in just as it is written in the book.

SyntaxError: multiple statements found while compiling a single statement

Just bought book, first day of programming. "Hello World" worked fine, but every time I type something more complex, I get the "SyntaxError: multiple statements found while compiling a single statement". Have tried copying and pasting from website and still get this error. Please help.

home = "America"
if home == "America":
print("Hello, America!")
else:
print("Hello, World!")

SyntaxError: multiple statements found while compiling a single statement

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.