Conditions
Reading
This is some advice geared towards beginners like you when starting to code. The tone is a bit condesending but the advice it gives out is pretty solid.
I want you to read all of it. As many times as you can. Understand what it says, and why it says so. Feel free to ask me questions on if you disagree with any part of it or don’t think of it as good advice. I will quote a few sections that I like from there, but I want you to have read the whole thing. (I have no way of checking so I’ll just believe that you have on good faith).
Bookmark this page.
Quotes
(Considering that I quote more than half the page you know it’s worth reading)
With the help of this book, you will do the incredibly simple things that all programmers do to learn a programming language:
- Go through each exercise.
- Type in each file exactly.
- Make it run. That’s it. This will be very difficult at first, but stick with it.
three most essential skills that a beginning programmer needs to know: reading and writing, attention to detail, and spotting differences.
The one skill that separates bad programmers from good programmers is attention to detail. In fact, it’s what separates the good from the bad in any profession. You must pay attention to the tiniest details of your work or you will miss important elements of what you create. In programming, this is how you end up with bugs and difficult-to-use systems.
By going through this book, and copying each example exactly, you will be training your brain to focus on the details of what you are doing, as you are doing it.
A very important skill (that most programmers develop over time) is the ability to visually notice differences between things. An experienced programmer can take two pieces of code that are slightly different and immediately start pointing out the differences.
You first have to train your brain the hard way, then use the tools.
While you do these exercises, typing each one in, you will be making mistakes. It’s inevitable; even seasoned programmers would make a few. Your job is to compare what you have written to what’s required and fix all the differences. By doing so, you will train yourself to notice mistakes, bugs, and other problems.
your bugs will be hidden somewhere in the code, and you have to go find them. You can’t just sit at your computer screen staring at the words you’ve written hoping that the answer jumps out at you. There is no more additional information you can get doing that, and you need additional information.
To do that you have to interrogate your code and ask it what is going on or look at the problem from a different view. In this book I’ll frequently tell you to “stop staring and ask”. I’ll show you how to make your code tell you everything it can about what’s going on and how to turn this into possible solutions. I’ll also give you ways to see your code in different ways, so you can get more information and insight.
You must type each of these exercises in, manually. If you copy and paste, you might as well not even do them. The point of these exercises is to train your hands, your brain, and your mind in how to read, write, and see code. If you copy-paste, you are cheating yourself out of the effectiveness of the lessons.
To me repetitive practice is natural and just how to learn something. I know that to get good at anything you have to practice every day, even if I suck that day (which is often) or it’s difficult. Keep trying, and eventually it’ll be easier and fun.
If you break the problem down into small exercises and lessons, and do them every day, you can learn to do almost anything. If you focus on slowly improving and enjoying the learning process, then you will benefit no matter how good you are at it.
As you study this book, and continue with programming, remember that anything worth doing is difficult at first. Maybe you are the kind of person who is afraid of failure, so you give up at the first sign of difficulty. Maybe you never learned self-discipline, so you can’t do anything that’s “boring.” Maybe you were told that you are “gifted,” so you never attempt anything that might make you seem stupid or not a prodigy. Maybe you are competitive and unfairly compare yourself to someone like me who’s been programming for more than 20 years.
Whatever your reason for wanting to quit, keep at it. Force yourself. If you run into a Study Drill you can’t do, or a lesson you just do not understand, then skip it and come back to it later. Just keep going because with programming there’s this very odd thing that happens. At first, you will not understand anything. It’ll be weird, just like with learning any human language. You will struggle with words and not know what symbols are what, and it’ll all be very confusing. Then one day BANG—your brain will snap and you will suddenly “get it.”
As you study this book, and continue with programming, remember that anything worth doing is difficult at first. Maybe you are the kind of person who is afraid of failure, so you give up at the first sign of difficulty. Maybe you never learned self-discipline, so you can’t do anything that’s “boring.” Maybe you were told that you are “gifted,” so you never attempt anything that might make you seem stupid or not a prodigy. Maybe you are competitive and unfairly compare yourself to someone like me who’s been programming for more than 20 years.
Whatever your reason for wanting to quit, keep at it. Force yourself. If you run into a Study Drill you can’t do, or a lesson you just do not understand, then skip it and come back to it later. Just keep going because with programming there’s this very odd thing that happens. At first, you will not understand anything. It’ll be weird, just like with learning any human language. You will struggle with words and not know what symbols are what, and it’ll all be very confusing. Then one day BANG—your brain will snap and you will suddenly “get it.” If you give up, you won’t ever reach this point. You will hit the first confusing thing (which is everything at first) and then stop. If you keep trying, keep typing it in, keep trying to understand it and reading about it, you will eventually get it. If you go through this whole book, and you still do not understand how to code, at least you gave it a shot. You can say you tried your best and a little more, and it didn’t work out, but at least you tried. You can be proud of that.
Conditions
One of the core pillars of programming are how programs adapt and change. What set computers apart from the machines from earlier, is that computers could know how to adapt to changing criteria and work. They were adaptable.
A program that can just do one thing all the time isn’t really useful. So we need a way to tell programs how to do things differently based on conditions.
A code example speaks a thousand words
favorite_number = int(input("What is your favorite number? "))
if (favorite_number == 42):
print("Hey that's a great number!")
else:
print("My number " + str(42) + " is better")
Note: I’ll keep trying to bring back older concepts from earlier. The trick to learning is seeing something lots and lots of times.
Okay. Look at the above. Type it out line by line and running it and trying to understand what it does. Generally, whenever I show an example to you, try to get it as well as you can. Poke around it and then we move onto how it works. If it helps take notes, modify it, rewrite it a few times etc. (This is a general rule that applies to any code example you ever see here or anywhere - the whole point is to build up your understanding
Take a moment. Now look below.
Input
favorite_number = int(input("What is your favorite number? "))
Building up from the last lesson. We just ask the user for their favorite number and convert it to an integer.
The condition
favorite_number == 42
First thing you notice is the ==. This is the way we check for equality.
Here the code is checking if favorite_number is equal to 42
Branching
The core idea is that based on the results of the condition, the program decides what gets executed. So if it’s true or false affects what happens. This is an important idea, and pretty much every type of conditional execution a computer does is built upon this basic idea.
if (favorite_number == 42):
print("Hey that's a great number!")
else:
print("My number " + str(42) + " is better")
So when the condition is True (the entered number is 42) it prints out
Hey that's a great number!. Otherwise if it is False it prints
My number 42 is better (note that str() converts things to strings).
Blocks
Notice also how the bit attached to the if and else are indented. These are called blocks, and while I will explain this better later for now just understand blocks as ways of attaching code onto labels and control structures.
Basic rules for now:
- starts with a
:which signifies what it’s attached to - every line of the block has to have
4 spacesof indent. Usually pressing thetabkey will create that in most places. - the block ends with the start of something else (the block attached to if ends
with
else, otherwise it ends with an empty line (notice how I carefully have added an extra line
Outputs
I’m showing output only but I want you to run the above code to get both outputs.
For True
What is your favourite number? 42
Hey that's a great number!
What is your favourite number? 25
My number 42 is better
General structure
So the general syntax for if conditions are like.
if(condition):
<code run when the condition is True>
else:
<code run when the condition is False>
Note the empty line at the end.
Exercise
Modify the above example to work with your favourite number. And in you happen to also like Adam’s novels and hence also like 42 just rewrite it for maybe your second favourite number.
Other conditional statements.
In the above example we checked for equality of numbers. But python has many,
many types of conditional statements that we can put inside an if. The rule
of thumb is if it returns True or False you can put it in an if block.
Here are some you might see often (these are some but not all):
5 != 3- not equals check - here givesFalse5 > 3- greater than - here givesTrue5 >= 5- greater than or equal to - here givesTrue5 <= 4- lesser than or equal to - here givesFalse4 < 5- lesser than - here givesTrue
Exercise
Mofify the example from the last exercise. Now instead of checking for equality, check if the given number is greater than or equal to your favorite number. So it should be like:
What is your favorite number? 25
Yup that's equal or greater than my favorite number 21.
and
What is your favorite number? 20
Oh no that's lesser than my favourite number 21.
Complex branching
We basically achieve more complex structures with just combining ifs together. This works because of blocks, blocks can be pretty much any code, including more if statements.
Nesting
number = 5
if (number > 0):
print("It is positive")
if (number < 10):
print("It has only one digit")
else:
print("It is not positve")
Similar to the last example, here the first level condition checks if the number
is positive or not. Then in the true branch of that we check if it’s lesser than
10, so if it is then we are sure it only has one digit. Likewise, any complex
logic you have can be represented this way.
Notice:
- The empty line ending the second level if condition. So either a new block or empty line marks the end of the current block.
- The level of indentation. For every block we’re creating, we add another set of nesting. This lets us programmers clearly see what block links with that control flow. In other languages the indentation is optional, but in Python it’s has to be there.
- Ifs don’t need elses. So when they do, you can add them, otherwise it’s not needed.
Chains
Lots of times we have cases where we have an if-else-if-else-if-else structure.
Look at below.
score = 95
if (score > 90):
print("A")
else:
if(score > 80):
print("B")
else:
if (score > 70):
print("C")
else:
print("D")
This is something really common in lots of programs, but this indentation and understanability gets annoying fast. So we came up with a better syntax for this.
score = 73
if (score > 90):
print("A")
elif (score > 80):
print("B")
elif (score > 70):
print("C")
else:
print("D")
So using elif saves us from a lot of nasty indentation hell and makes code
look nicer. Sweet!
This is very common in code and both yours and others code will have such structures quite often.
Combining conditional statements
We can also take simple conditions and compound them into bigger statements.
and
Use this to check if both conditions are true. Only then does this overall return true.
physics_score = 78
math_grade = 48
if (physics_score > 50 and math_grade > 50):
print("You passed")
Here if the physics and maths scores are both above 50 the student passes.
or
This is basically to make sure that atleast one of the conditions is true.
i_am_hungry = False
i_am_bored = True
if (i_am_hungry or i_am_bored):
print("I want to eat!")
Here the user can be either hungry or bored and they will want to eat. Note
that even if the user is both hungry or bored it will still print I want to eat!.
This only gives false if both of them are false.
not
All this does is flip the condition’s results.
FalsebecomesTrueTruebecomesFalse
if (not 5 < 4):
print("Reversed, 5 < 4 is false")
Exercise
Here is a slightly meatier one. I want you take someone’s day, month, and year in which they were born and print out if you are older than them or not.
So the output of the program will look like
Enter your birth details
Year? 2000
Month? 10
Day? 4
Hah I am older than you!
2000 is the user input for birth year, 10 is the user input for both,
and 4 for day.
This one is more ambitious than your standard replace something in existing programs that you have done till now. A few points to think on
- How to get user input as an int?
- How can I tell if someone is younger or older than me?
Data type: Booleans
So far we’ve dealt with the data types of Int and String for numbers and
general text respectively. Now we come face to face with our next one, booleans.
Unlike Strings and Integers that can take a lot of values, these can only take
two vales True and False. These are made to work with any sort of conditional
structure.
Also note the exact casing, it’s True not true or TRUE like in other languages.
This one trips a lot of people (and me) up so be careful on this one.
You can set these into variables too
i_like_java = False
projects_are_fun = True
The road ahead
Good job on getting this far! So I want you to understand what I am planning ahead.
So my end goal is to basically teach you to think. Really it doesn’t matter too much of what I teach you so long as I hit the basics and you have the ability to think through problems. Really that’s all CS125 or any other future CS (or other field) endavor really needs.
Drills
Whatever lessons I write out here. They are mostly there to quickly bring you up to speed with the core concepts. However, that’s only showing what the rules are. You only get good by writing code. Lots of it. Repitiion. Application in different areas. Thinking. I have some exercises up but they’re mostly for reading comprehension types.
It’s like learning to swing a bat, you can learn about techniques sure, but you can’t get around just taking swing after swing.
So you saw the preface of the book Learn Python The Hard Way. I quite like this book, so what I will do is basically assign bits and pieces here or there that I want you to do. The whole point is to really make the concepts you learn here sink in.
Projects
So the first one you’re building towards is a discord chatbot. This one is really fun and you can write very interesting things with this. So after this lesson. I’ll have you write some starter code for the bot. After each lesson we will pile on a little more on top of it. The important takeaway I want for you to understand is how all these things you learn start going into something real life.
Other base concepts
I am going to write similar lessons for
- Loops (for, while, ranges)
- Arrays (including each loops)
- Functions
After that I’ll consider that enough base concepts for now. Then I’ll pick drills and decide your path through projects. Again, depending on the pacing you show I’ll decide your path.
You’ve mentioned issues with things not sinking in, and that’s the whole point of drills and repeating. Now if things aren’t sinking in after say your 5th or 6th genuine attempt then we have another problem.
(It’s 2am when I write this so tell me typos that have crept in and I’ll fix those)