<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Angeleah Hoeppner on Medium]]></title>
        <description><![CDATA[Stories by Angeleah Hoeppner on Medium]]></description>
        <link>https://medium.com/@GelBelleH?source=rss-52844f1c779e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FwifsGNNlCAiQpw5.jpg</url>
            <title>Stories by Angeleah Hoeppner on Medium</title>
            <link>https://medium.com/@GelBelleH?source=rss-52844f1c779e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:27:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@GelBelleH/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff — Chapter Five]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-five-2c17b01dbd0b?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c17b01dbd0b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 03:21:33 GMT</pubDate>
            <atom:updated>2023-06-17T03:21:33.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Journey with Automate the Boring Stuff — Chapter Five</h3><p>Whoops, my <a href="https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-four-part-two-2f7d10fea9be">Chapter Four, part two</a> should have been Chapter Five. The Tic Tac Toe game I describe in that story is actually the sample program for Chapter Five. Today I will discuss the two practice programs at the end of chapter five. I made much quicker progress with these than Tic Tac Toe.</p><p>The first practice program is a chess board validator, which I read as chess move validator initially, so I ended up implementing both.</p><p>The chess move validator uses a pre-written dictionary of moves as its input, but this could be easily changed to use player input. The main function then loops through each key and value representing the coordinates of a square on the board and the colour and piece being moved. Each key, value pair is passed to a valid_move function.</p><pre>    moves = {&#39;1h&#39;: &#39;bking&#39;, &#39;6c&#39;: &#39;wqueen&#39;,<br>             &#39;2g&#39;: &#39;bbishop&#39;, &#39;5h&#39;: &#39;bqueen&#39;, &#39;3e&#39;: &#39;wking&#39;}<br>    for key, val in moves.items():<br>        if not valid_move(key, val):<br>            print(f&quot;I&#39;m sorry, moving {val[1:]} to {key} is not valid.&quot;)<br>            return False<br><br>    print(&quot;All moves valid&quot;)</pre><p>The valid_move function checks if the square is valid based on rows being numbered from 0–8 and columns a-h. Initially the validate_square function was in this file, but when I made the chess board validator I broke it out into a chess utilities file.</p><p>It’s just two boolean checks, 0 ≤ row ≤ 8 and a ≤ col ≤ h. After it validates the square valid_move checks if the colour of the piece is valid, it can only be black or white, indicated by ‘b’ and ‘w’. I used the item in list to check for this. Finally it checks if the piece is a valid piece, chess doesn’t not have an archer piece for instance. Again, I went with item in list to determine if this was valid. The function returns True if all items are true, otherwise False.</p><pre>def valid_move(square, piece):<br>    valid_square = chessUtils.validate_square(square)<br>    valid_color = validate_color(piece[1])<br>    valid_piece = validate_piece(piece[1:])<br><br>    return all([valid_square, valid_color, valid_piece])<br><br><br>def validate_square(square):<br>    return validate_row(int(square[0])) and validate_col(square[1])<br><br>def validate_row(row):<br>    return row &gt; 0 and row &lt; 9<br><br>def validate_col(col):<br>    return col &gt;= &#39;a&#39; and col &lt;= &#39;h&#39;<br><br>def validate_color(color):<br>    return color in [&#39;b&#39;, &#39;w&#39;]<br><br>def validate_piece(piece):<br>    return piece in [&#39;king&#39;, &#39;queen&#39;, &#39;bishop&#39;, &#39;knight&#39;, &#39;rook&#39;, &#39;pawn&#39;]</pre><p>In reality the above functions would have valid_move at the bottom otherwise the functions it calls won’t be defined and you’ll get an error. I have put valid_move at the top to show the flow of the code.</p><p>As you can see, all the functions are very small and only do one thing. I do this when I code for two reasons, the first is that I came from JavaScript and making sure all your functions have one activity is part of the functional paradigm that I learned for JavaScript. I’m sure there are many other paradigms out there, this is just the one I learned. One activity and no side effects, not even printing. The other reason is that I find functions with multiple purposes to quickly become hard to read and understand. At this level of program I think it’s fine to have the extra overhead for a function call as it makes everything clearer.</p><p>If any of the checks valid_move makes are False it will print “I’m sorry, moving PIECE to SQUARE is not valid and return False and break the for loop. If the moves are valid then it will print “All moves valid.”</p><p>The chess board validator is not much different from the move validator. The main difference is that it also verifies the number of and kind of pieces on the board. Each player can only have: 1 king, 1 queen, 2 bishops, 2 knights, 2 rooks, and 8 pawns. If either player starts with too view or has too many at any point in the game it will advise the players that, “There are too many pieces on the board.”</p><p>To determine if a board is valid the program first uses the validate_square function used earlier for the moves. If this fails it advises the players, “SQUARE is not a valid square.” and does not bother to check the number and kinds of pieces. If the square passes then it will pass all the pieces to check_num_pieces.</p><p>This function does perform a few different things, it contains a dictionary with the name and count of each piece allowed, it checks that all pieces are either black or white, checks that each colour only has 16 pieces in total, and then checks for the amount of each piece for both colours. As I type this I realize that I could pass in which colour needs to be checked to save the duplication I used for white and black. I don’t often overlook duplicate code, that’s unusually, but this is why writing about it is so helpful.</p><pre>def check_num_pieces(pieces):<br>    valid_pieces = {<br>        &quot;king&quot;: 1,<br>        &quot;queen&quot;: 1,<br>        &quot;bishop&quot;: 2,<br>        &quot;knight&quot;: 2,<br>        &quot;rook&quot;: 2,<br>        &quot;pawn&quot;: 8<br>    }<br>    white = [piece for piece in pieces if piece[0] == &#39;w&#39;]<br>    black = [piece for piece in pieces if piece[0] == &#39;b&#39;]</pre><p>The first part of the method shows the dictionary, valid_pieces anything outside of these restrictions is invalid. The next part uses list comprehensions to create a list of all the pieces on the board passed into the check_num_pieces function. The first one, white = [piece for piece in pieces if piece[0] ==&#39;q&#39;]translates to add piece to the list for each piece in pieces if the first letter of the piece is equal to w. The black is the same.</p><pre>white_pieces = {}<br>black_pieces = {}<br><br>for piece in white:<br>   white_pieces[piece[1:]] = white.count(piece)<br><br>for piece in black:<br>   black_pieces[piece[1:]] = black.count(piece)<br><br>for key, val in valid_pieces.items():<br>    if white_pieces.get(key):<br>        if white_pieces[key] &gt; val:<br>            print(f&quot;You have too many {key}s&quot;)<br>            return False<br>    if black_pieces.get(key):<br>         if black_pieces[key] &gt; val:<br>            print(f&quot;You have too many {key}s&quot;)<br>            return False<br><br>    return True</pre><p>I split the function into such uneven sections because all of this code deals with the lists we created above. First two empty dictionaries are defined, these will hold a list of all the pieces for each colour with how many of them are on the board.</p><p>It then loops through the list of pieces for each colour and if the piece is not already in the dictionary it adds the piece name as a key and how many of them there are in the list as the value. Again, duplicate code and two loops, this is turning into a very inefficient program, good thing it’s small. I’m going to have to revisit this and see what I can do, it’s very sloppy.</p><p>The final big for loop goes through each item in the dictionary of valid pieces and checks the counts against how many of that piece were found on the board for each colour. If the count of the pieces in that colour’s dictionary is greater than the allowed count in valid_pieces it prints, “You have too many PIECES.” then quits the function and returns False, otherwise it continues this final loop. If it gets through without anything coming up false then it returns True.</p><p>I thought I was going to cover the other practice program in this one, a game inventory system, but this ended up being far longer than I anticipated. That will have to be for next time. I nearly forgot, I created full test suites for these programs as well. I think I covered everything, if you visit my <a href="https://github.com/gelbelle/Automate-the-Boring-Stuff">repo</a> and find anything missing from test coverage I would love to get the feedback.</p><p>A huge thank you to Al Sweigart for writing <a href="http://automatetheboringstuff.com/#toc">Automate the Boring Stuff with Python</a> and especially for releasing it free online.</p><p>My code for the projects thus far and my utility programs can be found on my <a href="https://github.com/gelbelle/Automate-the-Boring-Stuff">GitHub Repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c17b01dbd0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff — Chapter Four, part two]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-four-part-two-2f7d10fea9be?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f7d10fea9be</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 01:53:16 GMT</pubDate>
            <atom:updated>2023-06-04T01:53:16.745Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Journey with Automate the Boring Stuff — Chapter Four, part two</h3><p>Well this week was a doozy. I had anticipated this would be a quick run through of the Tic Tac Toe example and then go through both the end chapter projects. Instead it was a week of Tic Tac Toe. The game itself was quite easy to implement. I started with the dictionary definition supplied in the book.</p><pre>theBoard = {&#39;top-L&#39;: &#39; &#39;, &#39;top-M&#39;: &#39; &#39;, &#39;top-R&#39;: &#39; &#39;,<br>            &#39;mid-L&#39;: &#39; &#39;, &#39;mid-M&#39;: &#39;X&#39;, &#39;mid-R&#39;: &#39; &#39;,<br>            &#39;low-L&#39;: &#39; &#39;, &#39;low-M&#39;: &#39; &#39;, &#39;low-R&#39;: &#39; &#39;}</pre><p>This was mostly to save time, I find typing dictionaries and long lists rather tedious. My theory is once I know the syntax of something then I no longer have to type it out each time. If I haven’t got the syntax down yet then I must type it out each time as a learning thing. In this case I’ve got dictionaries and lists down so I let myself copy and paste. I change the name of my board to ```board```, but other than that I kept it the same.</p><p>Once I had my board I set off on my own. First I built a get_move function that used the create_options utility I had created for myself during my list management adventures.</p><pre>def get_move(player, board):<br>    # Only display options that are available for play<br>    keys = [key for key in board.keys() if board[key] == &quot; &quot;]<br><br>    square = utils.create_options(<br>        &quot;Please select which spot you would like to play in&quot;, keys)<br>    print(&quot;You have chosen your location&quot;)<br>    board[keys[square]] = player<br><br>    return board</pre><pre>def create_options(msg, options) -&gt; int:<br>    print(msg)<br>    # print(&quot;\n&quot;)  # For easier reading<br>    for i in range(len(options)):<br>        print(f&quot;{i}: {options[i].strip()}&quot;)<br><br>    ans = input()<br>    # List from range https://www.geeksforgeeks.org/range-to-a-list-in-python/<br>    return int(getAns(ans, str([*range(len(options))])))</pre><p>This lists out all the options available for play in that round:</p><p>0: top-R<br>1: mid-L<br>2: mid-M<br>3: mid-R<br>4: low-L</p><p>This is the list from a partially played game. I quickly realized that I needed to update and show the board each time that’s when I added the line to update the board to ```get_move```. ```board[keys[square]] = player``` This done I called print_board again with the new board. After this I put the logic for getting the next player in its own function too.</p><pre>current_player = get_next_player(current_player)<br><br>def get_next_player(current):<br>    return &quot;O&quot; if current == &quot;X&quot; else &quot;X&quot;</pre><p>It’s quite small and very quick, initially it was a regular if/else statement and I thought it cluttered up my game space, but seeing it now, I may decided to put it back in as its turned into a one-liner. Either way, that was my next step, switch the current player.</p><p>Once all these things were done I tackled the win logic. This is what took all the time. I haven’t had much time to code this week, but the bulk of it was spent on this function. As always, I wanted to make it efficient and elegant immediately. After an unsuccessful attempt to use the logic I learned in the coin flips project to check for runs of 3 I was good and went back and used brute force so I could see it in action. Checking the length of runs doesn’t work in this case because a run of three could span part of one row or column and part of the next, that doesn’t work for Tic Tac Toe and besides, how is that going to check the diagonals. Just for transparency and don’t do this I’ve included the wrong code below.</p><pre>def check_game_over(board):<br>    start_pos = 0<br>    sum = 0<br>    plays = &quot;&quot;.join(list(board.values()))<br>    while start_pos &lt; len(board):<br>        pos = plays.find(&quot;XXX&quot;, start_pos)<br><br>        if pos != -1:<br>            start_pos = pos + 1<br>            sum += 1<br>        else:<br>            print(sum)</pre><p>The sum is supposed to move you through the board and I used the print in the else to check what was happening. Sadly, not much. So I pulled back and typed out a billion if statements. Man is it ugly.</p><pre>    if board[&#39;top-L&#39;] in players and board[&#39;top-L&#39;] == [&#39;top-M&#39;] == board[&#39;top-R&#39;]:<br>        return True<br>    if board[&#39;mid-L&#39;] in players and board[&#39;mid-L&#39;] == board[&#39;mid-M&#39;] == board[&#39;mid-R&#39;]:<br>        return True<br>    if board[&#39;low-L&#39;] in players and board[&#39;low-M&#39;] == board[&#39;low-L&#39;] == board[&#39;low-R&#39;]:<br>        return True<br>    if board[&#39;top-L&#39;] in players and board[&#39;top-L&#39;] == board[&#39;mid-L&#39;] == board[&#39;low-L&#39;]:<br>        return True<br>    if board[&#39;top-M&#39;] in players and board[&#39;top-M&#39;] == board[&#39;mid-M&#39;] == board[&#39;low-L&#39;]:<br>        return True<br>    if board[&#39;top-R&#39;] in players and board[&#39;top-R&#39;] == board[&#39;mid-R&#39;] == board[&#39;low-R&#39;]:<br>        return True<br>    if board[&#39;top-L&#39;] in players and board[&#39;top-L&#39;] == board[&#39;mid-M&#39;] == board[&#39;low-R&#39;]:<br>        return True<br>    if board[&#39;top-R&#39;] in players and board[&#39;top-R&#39;] == board[&#39;mid-M&#39;] == board[&#39;low-L&#39;]:<br>        return True <br>    return False</pre><p>It worked though. There are two statements in each if because I found that if all of the entries were “ “ then it returned a win as well so the first part is simply checking if the first item in each potential row is an X or an O.</p><p>After this I tried creating a list of lists checking to see if they contained “top”, “mid”, “low”, “L”, “M”, or “R”. My theory was that I wouldn’t have to check “top-L”, “top-M”, “top-R” etc as I did in my if statements. It would cut things down a little bit. This didn’t work either, I used generator statements and generators don’t have a length. Which is obvious in hindsight as generators are used so you don’t have to store it all in memory, I believe. I can use them, but I’m still a little sketchy on the details. Real Python has a fantastic article on <a href="https://realpython.com/introduction-to-python-generators/">generators</a> though that I highly urge everyone to read. It was very helpful!</p><pre>lines.append((play for play in plays if &quot;top&quot; in play))<br>lines.append((play for play in plays if &quot;mid&quot; in play))<br>lines.append((play for play in plays if &quot;low&quot; in play))<br><br>lines.append((play for play in plays if &quot;L&quot; in play))<br>lines.append((play for play in plays if &quot;M&quot; in play))<br>lines.append((play for play in plays if &quot;R&quot; in play))<br><br>checked = any(line for line in lines if len(line) == 3) </pre><p>This still took six separate checks though, plus my ```any``` line didn’t work because generator objects don’t have a len function as my terminal so helpfully informed me, many times. My next thought was to have a separate list for each row and column. I would check if “top”, “mid”, “low”, etc were played. If it was contained in the play then it would be added to the “top” list. If any of them had a length of three then it was a winner.</p><pre>lines = []<br>top = []<br>mid = []<br>low = []<br>left = []<br>middle = []<br>right = []<br><br>for play in plays:<br>   if &quot;top&quot; in play:<br>      top.append(play)<br>   elif &quot;mid&quot; in play:<br>      mid.append(play)<br>   elif &quot;low&quot; in play:<br>      low.append(play)<br><br>   if &quot;L&quot; in play:<br>       left.append(play)<br>   if &quot;R&quot; in play:<br>       right.append(play)<br>   if &quot;M&quot; in play:<br>       middle.append(play)</pre><p>Plays is a set that contains a list of all the squares that have an X or an O in them. This is also a bunch of ugly if statements, but it gets worse. All these lists are added to the ``lines``` list and then it all gets iterated through.</p><pre>lines.append([top, mid, low, left, middle, right])<br><br>for line in lines:<br>   for row in line:<br>      if len(row) == 3:<br>         return True </pre><p>That’s a nested loop every time the game loop runs. Yes, it’s a small game that takes virtually no resources, but still, nested loops are time sucks and even if it doesn’t matter here, it will some day. Get in good habits while you’re learning! It was at this point that I broke and started searching Google for Tic Tac Toe logic. I didn’t want code to copy, but something that could help me reason my way through this with a better algorithm as the end result. I actually found someone else doing what I’m doing here on Medium, <a href="https://medium.com/byte-tales/the-classic-tic-tac-toe-game-in-python-3-1427c68b8874">James Shah</a>. I was still looking for logic and not code so I moved on after skimming the first part before he got to the win logic. It was good though. If you like what I’m doing here then you will probably like his article too. Back to Google for me.</p><p>I had, had a brief thought somewhere along the way that maybe I should just make a list of each potential combination of wins. Again, this isn’t something that scales well and I try to avoid this at all costs, but it is nicer than the brute force if statements and scales slightly better. It’s not good though. This is the answer I found on Google though. There’s a site I hadn’t encountered before called Scaler Topics, they seem to offer free Python courses and tutorials, but they also had an article on <a href="https://www.scaler.com/topics/tic-tac-toe-python/">implementing Tic Tac Toe</a>.</p><p>I skipped through all the parts I had already done, with a brief glance to see if the implementation was any different of course. It was a bit from what I could tell, but aside from my win logic I’m happy with mine so I kept going. In the end, this person had used a list of all the win possibilities. I went back to the partial list I had made before giving up on that route and finished it. I did use the loop piece in the end. I don’t like doing that, but it implemented it all in a way that I had been pondering before but I didn’t quite know how to do it right.</p><pre>    #Implementation loop from https://www.scaler.com/topics/tic-tac-toe-python/<br>    for line in lines:<br>        if all(check in plays for check in line):<br>            return True<br>    return False</pre><p>After this it was fairly quick to finish up. I used my utility library to ask if the person or people wanted to play again and save their scores. I did have to change it up a bit because I wanted both players to be able to save their score. I ended up implementing a save_tic_tac_toe wrapper function around save_game to get this to work without duplicating a ton of stuff. In the end it was just easier to call save_game twice.</p><pre>def save_tic_tac_toe(score):<br>    print(&quot;X&quot;, end=&quot;&quot;)<br>    save_game(&quot;Tic Tac Toe&quot;, f&quot;X {score[0]}&quot;)<br>    print(&quot;O&quot;, end=&quot;&quot;)<br>    save_game(&quot;Tic Tac Toe&quot;, f&quot;O {score[1]}&quot;)</pre><p>I did run into a bit of trouble due to my decision to save the wins, losses, and ties for each player in a dictionary, “Xs” and “Os”. In my other games I was passing in an f string containing the win, lose, tie information</p><pre>[f&quot;wins: {wins}&quot;, f&quot;losses: {losses}&quot;, f&quot;ties: {ties}&quot;]</pre><p>You cant’ use an f string with dictionary accessors, it didn’t like ```Xs[“wins”]``` I ended up just passing the dictionaries in, in a list ```utils.playAgain(“Tic Tac Toe”, [Xs, Os])```</p><p>That’s why the save_tic_tac_toe function uses ```score[0]``` and ```score[1]```. I don’t like hard coding things like that, but I also realize it’s small and this is a wrapper for the game Tic Tac Toe specifically so it’s always going to be 0 and 1, but still.</p><p>A quick change to my game play loop in case players wanted to play again and I was all set. Or so I thought. I briefly dealt with the board not resetting when a player chose to play again, but luckily that wasn’t too bad of a fix, I just wrote a new_board function that I called.</p><pre>board = new_board()<br><br>def new_board():<br>    board = {&#39;top-L&#39;: &#39; &#39;, &#39;top-M&#39;: &#39; &#39;, &#39;top-R&#39;: &#39; &#39;,<br>             &#39;mid-L&#39;: &#39; &#39;, &#39;mid-M&#39;: &#39; &#39;, &#39;mid-R&#39;: &#39; &#39;,<br>             &#39;low-L&#39;: &#39; &#39;, &#39;low-M&#39;: &#39; &#39;, &#39;low-R&#39;: &#39; &#39;}<br>    return board</pre><p>And NOW we’re done. It was rather more involved than I was expected, but as always, good learning and I always enjoy writing Python. Next up is the two practice problems from Chapter 4: a chess move validator and an inventory system for a game. Let’s see if I can manage to do them both before next week.</p><p>And, of course, thank you to <a href="http://automatetheboringstuff.com/2e/">Al Sweigart</a> for writing this wonderful book and making it available.</p><p>If you’re interested in my code and my utility library it’s all up on my <a href="https://github.com/gelbelle/Automate-the-Boring-Stuff">Github repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f7d10fea9be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff — Chapter Four]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-four-e1983fdcfb4e?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1983fdcfb4e</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Sat, 27 May 2023 23:28:30 GMT</pubDate>
            <atom:updated>2023-05-27T23:28:30.708Z</atom:updated>
            <content:encoded><![CDATA[<h2>My Journey with Automate the Boring Stuff: Chapter Four</h2><p>Well I went off the deep end with this chapter. The small example program that lets users continue to add items to a list until their done turned into a rather large list management program. And I still have things to improve and add to it. I figured I better stop though or I’ll never get through this chapter, let alone the entire book. I have boring things to automate here!</p><p>Again, Al Sweigart has not disappointed with his explanations. I realize I’m coming at this book with a large knowledge base to draw on already, but I really do think his explanations are clear and well illustrated when they need to be. As the title of the chapter suggests, it is all about lists.</p><p>After switching to Python from mostly JavaScript it took me a bit to switch the terminology in my mind from array to list. So far in my journey I haven’t found any differences in how I interact with each one, this does not mean that there aren’t differences, just that I’ve found that since I was already familiar with arrays and the kinds of things their methods did I was able to translate to Python’s lists quite easily.</p><p>So, back to the teensy-weensy example in the chapter, list your cats. The code is relatively short and similar to the other examples so far.</p><pre>while True:<br>  run this code to get user input<br>  if they do the thing to stop:<br>    print list items<br>    break</pre><p>I went a further than this, just a little at a time. This was an excellent example of mission creep, although it was my mission for myself. :)</p><p>First, I decided I wanted the ability to save the list so I had it write to a text time. This is the same functionality I added to the small game examples where I gave users the choice to save their score or not. I realized it didn’t make sense to use the same utility function I’d written though because the information being saved was so different. I attempted to refactor the original save_game function but it ended up becoming very convoluted and wound up with passing in 4 arguments I think. At that point I decided to create a specific list one. I may revisit this later. I’m a big believer in functional code and methods without side effects. This is a holdover from coming up in JavaScript and I have yet to discover where Python stands on this, if at all.</p><p>After saving the list I realized you need to be able to add things to your list. But, to add things to your list you also need to know which lists are available to be added to. So two more functions were added. First the one that let you add things to your list, but I quickly realized that unless you knew which lists were there then you wouldn’t be able to pick one, nor spell it exactly to open it. This aspect of typing out the name of the list gets addressed later as I improved things. It was after my realization that I knew which list to pick because I had just created it in my testing so I added yet another function. This one lets you see all your lists and then choose which one to add items to.</p><p>If you can add things to your list I realized you also needed to be able to remove things from your list. So that came next. This was a little more complex than just appending things to the file, but not too bad. It does involve rewriting the entire file. This is another thing to review, I bet there’s a more “Pythonic” way to do this, I haven’t found it yet. But we’re just at v1. :)</p><p>It was once I got here that I realized my way of selection was cumbersome and would quickly become a pain point for users. If I had any… I went back to my original list of menu options that I had printed out by hand using numbers of the left as the selection method. When it was just a couple of things to do with a list or two it wasn’t a big deal, but growth was not feasible and as we’ve already seen, I’ve been adding more and more to this little example.</p><p>I needed a method that would take a list of options for a menu that would print out the options nicely formatted with a number to the left to choose the option. This list method would allow me to passing in any length of items to display for a menu. As more lists get added, this will be helpful. Each list will automatically be added to the options to choose for viewing. This removes a big headache as things grow. I realize this is a small personal project and there are a million list programs out there, but treating it like something that will launch and have users some day is a good way to ensure good habits. I spent long enough designing and thinking about ux that this is ingrained in the way I think, even if I’m working more backend now.</p><p>To get back to my new function, it will now take a list of any length as input and create a text-based menu for it. I was very happy about this one. As a programmer it’s important to account for growth. It’s better to operate as if everything is something that will need to grow 10, 20, 100 fold some day. That way it doesn’t come back to bite you if/when it does. A bit more work now to save yourself a TON of work later.</p><p>The only tricky thing I ran into with my new menu function was my main menu. This menu required that a function be called when an option was selected, this is also a list that would keep growing. How could I decouple the menu function from requiring a list of function calls as well. After identifying the problem and many false starts trying to use lists and dictionaries and too many loops and much Googling I found the syntax to do what I wanted. There are two lists here that sadly must be written out manually, at this point anyway.</p><p>There is one list containing the option names for the menu. This list and the prompt for the user is passed to a utility function called create_options. This displays the options nicely regardless of the number of options. The second list here is a list containing the names of the functions to be called with each option, just the names NOT the () required to call the function. A part I’m still not happy with here is that if these lists aren’t in the matching order then the wrong function will be called . This is something I’m still pondering. Finally, the index of the item chosen is passed to the options list for selection and that function is then called.</p><p>My last realization, well my last realization I’ve implemented so far was to delete a list. I can’t believe I missed this, especially after the create a list option was added. Luckily Python makes this super easy. Just use</p><pre>import os<br>as.remove(&lt;file path and name here&gt;)</pre><p>That’s it. Coding in Python is such a delight sometimes! The entire delete function took about 5 minutes. Print the lists available, which was already done; choose a list, also already done; confirm with the user that they really want to delete the list, done; and report out that the list was deleted or that it wasn’t depending on their choice.</p><p>There are things I still want to implement and will go back, some smaller tasks than others.</p><ol><li>Right now you can view a list of the lists, but not select one from there. To select you go back to the main menu and choose read list and then choose the list.</li><li>If you are reading a list you can’t choose to add or delete items right there. You must go back to the main menu and choose add or delete items to do this.</li></ol><p>Are you sensing a trend here?</p><p>3. If you are a reading a list you cannot delete it from there, you must go back to the main menu and choose delete list and then you can.</p><p>Clearly there’s some better ux needed here.</p><p>My last plan is to convert the save/recall system to a database. This would be much more realistic than writing text tiles to a user’s computer. Plus it would be an excellent introduction for me into working with databases programmatically. I’ve only used a GUI for local databases in the past. This is an area high on my list of things to learn. I think it’s essential with today’s connected world and what people expect from websites and apps.</p><p>That’s it for this part of this chapter. The small example because so big I haven’t worked on the practice problems at the end of the chapter yet. That will come next. I’m working on sticking to a schedule with this thing and that means something goes out today.</p><p>As always, thank you Al Sweigart for, not only his excellent book (found here <a href="http://automatetheboringstuff.com/#toc">http://automatetheboringstuff.com/#toc</a>), but for providing it online. My code is below and the link for my Github repo is<a href="https://github.com/gelbelle/Automate-the-Boring-Stuff">https://github.com/gelbelle/Automate-the-Boring-Stuff</a></p><pre>import customUtils as utils<br>import sys<br>import os<br><br><br>def delete_list():<br>    files = view_lists()<br>    choice = utils.create_options(<br>        &quot;\nChoose the list you would like to delete: &quot;, files)<br>    print(&quot;Your list  has the following items on it: &quot;)<br>    utils.print_list(utils.open_file(files[choice]))<br>    print(<br>        &quot;Are you sure you want to delete this list? [y/n]\n**You will not be able to recover the list afterwards**&quot;)<br>    if utils.getAns(input(), [&#39;y&#39;, &#39;n&#39;]) == &#39;y&#39;:<br>        os.remove(f&quot;lists/{files[choice]}.txt&quot;)<br>        print(f&quot;The list {files[choice]} has been deleted&quot;)<br>    else:<br>        print(f&quot;The list {files[choice]} has not been deleted&quot;)<br><br><br>def delete_items():<br>    files = view_lists()<br>    file = files[utils.create_options(<br>        &quot;\nChoose the list you would like to remove items from: &quot;, files)]<br>    items = utils.open_file(file)<br>    idx = utils.create_options(<br>        &quot;\nChoose the item you would like to delete\nTo end enter &#39;*&#39;&quot;, items)<br><br>    remove_these = []<br>    while True:<br>        remove_these.append(items[idx].strip())<br>        if input() == &#39;*&#39;:<br>            file = open(f&quot;lists/{file}.txt&quot;, &quot;w&quot;)<br>            for item in items:<br>                if item.strip(&quot;\n&quot;) not in remove_these:<br>                    file.write(f&quot;{item}&quot;)<br>            file.close()<br>            break<br><br><br>def update_list():<br>    files = view_lists()<br>    choice = utils.create_options(<br>        &quot;\nChoose the list you would like to add items to: &quot;, files)<br>    print(&quot;Your list already has the following items on it: &quot;)<br>    utils.print_list(utils.open_file(files[choice]))<br>    list_items = add_items()<br>    utils.save_list(files[choice], list_items)<br>    print(&quot;Your list has been saved&quot;)<br><br><br>def add_items():<br>    list_items = []<br>    print(&quot;\nEnter the items you would like to add to your list: &quot;)<br>    print(&quot;To complete and save your list enter &#39;*&#39;&quot;)<br>    while True:<br>        item = input()<br>        if item == &#39;*&#39;:<br>            return list_items<br>        else:<br>            list_items.append(item)<br><br><br>def is_available(list_name):<br>    while True:<br>        if list_name in utils.read_files(r&quot;lists&quot;):<br>            print(&quot;I&#39;m sorry, that list name is already taken.&quot;)<br>            print(<br>                &quot;Please enter another list name or enter &#39;*&#39; to return to the main menu.&quot;)<br>            list_name = input()<br><br>            if list_name == &#39;*&#39;:<br>                return False<br>        else:<br>            return True<br><br><br>def create_list():<br>    print(&quot;\nEnter a name for your list: &quot;)<br>    list_name = input()<br>    if is_available(list_name):<br>        list_items = add_items()<br>        print(&quot;Would you like to save your list? [y/n]&quot;)<br>        if utils.getAns(input(), [&#39;y&#39;, &#39;n&#39;]) == &#39;y&#39;:<br>            utils.save_list(list_name, list_items)<br>            print(&quot;Your list has been saved&quot;)<br>            return<br>        else:<br>            print(<br>                &quot;\nBy not entering a list name you have chosen not to save your list.&quot;)<br>            print(&quot;Are you sure? [y/n]&quot;)<br>            if utils.getAns(input(), [&#39;y&#39;, &#39;n&#39;]) == &quot;y&quot;:<br>                return<br><br><br>def open_list():<br>    files = utils.read_files(r&quot;lists&quot;)<br>    choice = utils.create_options(<br>        &quot;\nChoose the list you would like to read&quot;, files)<br>    contents = utils.open_file(files[choice])<br>    utils.print_list(contents)<br><br><br>def view_lists():<br>    print(&quot;\nThe lists available are: &quot;)<br>    files = utils.read_files(r&quot;lists&quot;)<br>    utils.print_list(files)<br>    return list(files)<br><br><br>def main():<br>    while True:<br>        choice = utils.create_options(&quot;\nWhat would you like to do?&quot;,<br>                                      [&quot;Create list&quot;, &quot;Delete list&quot;, &quot;View lists&quot;, &quot;Read list&quot;,<br>                                       &quot;Add list items&quot;, &quot;Delete list items&quot;, &quot;Quit&quot;])<br>        options = [create_list, delete_list, view_lists, open_list,<br>                   update_list, delete_items, sys.exit]<br>        options[choice]()<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>My custom utilities</p><pre>import sys<br>import os<br><br><br>def create_options(msg, options) -&gt; int:<br>    print(msg)<br>    # print(&quot;\n&quot;)  # For easier reading<br>    for i in range(len(options)):<br>        print(f&quot;{i}: {options[i].strip()}&quot;)<br><br>    ans = input()<br>    # List from range https://www.geeksforgeeks.org/range-to-a-list-in-python/<br>    return int(getAns(ans, str([*range(len(options))])))<br><br><br>def getAns(ans, options):<br>    while ans not in options:<br>        print(f&quot;You must choose one of the following: {options}&quot;)<br>        ans = input()<br>    return ans<br><br><br>def save_game(game, score):<br>    fileName = &quot;scores.txt&quot;<br>    print(&quot;Would you like to save your score? [y/n]&quot;)<br>    ans = getAns(input(), [&#39;y&#39;, &#39;n&#39;])<br>    if ans == &#39;y&#39;:<br>        print(&quot;Please enter your name&quot;)<br>        name = input()<br>        try:<br>            file = open(fileName, &quot;a+&quot;)<br>            file.writelines(f&quot;{game}:: {name}: {score}\n&quot;)<br>            file.close()<br>            sortFile(fileName)<br>        except FileNotFoundError as err:<br>            print(f&quot;Something has gone wrong: {err}&quot;)<br><br><br>def open_file(file_name):<br>    try:<br>        file = open(f&quot;lists/{file_name}.txt&quot;, &quot;r+&quot;)<br>        contents = file.readlines()<br>        return contents<br>    except FileNotFoundError as err:<br>        print(f&quot;Something has gone wrong: {err}&quot;)<br><br><br>def print_list(items):<br>    for item in items:<br>        print(item.strip())<br><br><br>def save_list(name, items):<br>    try:<br>        file = open(f&quot;lists/{name}.txt&quot;, &quot;a+&quot;)<br>        for item in items:<br>            if item.strip():<br>                file.write(f&quot;{item}\n&quot;)<br>        file.close()<br>    except FileNotFoundError as err:<br>        print(f&quot;Something has gone wrong: {err}&quot;)<br><br><br>def ask_save(msg):<br>    print(f&quot;{msg} [y/n]&quot;)<br>    ans = getAns(input(), [&#39;y&#39;, &#39;n&#39;])<br>    if ans == &#39;y&#39;:<br>        print(&quot;Please enter a name for your list: &quot;, end=&quot;&quot;)<br>        return input()<br><br><br>def sortFile(fileName):<br>    with open(fileName, &#39;r&#39;) as reader:<br>        lines = reader.readlines()<br>    with open(fileName, &quot;w&quot;) as writer:<br>        for score in sorted(lines):<br>            writer.write(score)<br><br><br>def playAgain(game, score):<br>    print(&quot;Would you like to play again? [y/n]&quot;)<br>    if getAns(input(), [&#39;y&#39;, &#39;n&#39;]) == &#39;n&#39;:<br>        save_game(game, score)<br>        sys.exit(0)<br><br><br>def read_files(dir_name):<br>    files = []<br>    for entry in os.scandir(dir_name):<br>        if entry.is_file():<br>            idx = entry.name.index(&quot;.&quot;)<br>            files.append(entry.name[:idx])<br>    return files</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1983fdcfb4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff — Chapter Three]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-three-1a7b17273832?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a7b17273832</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Wed, 17 May 2023 19:27:07 GMT</pubDate>
            <atom:updated>2023-05-17T19:27:07.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Journey with Automate the Boring Stuff — Chapter Three</h3><p>Here we are, moving right along. Chapter 3 is all about how functions work. It talks about the “difference” between arguments and parametres, the return statement, what calling a function is, and passing it information. I could only do a disservice to Sweigart’s explanation, please read it yourself if you’re interested. <a href="https://automatetheboringstuff.com/2e/chapter3/">https://automatetheboringstuff.com/2e/chapter3/</a></p><p>It uses a Magic 8 Ball program to explain all this terminology. If you haven’t seen one of these then for one, you are younger than I, but you’re missing out on the excitement of determining your future. Check them out on YouTube. <a href="https://www.youtube.com/watch?v=hP2kkjbFbHc">https://www.youtube.com/watch?v=hP2kkjbFbHc</a> I chose not to implement this one, I didn’t feel like I would get much out of implementing a long switch statement. Switch statements are very useful, but not very exciting to create. Lots of copy paste, rather boring in my opinion.</p><p>It explains the call stack, one of the better explanations I’ve encountered. Again, check it out if this is one of the mysteries of life/coding for you. Although, this could be due to the sheer number of times I’ve read and seen this explained too. Eventually things have to start making sense, right?</p><p>Another tricky concept is next, scope. What a flexible word, it’s usually something to do with sight, right? Telescope. Microscope. But that’s not all, you can telescope something by folding it up, you can investigate something by scoping it out, and finally, scope is also everything within your bubble. That’s how it is meant in the coding sense. The scope of a variable is where it can be used. This section is a bit of a mind-bender with multiple variables using the same name, read through it carefully!</p><p>The final lesson in this chapter is on exception handling, basically deal with errors within your program so it doesn’t crash. The practice program at the end of the chapter is a good place to play with this. You need the user to enter a number, if they don’t your program will break. How do you fix this? Spoiler alert: handle the error!</p><p>Before we get to that practice program there is one more example. It’s a rather mesmerizing animated zigzag. In this case I just copied their program. My brain doesn’t quite see how to make things move with programming, at least not yet. Something else to add to the extremely long list of things I want to learn. I need at least 10 lifetimes.</p><p>I did make one alteration, at one point due to a typo I created a different animation that was also fun to watch to I added a small menu for the user to choose which one to see. The intention of this program was to show people the use of a `try` block, or exception handling. Their program will continue the animation until you force an exception by using ctrl-c. For those that don’t play in the command line, this is the keyboard interrupt for any process running. It might be Linux and Mac only, I’ve never tried it on Windows. Once the exception occurs the program exits gracefully. No messy looking error messages.</p><p>Finally, we get to the practice program and some real code writing! The practice problem is to implement the Collatz Sequence. Given any number this program will eventually reach one. If the given number is even then divide it by two and call the program again (note the recursion, I don’t think we’ve covered that yet). Again, tricky topic, perhaps he decided to cram all the challenging concepts into one chapter? Recursion is where a program has a particular case where it ends and if it doesn’t get there it continues to call itself with new values. There’s a nice video explanation on YouTube. <a href="https://www.youtube.com/watch?v=rf60MejMz3E">https://www.youtube.com/watch?v=rf60MejMz3E</a></p><p>If you watched the recursion video you may have noticed that it referenced the call stack, we learned about that a few paragraphs ago. It’s all coming together. The error handling comes into play in this program too, what if your user gives you a non-number? How do you divide the letter “d”? You’ll use a `try` block to “catch” if the user entered anything that wasn’t a number the program will ask them to enter a number again, and again, and again, until they do what they’re supposed to do. Then it prints the sequence of numbers and exits. No gross errors when they don’t listen.</p><p>Here’s my code which I’m sure would be nearly identical to the book if it wasn’t a practice problem.</p><pre>def collatz(num: int):<br>    if num &lt;= 1:<br>        return num<br><br>    if num % 2 == 0:<br>        num = num//2<br>    else:<br>        num = 3*num+1<br>    print(num)<br><br>    return collatz(num)<br><br><br>def main():<br>    print(&quot;Please enter the number you would like to run through the Collatz sequene: &quot;)<br><br>    while True:<br>        try:<br>            num = int(input())<br>            collatz(num)<br>            break<br>        except ValueError:<br>            print(&quot;You must enter a whole number: &quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>As always, I encourage you to check out Al Sweigart’s book for yourself. Well, all of his books. Go to the <a href="https://automatetheboringstuff.com/">Automate the Boring Stuff</a> website to find the one I’m using.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a7b17273832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff — Chapter Two, part two]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-two-part-two-be1ae08258c3?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1ae08258c3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Sun, 14 May 2023 01:47:21 GMT</pubDate>
            <atom:updated>2023-05-17T18:35:26.693Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Journey with Automate the Boring Stuff — Chapter Two, part two</h3><p>There isn’t much more to say about chapter two, but there was another game, Rock, Paper, Scissors. It was the addition of this game to the fold that prompted me to write my customUtils library. I was tired of writing while loops to make sure people followed the directions. (Boy was I glad I did, there are lots of mini games to write in this book)</p><p>I did the same thing with Rock, Paper, Scissors that I did with Guess the Number. It told me what the program was going to be and gave me output. I made my own before reading on.</p><p>I started very basic and then built upon it. This is something I working on. I’d rather just start coding and when I see somewhere I can add efficiency I usually just do it then. This often leads to weird bugs and lost time. If I had learned to slooooooooow down, I wouldn’t have had to deal with them. So this book is also about training myself to write it the long way and then improve it. Improving it as you go just creates problems!</p><p>Sadly, this program still uses a stupid number of if statements. I shortened that a wee bit my nesting them one level deep.</p><pre>if player == computer:<br>            print(f&quot;It&#39;s a tie, you both picked {words[player]}&quot;)<br>            ties += 1<br>        elif player == &#39;r&#39;:<br>            if computer == &#39;s&#39;:<br>                print(&quot;You win! rock beats scissors&quot;)<br>                wins += 1<br>            else:<br>                print(&quot;You lost this one, paper beats rock&quot;)<br>                losses += 1<br>        elif player == &#39;p&#39;:<br>            if computer == &#39;r&#39;:<br>                print(&quot;You win! paper beats rock&quot;)<br>                wins += 1<br>            else:<br>                print(&quot;You lost this one, scissors beats paper&quot;)<br>                losses += 1<br>        else:<br>            if computer == &#39;r&#39;:<br>                print(&quot;You win! scissors beats paper&quot;)<br>                wins += 1<br>            else:<br>                print(&quot;You lost this one, rock beats scissors&quot;)<br>                losses += 1</pre><p>I still thing there’s probably a more elegant way to do this. Like passing pairs and remembering which one is the player and which the computer. The function only needs to know which letter beats which and then you can use that to print your message and tell the player if it was them or the computer that won. Needless to say, I haven’t done that yet.</p><p>My approach used a list and a dictionary to hold the options. (I just noticed that this can be done with one data structure not two) They are</p><pre>possibilities = [&quot;r&quot;, &quot;p&quot;, &quot;s&quot;]<br>    words = {<br>        &quot;r&quot;: &quot;rock&quot;,<br>        &quot;p&quot;: &quot;paper&quot;,<br>        &quot;s&quot;: &quot;scissors&quot;<br>    }</pre><p>Possibilities is used to determine if the player picked a valid move using `player in possibilities`. The second maps the possibilities to the actual words. Another thing I just noticed, the dictionary is only used once, in the tie case. I could use it to output the message regarding wins and losses. I was making me a little cringy hard coding in the words. I’ve seen a fair number of things that could be improved. Writing this out is a helpful exercise in addition to the programs.</p><p>There isn’t much more to it than that. A little bit of pretty formatting for the title because this is a command line game and score display.</p><pre>import random<br>import customUtils<br><br><br>def main():<br>    possibilities = [&quot;r&quot;, &quot;p&quot;, &quot;s&quot;]<br>    words = {<br>        &quot;r&quot;: &quot;rock&quot;,<br>        &quot;p&quot;: &quot;paper&quot;,<br>        &quot;s&quot;: &quot;scissors&quot;<br>    }<br>    wins = 0<br>    losses = 0<br>    ties = 0<br>    while True:<br>        computer = random.choice(possibilities)<br><br>        print(&quot;\n===============================\n&quot; +<br>              &quot;Lets play rock, paper, scissors&quot; +<br>              &quot;\n===============================&quot;)<br>        print(f&quot;{wins} wins, {losses} losses, {ties} ties\n&quot;)<br>        print(&quot;Enter your move: (r)ock, (p)aper, (s)cissors&quot;)<br><br>        player = customUtils.getAns(input(), possibilities)<br><br>        if player == computer:<br>            print(f&quot;It&#39;s a tie, you both picked {words[player]}&quot;)<br>            ties += 1<br>        elif player == &#39;r&#39;:<br>            if computer == &#39;s&#39;:<br>                print(&quot;You win! rock beats scissors&quot;)<br>                wins += 1<br>            else:<br>                print(&quot;You lost this one, paper beats rock&quot;)<br>                losses += 1<br>        elif player == &#39;p&#39;:<br>            if computer == &#39;r&#39;:<br>                print(&quot;You win! paper beats rock&quot;)<br>                wins += 1<br>            else:<br>                print(&quot;You lost this one, scissors beats paper&quot;)<br>                losses += 1<br>        else:<br>            if computer == &#39;r&#39;:<br>                print(&quot;You win! scissors beats paper&quot;)<br>                wins += 1<br>            else:<br>                print(&quot;You lost this one, rock beats scissors&quot;)<br>                losses += 1<br><br>        customUtils.playAgain(&quot;Rock Paper Scissors&quot;, [<br>                              f&quot;wins: {wins}&quot;, f&quot;losses: {losses}&quot;, f&quot;ties: {ties}&quot;])<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Here’s their suggested code. Mine may not be pretty, but at least I eliminated a whole bunch of ifs.</p><pre>import random, sys<br><br>print(&#39;ROCK, PAPER, SCISSORS&#39;)<br><br># These variables keep track of the number of wins, losses, and ties.<br>wins = 0<br>losses = 0<br>ties = 0<br><br>while True: # The main game loop.<br>    print(&#39;%s Wins, %s Losses, %s Ties&#39; % (wins, losses, ties))<br>    while True: # The player input loop.<br>        print(&#39;Enter your move: (r)ock (p)aper (s)cissors or (q)uit&#39;)<br>        playerMove = input()<br>        if playerMove == &#39;q&#39;:<br>            sys.exit() # Quit the program.<br>        if playerMove == &#39;r&#39; or playerMove == &#39;p&#39; or playerMove == &#39;s&#39;:<br>            break # Break out of the player input loop.<br>        print(&#39;Type one of r, p, s, or q.&#39;)<br><br>    # Display what the player chose:<br>    if playerMove == &#39;r&#39;:<br>        print(&#39;ROCK versus...&#39;)<br>    elif playerMove == &#39;p&#39;:<br>        print(&#39;PAPER versus...&#39;)<br>    elif playerMove == &#39;s&#39;:<br>        print(&#39;SCISSORS versus...&#39;)<br><br>    # Display what the computer chose:<br>    randomNumber = random.randint(1, 3)<br>    if randomNumber == 1:<br>        computerMove = &#39;r&#39;<br>        print(&#39;ROCK&#39;)<br>    elif randomNumber == 2:<br>        computerMove = &#39;p&#39;<br>        print(&#39;PAPER&#39;)<br>    elif randomNumber == 3:<br>        computerMove = &#39;s&#39;<br>        print(&#39;SCISSORS&#39;)<br><br>    # Display and record the win/loss/tie:<br>    if playerMove == computerMove:<br>        print(&#39;It is a tie!&#39;)<br>        ties = ties + 1<br>    elif playerMove == &#39;r&#39; and computerMove == &#39;s&#39;:<br>        print(&#39;You win!&#39;)<br>        wins = wins + 1<br>    elif playerMove == &#39;p&#39; and computerMove == &#39;r&#39;:<br>        print(&#39;You win!&#39;)<br>        wins = wins + 1<br>    elif playerMove == &#39;s&#39; and computerMove == &#39;p&#39;:<br>        print(&#39;You win!&#39;)<br>        wins = wins + 1<br>    elif playerMove == &#39;r&#39; and computerMove == &#39;p&#39;:<br>        print(&#39;You lose!&#39;)<br>        losses = losses + 1<br>    elif playerMove == &#39;p&#39; and computerMove == &#39;s&#39;:<br>        print(&#39;You lose!&#39;)<br>        losses = losses + 1<br>    elif playerMove == &#39;s&#39; and computerMove == &#39;r&#39;:<br>        print(&#39;You lose!&#39;)<br>        losses = losses + 1</pre><p>The book, including the example code and explanations can be found at <a href="https://automatetheboringstuff.com/2e/chapter2/">https://automatetheboringstuff.com/2e/chapter2/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1ae08258c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff — Chapter Two]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-chapter-two-e4015557f67f?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4015557f67f</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Sun, 07 May 2023 01:37:18 GMT</pubDate>
            <atom:updated>2023-05-07T01:37:18.638Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Journey with Automate the Boring Stuff — Chapter Two</h3><p>Things are getting slightly more interesting. Not the billionth (definitely not exaggerating here…well…maybe a little) explanation of the different types of flow control, but there was a little bit of coding involved. Actual little programs, not one or two liners to type into the interactive environment.</p><p>Now this is getting good, all I want to do is program. I do the background reading so I can create a programming without spending four days on <a href="https://stackoverflow.com/">Stackoverflow</a> while tearing my hair out. Granted, there’s nothing terrible exciting here either. The explanations are clear and there’s some diagrams that really help illustrate what’s happening. (as a visual learner I thank you Mr. Sweigart)</p><p>I did get a tidbit or two, (yet again reinforcement to sloooooooow down) I learned the exact definition of continue. I know the gist of what it does and maybe it’s a wee bit different in other languages, but I know it means keep going with the loop. However, in Python it returns you to the top of the loop regardless of where you are in that loop.1 This gave me a little bit of a rabbit hole to detour down as I investigated if this was the case in all languages, at least the ones I know or attempted to know.</p><p>It looks like it does mean go back to the top of the loop. I don’t think I was ever totally clear on that, it’s not something I use often. Javascript, R, and C all seem to have this behaviour, well it’s next in R, but same thing. 234</p><p>And now, finally, the code. Automate the Boring Stuff gives you the full code to get a minimal viable program going, but that’s too easy. I’m here to learn. Their example for loops and if/else statements is Guess the Number.</p><p>Prior to reading their code, I made my own. It started small, I just did the basic set a random number and then get input from the user. Is the same, higher, lower? Then I got fancy. I put in error checking. If it’s not a number you have to guess again, letters don’t work in this version of Guess the Number. If you were playing with ascii values then it would be another story.</p><pre>import random<br>import customUtils<br><br>def main():<br>    number = random.randint(1,100)<br>    numGuesses = 0<br>    scores = []<br>    <br>    while True:<br>        print(&quot;Guess a number between 1 and 100&quot;)<br>        try:<br>            guess = int(input())<br>            numGuesses += 1<br><br>            if guess &lt; number:<br>                print(f&quot;{guess} is too low.\nGuess again&quot;)<br>            elif guess &gt; number:<br>                print(f&quot;{guess} is too high.\nGuess again&quot;)<br>            else:<br>                print(f&quot;Congratulations, {guess} is correct.\nIt took you {numGuesses} guesses&quot;)<br>                scores.append(numGuesses)<br>                customUtils.playAgain(&quot;Guess the Number&quot;, scores)<br>                number = random.randint(1,100)<br>                numGuesses = 0<br>        except ValueError:<br>            print(&quot;You must enter a number&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>You may notice in the else block an expression that you’ve never seen before, customUtils.playAgain(). After building a couple of these toy programs with the book I realized I was duplicating myself so I built my own little library. Nothing fancy and I’ve probably duplicated work that’s already been done, but it was fun and nice exercise to work through.</p><p>My function takes two arguments, the name of the current game you’re playing and a list of your scores. It uses them to save your game scores if you want to. If you’re interested in this function and the other I wrote to go with it I’ve made a repo with my experiments from the book on <a href="https://github.com/gelbelle/Automate-the-Boring-Stuff.git">Github</a>.</p><p>I had more fun exploring what I needed to include in my library than writing the program, but any chance to code is a good thing in my world.</p><p>Here’s the original program below, as you can see it’s not too different from mine.</p><pre># This is a guess the number game.<br>import random<br>secretNumber = random.randint(1, 20)<br>print(&#39;I am thinking of a number between 1 and 20.&#39;)<br><br># Ask the player to guess 6 times.<br>for guessesTaken in range(1, 7):<br>    print(&#39;Take a guess.&#39;)<br>    guess = int(input())<br><br>    if guess &lt; secretNumber:<br>        print(&#39;Your guess is too low.&#39;)<br>    elif guess &gt; secretNumber:<br>        print(&#39;Your guess is too high.&#39;)<br>    else:<br>        break    # This condition is the correct guess!<br><br>if guess == secretNumber:<br>    print(&#39;Good job! You guessed my number in &#39; + str(guessesTaken) + &#39;<br>guesses!&#39;)<br>else:<br>    print(&#39;Nope. The number I was thinking of was &#39; + str(secretNumber))</pre><ol><li>Sweigart, A. (2020) <em>Automate the Boring Stuff with Python: Practical Programming for Total Beginners</em>, 2nd Ed. No Start Press. Retrieved from <a href="https://automatetheboringstuff.com/2e/chapter2/">https://automatetheboringstuff.com/2e/chapter2/</a></li><li>MDN. (2023) <em>continue</em>. Retrieved from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue</a></li><li>Data Mentor. (n.d.). <em>R break and next Statement.</em> Retrieved from <a href="https://www.datamentor.io/r-programming/break-next/">https://www.datamentor.io/r-programming/break-next/</a></li><li>Tutorials Point. (n.d.). <em>continue statement in C. </em>Retrieved from <a href="https://www.tutorialspoint.com/cprogramming/c_continue_statement.htm">https://www.tutorialspoint.com/cprogramming/c_continue_statement.htm</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4015557f67f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey with Automate the Boring Stuff]]></title>
            <link>https://medium.com/@GelBelleH/my-journey-with-automate-the-boring-stuff-a01115557c57?source=rss-52844f1c779e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a01115557c57</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Angeleah Hoeppner]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 23:57:27 GMT</pubDate>
            <atom:updated>2023-04-29T23:57:27.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Unsurprisingly, the journey through <a href="https://automatetheboringstuff.com/"><em>Automate the Boring Stuff with Python: Practical Programming for Total Beginners</em></a> by Al Sweigart started the same way many others have started, with the boring stuff.</p><p>As someone who has been programming for more years than it feels possible I have can’t even count how many times I’ve learned what the difference between an int and a float is. I’m sure I’m not alone here. You decide to learn a new language and then proceed to skip over the first two or three chapters only to find that you missed something very important in among all the, “this is a variable” stuff.</p><p>I wanted to do it differently this time. I already know Python, I’m not an expert by any means, but I’m alright. Still, I made myself slow down a little. What I’ve found as I’ve learned Python is that it has some tricks I’ve never encountered before. So I read about the difference between ints and floats again and I learned what an if statement is again, but I did learn something new.</p><p>Python does lists (arrays) a bit differently than I was used to. It’s a pass by reference type language. I didn’t know that before and hadn’t thought about it either. Luckily, I have a decent handle on this concept from my single programming class throughout the whole of my BSc. (That’s an issue for another day)</p><p>While the explanation wasn’t earth shattering by any stretch it was quite well done. The important part to me was the potential side effects that this could cause. If I hadn’t slowed down and reread the basics for the billionth time I wouldn’t have known.</p><p>This was a good lesson for me regarding patience. It seems to be one I need to learn <strong>a lot.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a01115557c57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>