Categories
programming Python

Python: Using Dictionaries Instead of If/Else Statements for Handling User Input

I’ve recently learned that you can use a dictionary in place of pretty much any series of if/else statements which reduces and simplifies your code, making it easier to read and maintain. Here’s an example from my text-based adventure game, written in Python, which can be found here on github.

First, the original code with an ugly if/else tree:


def keydown(self, user_input):
 
 	if user_input == 'n':
	    current_location.move_north()
 
 	elif user_input == 's':
	    current_location.move_south()
 
 	elif user_input == 'e':
	    current_location.move_east()
 
 	elif user_input == 'w':
	    current_location.move_west()
 
 	elif user_input == 'q':
 	    quit_game()
 
 	elif user_input in {'x', 'search'}:
	    search_area(current_location)
        else:
            print "Please type 'h' for help."
	self.narrative(player.get_coords())

Note how rigid this structure is in that you can’t modify it or change behavior in subtle ways very easily.

And now here’s the same method using a dictionary which pairs input choices (keys) with method names (values) to be called upon match. The trick here, as you can see, is to append parentheses — () — to the end of the returned dictionary value after having found a match between user input and a dictionary entry’s key. Thus the dictionary value will simply store the name of any method you wish to call, paired with a key string representing the user’s input which triggers that method call:


def keydown(self, user_input):
		
    inputs = {"n": player.move, "s": player.move, 
    "e": player.move, "w": player.move, "q": player.quit_game, "x": player.search_area}

    if user_input in inputs:
        if user_input in ["n", "s", "e", "w"]:
	    inputs[user_input](user_input)  
	else:  # otherwise don't pass a parameter 
            inputs[user_input]()
    else:
	print "Please type 'h' for help."
    self.narrative(player.get_coords())

User input of “n” matches a key of the same name in inputs (dictionary), which then produces the string player.move, to which is appended a pair of parentheses, (), and thus the player instance’s move method is called. Since “n” user_input is found in the list ["n", "s", "e", "w"], user_input is passed as a parameter to player.move, like so: player.move(user_input).

You can see that besides changing from an if/else tree to a dictionary, and then traversing that dictionary with my user’s input as a key, I also handled movement differently. Instead of calling a separate method for movement in each direction (n, s, e, w), I call the same function and pass the direction as a parameter, still using if/else statements for deciding whether or not to pass parameters (true for directional movement, not true for other user input.) These changes not only makes the code a bit cleaner but they also make it easier to change the behavior of the game in response to user input. Adding or changing features is much simpler than with strict use of if/else trees.

I hope you found this helpful and happy coding.

Categories
programming Python

Virtualenv (Getting Started With Python)

Setting Up Your First VirtualEnv

