Intro to Python, Chapter 1 – Arithmetic and Variables


Seated in his cubicle, Baldric tried to block out the buzz of busy clerks scattered about the office. The usual mix of apathy, grumpiness, and existential dread filled his thoughts, but something was tugging at the back of his mind. It felt vaguely like a sense of…hope. Almost as if there was finally a way out of this nightmare. Wait, there was something he dreamed about last night, some sort of…

“Howdy doody Baldric! Working hard or hardly working? Hehehehehe.”

Baldric looked up to see a young male halfling laughing mechanically. It was Kevin, Baldric’s supervisor. As usual he was seated on a platform borne aloft by several interns.

“Any-hoo, just wanted to pop in and see if you’re staying above water. With everything coming down the pipeline I think we need to have a little pow wow later this afternoon to make sure all our ducks are in a row. From our standpoint, we’re really gonna need to coordinate if we don’t want to drop the ball.”

Baldric looked into Kevin’s dull gray eyes. They always looked the same regardless of the emotion he was exhibiting, cold on the outside yet burning with a searing fervor deep within.

“Yes Kevin, I’ll have the inventory calculations done on time, no problems…”

“Great, well, you know I have an open door policy if you ever need to drop by and let me know where your head’s at. With Steve having to take a little trip to HR, we’re all gonna be playing a little catch up.” With a couple quick claps, the interns lifted the platform back up. “Keep me in the loop, and don’t forget, Busyness is Progress!” said Kevin with a big grin as he was carried away.

“Busyness is Progress,” replied Baldric, cringing at the Empire’s slogan. Poor Steve. He had been the last person whose presence didn’t make Baldric physically ill. Few things in this world were worse than a trip to Humanoid Resources. But in spite of it all, he was quite pleased with himself. He was almost finished with the day’s work, and it wasn’t even midmorning yet!

Since waking up, the otherwise ordinary dwarf had found he had a strange ability to weave patterns of threads. Not actual threads, as no one else seemed able to see them, but some sort of green immaterial threads composed of 0’s and 1’s that were seemingly conjured from his mind. To weave the threads he needed only to concentrate on a calculation, and when the pattern was finished it collapsed into that calculation’s result. Amazingly, these patterns could perform once-tedious arithmetical computations in the blink of an eye. Was he finally losing his mind? Maybe this place had gotten to him more than he realized.

Sighing, Baldric turned back to the inventory calculations he had been working on and began again to weave his patterns. “Let’s see, a stock of 81 whips in one HR storeroom, 76 whips in another, for a total of…

>>> 81 + 76
157

…157 available whips,” Baldric muttered to himself, noting the result of his mystical calculation in the ledger. He didn’t even really have to think about the patterns he was weaving, he somehow intuitively knew what to do.

“And here we have corpse shroud counts. 434 in the first crate, 286 in the second, then 342, 260, 419, and finally 239, for a total of…

>>> 434 + 286 + 342 + 260 + 419 + 239
1980

…1,980 shrouds. Seems a bit short.” He checked his calculations by hand and found that yet again his weaving was correct. Somehow he had learned this curious new way of doing arithmetic since falling asleep last night. Perhaps in a dream? Well, he would have to keep quiet about that. Sleeping was permitted, if just barely, but dreaming? Anyone caught dreaming by the Empire soon went the way of Steve.

“What’s next…ah, impaling stakes. In HR’s warehouse, the stakes are stored upright in a grid, with 122 to a row and 87 to a column. With 122 rows by 87 columns, we must have…

# variables can be used to store numbers

>>> rows = 122
>>> columns = 87
>>> rows * columns
10614

…10,614 of them. Impaling stake supplies seem to be sufficient. At least until mid-year reviews.

Let’s see, the next section of calculations is on employees under “extended review”. Humanoid Resources has 3 cell blocks, where Cell Block A has 600 cells, B has 800, and C has 1,000. With all the cell blocks full as of last week, there must have been…

# variables can also be assigned expressions
# these expressions automatically evaluate to a single number

>>> population_last_week = 600 + 800 + 1000
>>> population_last_week
2400

…2,400 employees there. But with 97 firings, 52 other deaths, 0 escapes, and 15 new arrivals, that total will change. We now have…

# variables can help make calculations more readable
# parentheses can help clarify or change the order of operations

>>> firings = 97
>>> other_deaths = 52
>>> escapes = 0
>>> new_arrivals = 15
>>> current_population = population_last_week - (firings + other_deaths + escapes) + new_arrivals
>>> current_population
2266

…2,266 remaining employees under extended review.” Baldric paused a moment to shudder at the thought of being sent to HR. Whereas employees (there were no longer citizens, only full-time employees) in good standing were only mandated to have 5 staff meetings a week, inmates were forced to have 10 every day. Worse, rumor had it HR was remodeling soon and planned to convert the cell blocks to an open floor plan. Surely even HR couldn’t be that cruel.

“And now for some military sums. They want to know how many arrows per archer are stockpiled in the local barracks. Well, with an estimated 7,263,180 arrows divided among 127,060 trained archers, we have…

>>> arrows = 7263180
>>> archers = 127060
>>> arrows_per_archer = arrows / archers
>>> print(arrows_per_archer)
57.16338737604281

# print() is used above to show a variable's value
# in interactive mode you can also enter a variable's name to see its value (as done previously)
# if you are using script mode, however, you must use print() for a value to be displayed
# see here for more details https://datarebellion.com/blog/coding-in-interactive-mode-vs-script-mode/

…a little over 57 arrows per archer.

And here it says the Empire has 38 crates of newly-manufactured swords. If each crate is a cube with 2 meter-long sides, and 160 swords fit in one cubic meter, then in total we have…

>>> number_of_crates = 38
>>> crate_volume = 2**3 # a double asterisk is used for exponents
>>> swords_per_cubic_meter = 160
>>> swords = number_of_crates * crate_volume * swords_per_cubic_meter
>>> print(swords)
48640

…48,640 swords.” Baldric could feel a sort of difference between his last two calculations. It was as if the results of those calculations were of different…types. Well, both were numbers, but one was a whole number with no decimal point and the other had a decimal point with numbers after it. Relying on intuition, Baldric began to weave something he thought might help explain the difference.

# what's different about arrows_per_archer compared to swords?
# they are different "types" of things

>>> type(arrows_per_archer)
<class 'float'>

>>> type(swords)
<class 'int'>

# a float is a number with a decimal point
# int is short for integer, a number which doesn't have a decimal point

# you can convert an integer to a float like so
>>> float(5)
5.0

# and you can also convert a float to an integer
>>> int(5.0)
5

>>> int(5.8462)
5

“Hmm, I knew they felt different. I wonder…”

As Baldric was muttering to himself, Kevin floated back over to Baldric’s cubicle. “Baldric, hey, you keeping busy? Let’s touch base for a second. I know you’ve got a lot on your plate, but I want to try and take care of some of the low hanging fruit before we get too swamped. Here’s a request I want you to go ahead and take the lead on. A Senior Manager needs a book from the library.” Kevin handed Baldric a note. “Let’s circle back once you knock this out. Thanks for jumping on this champ!”

Adjusting his glasses, Baldric read the note. The book was titled, That’s No Wyvern, That’s My Wife! Learning to Live with a Permanently Polymorphed Spouse. “At least I’ll get out of this god-forsaken office for a bit,” Baldric quietly grumbled to himself once Kevin was gone. He shuffled outside, passing several vacant-looking clerks engaged in conversation.

“So I told Bob that what we really need is to all get on the same page and start implementing best practices, because at the end of the day there’s no point in reinventing the wheel.”

“Exactly, we don’t have the bandwidth to be constantly shifting gears, and from our standpoint…”

It was a short walk to the library, the streets empty aside from a couple of half-elves lounging about, a dangerous thing to be doing during work hours. Fewer people seemed to be going outside recently, but this was the emptiest Baldric had seen it at this time of day.

The library Baldric was headed to was quite different from the ones he remembered as a kid. There was only one library now, and of course most of the books were about work, such as Impress Your Boss and Never Leave the Office Again!, The 7 Habits of Highly Obedient People, and 50 Great Gossip Techniques That Will Drive Your Coworkers Crazy! But these were available to everyone, and Baldric knew his target would be in the Privileged section where they kept the books for higher-ups’ eyes only.

Upon arriving and showing his request to the section’s guard, Baldric quickly located the requested book. But it was a larger one next to it that caught his eye. He could tell this other book was old. Not in bad shape, but it had a sense of age about it. Leatherbound, no title. He casually flipped through it. Page after page was covered in a small, neat script occasionally punctuated by inscrutable drawings and schematics. He turned back to the start and began to read. It was talking about magic!

“The Multiverse is composed of five fundamental elements: Wind, Water, Earth, Fire, and Logic. The weaving of these elements comprises the art and science of Magic.” Much of it was even less intelligible, such as, “The Primordial Weaver, the Prime Loop, the Great Serpent, is that which gives rise to reality”, and, “The Multiverse is comprised of Magic, yet its most fundamental building blocks are not elemental threads, but…” Baldric became entranced in the scribblings, and after a few minutes it even started to make sense. Wait, there was a section on arithmetic. “The weaving of sums and products and the like is the most basic use of the Magic of Logic.”

Baldric’s jaw dropped. “Magic? I know how to use Magic!? I guess that explains those threads that do math I’ve been weaving. Braid my beard, this is…” His excitement quickly subsided after remembering what happened to Magic users. If someone used Magic in public, they skipped HR altogether and were sentenced to an immediate Firing. Burning at the stake, as it was once called. So anyone with any sense kept their Magical abilities secret. But inevitably they disappeared anyways. Baldric had known a few. At work one day, their cubicle cleared out the next. Baldric could’ve sworn he’d later seen one of them wearing the garb of Management as they passed in the hall several months back, but she didn’t appear to recognize Baldric.