Let’s cover first steps in Python programming as I learn them myself. Namely, this is about setting up your first virtualenv in which to write programs which make use of a module like kivy, flask, pygame or django, for example. It’s very simple but I rarely see anyone breaking it down like this in one place, hence this post.

  1. Installation and Editor for Writing Your Code
  2. You need to install Python if you’re unfortunate enough to be using Windows (and I am, so I won’t hold it against you). Otherwise you’re already almost ready to go. In Linux I recommend just using Vim as an editor. In Windows I recommend Sublime.

  3. Setting up Virtual Environments
  4. It is strongly recommended by others to use virtualenv when developing with Python. This is for Windows users and it is assumed you installed Python to a directory with the path ‘C:Python27’. I’ll add Linux commands when time permits. Anything in brackets ([]) is meant as a variable entirely to be replaced as appropriate.

    1. Install Python
    2. Create your own project/working directory. Mine is simply a ‘python’ folder in my Documents folder. CD into this folder from the command line.
      mkdir [dir name]
      (add C:Python27Scripts to Windows path and may need to reboot)
    3. Download and run get-pip.py from inside your new python folder. (May not need to do this step https://pip.pypa.io/en/stable/installing/)
      python get-pip.py
    4. python -m pip install virtualenv
    5. virtualenv [virtualenv name] Example: virtualenv kivy This will create a new directory inside your current directory with the [virtualenv name] you provided.
    6. cd [virtualenv name]/Scripts
    7. activate This activates the virtual environment which will show up as ([name]) in your command line before the path.
    8. (inside [name] virtualenv:)
      python -m pip install [a space-separated list of all the dependencies of the module you are intending to work with] Example: python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
    9. python -m pip install [module itself] This installs the module itself. Example: python -m pip install kivy

Hopefully the kivy example clarifies things a bit further. If you are having trouble setting up your first virtualenv, feel free to ask questions and I will help as best I can.

For ease of reference visually, here are all the steps once again without commentary/explanation using the kivy example for clarity:

  1. Install python
  2. Create your own project/working directory and CD into this folder from the command line.
    mkdir [dir name]

  3. python get-pip.py
  4. python -m pip install virtualenv
  5. virtualenv kivy
  6. cd kivy/Scripts
  7. activate
  8. python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
  9. python -m pip install kivy
Categories
programming

#100DaysofCode

I’m committing to #100DaysofCode to improve my programming skills, begin to build a portfolio on my at-present bleak-looking github page and, of course, improve my prospects of starting a development career here in Saigon. I’m not particularly experienced with any type of programming outside of a few college- and graduate-level courses over the years, so wish me luck and consider joining me! I’ll be tweeting about it at @2nd0pinion and blogging a bit here as time permits since I’m also teaching and taking a series of Python courses through Coursera.

Update: I’ve just completed 21 days of daily coding and I feel like I’ve learned and reinforced a lot of knowledge. My progress is being helped quite a bit with what I am learning through my Coursera python classes. I’ve completed the first course and am now starting the second.

Categories
IT helpdesk

Windows 10 Telemetry (Disabling It)

I saw similar, unusual behavior on both my desktop and laptop today, both of which are running Windows 10. I saw the icons on the task bar disappearing and repainting themselves several times in a row. I started task manager and saw that 20% of CPU was intermittently being consumed by a process with the word telemetry in it. A quick Google search uncovered the following article:

https://blog.neweggbusiness.com/windows/should-you-disable-windows-10-telemetry/

This is pretty disturbing to me, though, sadly, not surprising considering how well both the Chinese government and the NSA seem to get along with Microsoft. Needless to say, it’s a good idea to minimize the risks of invasion of privacy these days at the hands of any large and powerful corporation or other such entity. With that aim in mind, the article links to a github script written in Python which appears to do a quite good job of getting rid of (most of?) the MS spy tools that come shipped with Windows 10.

I must admit that I have nostalgic feelings about Windows going all the way back to 3.11, Windows for Workgroups. And so it’s really sad to see how disgraced the company has become by it’s own actions, not to mention the horror stories I’ve heard from people who’ve worked there.

If only Linux could run PC games so I could free myself of this devil-ware forever …

Categories
programming

My First Github Project

I am both excited and embarrassed to share my first bit of Python on github. It’s a very short text-based adventure game called ‘Realm of Reckoning’, still very much an early work in progress. It’s been a great exercise over the last couple weeks in learning Python and was inspired by an assignment from a chapter of ‘Learn Python the Hard Way’.

I’m currently taking the first in a 7-part series of courses in Coursera on Python programming as well as finishing ‘Learn Python the Hard Way’ and reading ‘Think Python’. I had taken a C++ class 20 years ago and since then had also taken both an undergrad- and a graduate-level Java course which also covered a bit of C, as well as a course in web design (HTML, CSS, JQuery) and I have to say, based on my limited experience with programming languages, Python is much easier to read and much more intuitive with which to write than any other language I’ve used.

Here it is:
https://github.com/sartreszche/realmofreckoning

Categories
HTML/CSS

How to Customize Your Existing WordPress Theme Using CSS

If, like me, you know how to use CSS more or less and you just want to tweak an existing theme but aren’t sure how to do that from within a WordPress installation on your self-hosted web site, there’s good news — it’s extremely easy to do. Here are the steps involved.

  1. Log in to your WordPress Admin page
  2. On the left-hand vertical menu, click on ‘Appearance’ and then the sub-menu item ‘Edit CSS’
  3. Here you can edit your CSS til your heart’s content, overriding default element behaviors, creating specific IDs, etc.
edit-css
Click ‘Edit CSS’ from within the ‘Appearance’ menu of WP Admin Dashboard.

It’s really that simple. Happy coding!

Categories
IT helpdesk

Syncing Your PDF-reading Experience Across Devices

There are a few steps to take in order to be able to read the same pdf document from the last page you were reading on another device. Here’s a brief walk-through on how to make this feature actually work for you.

  1. Download and install the free Adobe reader for all of your devices. (*This was tested on desktops and laptops with Windows 10 and a tablet with Android.)
  2. Open Adobe reader on each device and go to Preferences/Documents, making sure that the option to restore last view when reopening documents is checked.

    Edit –> Preferences (or simply Ctrl+K), Select ‘Documents’ from the vertical list at the left and check the box labeled ‘Restore Last View Settings When Reopening Documents’

    pdf-restore-last-view
    Edit Document Preferences in PDF Reader to Restore Last View when reopening any document.
  3. Create an Adobe account if you haven’t already got one and then log into your Adobe account from within Adobe Reader on each device. This worked right away for me on some devices but on my laptop, I kept getting a ‘networking unavailable’ message before presenting credentials to log in. This was resolved by adjusting the default ‘Internet’ settings inside Preferences as follows.
    1. Edit –> Preferences (or simply Ctrl+K), Select ‘Internet’ from the vertical list at the left and then click the ‘Internet Settings’ button at the right.
    2. Click ‘LAN Settings’ button in the pop-up window.
    3. Uncheck the boxes next to ‘Use automatic configuration script’ and ‘Use a proxy server […]’, unless of course you actually use either of these, since most people don’t.
    4. Make sure to click ‘ok’ button on both ‘LAN Settings’ pop-up window and the main ‘Preferences’ pop-up window.
    pdf-internet-1
    (1) click ‘Internet Settings’ button
    pdf-internet-2
    (2) Click ‘LAN Settings’
    pdf-internet-3
    (3) Uncheck ‘Use automatic configuration script’ and ‘Use a proxy server […]’
    make-sure-to-click-ok
    Be sure to click ok (or in some other programs, ‘save/save settings’), always, when changing settings on Windows.
  4. Upload any documents you want to access from all devices to your Adobe document cloud (once) associated with the same account to which you logged in on each device. You can upload your ebooks once to your document cloud and then simply remember to open the document cloud version of your book to be able to retrieve and store current reading location from any device using your Adobe account.

    To save a local document to Adobe Document Cloud:

    1. Open your local pdf file in Adobe Reader
    2. Click ‘File’, then ‘Save as …’ from the Menu bar, or simply hit Shift+Ctrl+’s’
    3. In the ‘Save As’ pop-up, select ‘Document Cloud’ from the vertical list at left and on the right you have the option to create a folder, then select it, or simply save the file to the Document Cloud without a folder to contain it.
    another-step-save-to-adobe-document-cloud
    Save to Adobe document cloud.
  5. Open Adobe Reader, log in, and open any of the files you uploaded to Document Cloud to read from the last page synced by any other device you logged into with the same account previously.
    1. Open Adobe Reader.
    2. Go to ‘Home’
    3. Under ‘Storage’ at the left, go to ‘Document Cloud’
    4. (4) Select to open whichever file you wish to read.
    open-from-cloud
    (3) Go to Document Cloud and select a previously-uploaded file to read it.

So simple, huh? It would be but for the network-connectivity-breaking default Preferences/Network settings I encountered at the time of this writing.

Categories
programming

Truth Tables for Programming

Truth tables come from Boolean Algebra and the associated operators are used in programming to create logic structures using if, while and other statements to test variables and/or user input and direct the program’s response to such variables/input.

We have as operators AND, OR, NOT, NOT OR and NOT AND, resulting in an output of either TRUE or FALSE.

Here is a table delineating how they work.

Operation Result
NOT FALSE TRUE
NOT TRUE FALSE
TRUE OR FALSE TRUE
TRUE OR TRUE TRUE
FALSE OR TRUE TRUE
FALSE OR FALSE FALSE
TRUE AND FALSE FALSE
TRUE AND TRUE TRUE
FALSE AND TRUE FALSE
FALSE AND FALSE FALSE
NOT(TRUE OR FALSE) FALSE
NOT(TRUE OR TRUE) FALSE
NOT(FALSE OR TRUE) FALSE
NOT(FALSE OR FALSE) TRUE
NOT(TRUE AND FALSE) TRUE
NOT(TRUE AND TRUE) FALSE
NOT(FALSE AND TRUE) TRUE
NOT(FALSE AND FALSE) TRUE
Other symbols
1 != 0 TRUE
1 != 1 FALSE
0 != 1 TRUE
0 != 0 FALSE

 

I am presently learning Python with ‘Learn Python the Hard Way’, among other resources, and this is a book I highly recommend for beginners to programming.  You can pick up a free copy of it here.  The topic of truth tables is covered in Exercise 27.

Categories
IT helpdesk programming

Cygwin + Windows Makes it Better

Cygwin is incredibly easy to install on Windows.  I remember trying to install it several years ago and giving up in frustration, preferring to set up a dual-boot for the first time instead.  But nowadays it is a no-brainer.

cygwin_logo-200x111

The only unusual thing I’ve run into which I will make note of here is that adding features after initial installation (simply) requires you to run the installer (.exe) again.  You simply choose the additional features you want to add and then you’re good to go.  I’m not sure if this overwrites configuration files, so make sure you back those up before adding new features, just in case.

I started using Cygwin regularly when I was working as a data center tech for Amazon* and was running Windows.  Though I later gave up Windows for Ubuntu, I was quite happy having Cygwin instead of the Windows command line to work with, especially when frequently ssh-ing into instances to run diagnostics and manage RAID arrays.

Nowadays I’m stuck with Windows for (1) games and (2) music production and so Cygwin is a wonderful improvement to the otherwise play-pen-like experience of working on Windows.  Besides, it gives you a chance, if you haven’t already, to learn and keep the rust off of your Linux command line skills while still being able to play all of your Steam games when you need a respite.  You can’t beat that.

 

Here is where you can go to install Cygwin:

https://cygwin.com/install.html

 

*I do not recommend taking this sort of job unless you’re fresh out of college, a very recent career changer and in desperate need of any kind of IT experience or money.  I may write more about that later.

 

 

Categories
Uncategorized

Thoughts on Transitioning

The purpose of this post will be to share a few thoughts I’ve been having about my present circumstances, having recently moved to Saigon.

Transitioning into a different culture is a very slow process and I am not convinced that it even begins until a basic understanding of the language is achieved.  With that said, I will share reflections on basic aspects of my life in Saigon.  In other posts I will continue this thread of thoughts about Saigon and my home before that,  Nanchang, China.

In moving 10,000 miles from home I think support is critical but hard to find, so far, and this is probably mostly my fault and somewhat to do with having so much to get situated with when first arriving.  It can feel overwhelming in our moments of tiredness.  Also, arriving as I did — sick, with a headache for 5 days, no job, having to find an apartment and develop a new love relationship — means I have had a lot on my plate these first two months.

Therefore, I am immensely appreciative, no, down-right in awe of my girlfriend, Ly, for sticking by my side and helping me so much in these last two months.  Aside from my grandmother and my mother, I don’t believe I have ever nor will ever meet a more generous, caring, loving or devoted woman in my entire life.  These last two months would have been much more difficult without her and she makes my days a thousand times brighter with her joyful presence.

In fact, I haven’t felt so attached, emotionally, to someone in a long time and it’s kind of scary, to be honest.  I am having to learn to build trust again after denying it to others for so long.  And so I worry whether she has the patience to wait for me to complete this heavy task.  Although it is not easy,  it is incredibly worthwhile.  It’s much better to make the effort and to allow yourself the opportunity to love again no matter how hard you fell when things didn’t work out in the last relationship.  Life is about taking chances and following your intuition (sixth sense, as Ly calls it), not having everything pre-planned and safe and sure.

With all of that said, I know well it is important to develop good habits, routines and relationships, not to stack everything on the shoulders of the one I love, not to act like a helpless child even though starting over in a new culture often forces us into such helplessness like a learned behavior, over and over again.  It’s important to look for ways to do things myself and retain my autonomy, maintain a perspective which nurtures inward strength and focus.  This strengthens our relationships.

How I most effectively rekindle my strength of self-reliance is through the writings of those I most admire spiritually and intellectually.  Right now I am reading Jiddu Krishnamurti and Thich Nhat Hanh and as always being inspired by insight upon insight from simply the reading of those written words.  I will endeavor to share some of those insights in the coming posts.

That’s pretty much all I had to say at the moment and I hope others might find it useful.  Please feel free to comment if you’ve had similar struggles and experience.