Suppressing a growing sense of dread, he continued reading and found a section on arithmetic. It was talking about some sort of arithmetic he wasn’t familiar with. “Beyond the usual operators for addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (**), there is also %, which allows one to perform clock arithmetic. Meditate on the fact that no matter how many hours pass on the face of a clock, it always gives an hour between 1 and 12. If one starts at midnight and 13 hours pass, the clock reads 1. If instead 25 hours pass from midnight, the clock still reads 1. Such Magic is often of use to skilled Logic users.” Baldric paused to try out clock arithmetic for himself.

# 13 hours pass on a 12 hour clock
>>> 13 % 12
1

# 25 hours pass on a 12 hour clock
>>> 25 % 12
1

# 1 hour passes on a 12 hour clock
>>> 1 % 12
1

# 8 hours pass on a 6 hour clock
>>> 8 % 6
2

# 1,000,000 hours pass on a 2 hour clock
>>> (10**6) % 2
0 

# 0 indicates the "noon", or starting, position on a clock

“Interesting, I think there’s some work where this will come in handy. And I don’t see how anyone will find out. I’ve apparently been weaving Magic all morning long and no one’s said a word. Hmm, I wonder what else I can do with Logic, not to mention with Wind and Fire and…” Thoroughly absorbed in the book, Baldric read page after page as time faded away.

When he was about a quarter of the way through he thought to himself, “Sigh, I suppose it’s time to get back before Kevin wonders where I am.” Looking out a nearby window, he saw it was dark outside. “Wait, that can’t be right. How long have I been here?!” Trading the Book of Magic for the asinine one he had been sent to get, Baldric ran out of the Library, nearly knocking over a pair of half-elves near the entrance, and sprinted back to the office with the requested book in hand.

He slipped inside and darted toward his desk but turned a corner and found himself face-to-face with Kevin. This time his mouth was curved in a disappointed frown. His eyes were the same as always.

“Baldric, buddy, where’ve you been? I hate to say it, but you really dropped the ball on this one when it should’ve been a no-brainer. I’m almost starting to think you don’t quite fit the culture here. You wouldn’t agree with that assessment, would you?”

The fires deep in Kevin’s pupils seemed eager for Baldric to agree.

“No not at all, it’s completely my fault Kevin, it just took me forever to search through the library, and the book wasn’t where…”

“Great, I didn’t think so. Now listen Baldric, there’s actually another request on your desk that I need you to execute on ASAP. So put your pencil to it, and let’s sync up once you’re done banging it out. Then you can give me the whole play-by-play of this little library incident, sound good?”

Baldric nodded drearily and sat down at his desk. A new request had indeed arrived via letter, sealed with wax imprinted with the likeness of a hand holding a leash and the phrase, “Busyness is Progress”.

“Just my luck, it’s got the Imperial Seal. From someone high up in Management then. Very high up.”

Sighing with dread, he opened the letter and read:

The following calculation is to be performed by under-clerk Baldric Hightower, and him alone. You are required to calculate the product of three numbers. The first number is 4 to the 4th power, from which is subtracted 3 times 19. The second number is 10 to the 3rd power plus 161, all of which is divided by 27. The third number is 2 times 3 times 3 times 23 times 3 times 233 times 43, all of which is subtracted by 5. Multiply these three numbers together, and submit the result directly to your supervisor.

No signature. Baldric scratched his head in thought. “Why would anyone be interested in such an enormously tedious calculation? Or, more importantly, feel compelled to bother me with it?” Cracking his knuckles, he said to himself, “Well whoever they are, I guess they came to the right place. Let’s see what this Magic of mine can really do.”

# notice the lack of ">>>" characters
# this suggests you should try running the code in script mode
# for such code, the result will be displayed here in a separate box

number1 = 4**4 - 3*19 
number2 = (10**3 + 161) / 27
number3 = (2 * 3 * 3 * 23 * 3 * 233 * 43) - 5
final_number = number1 * number2 * number3
print(final_number)
106479825301.0

Once the calculation was completed, Baldric took a moment to stare at the result: 106479825301.0.

“Hmm. There’s something…peculiar about it. I can’t quite put my finger on it though…”

***

“Mistress, here’s the response to your request. Completed in remarkably short order I might add.”

“Hmm…yes, it seems we will be able to move forward with our plans, thank the Serpent. I trust you two managed to acquire the scrolls of Teleportation and Truth-telling as well?”

“Yes Mistress.”

“Good, then prepare the bait.”


Congratulations, you earned 32 experience and 14 gold! You are now a Level 1 Dwarven Novice! (cue victory music)

Here are the Python topics you covered (and may want to DuckDuckGo for further inquiry):

  • integers
  • floats
  • arithmetic
  • modular (clock) arithmetic
  • variables
  • Python data types and the type() function
  • converting between integers and floats with int() and float()
  • coding in interactive mode vs script mode
  • the print() function
  • comments (using the # symbol)


Chapter 2 – Strings and Lists >>>