Week2VariablesMathComments.pdf


Preview of PDF document week2variablesmathcomments.pdf

Page 1 2 3 4 5 6 7 8

Text preview


RHHS Compsci 2016

>​ and
ex. if (noOfStudents >= 20 ​and ​noOfStudents <=30): When separating ifs using ‘and’, the
entire condition satisfies if and only if both statements are true. In this example, in order to
execute the if-statement the noOfStudents must be between 20 and 30 inclusive.
>​ or
ex. if (nameOfPet == “Steve” ​or ​nameOfPet == “Bill”): ​When separating ifs using ‘or’, the entire
condition satisfies if either statement is true. In this example, if the name of the pet is ​either
“Steve” or “Bill” then the if-statement will execute.
>​not
ex. if (​not height < 95): ​Using ‘not’ or “!” simply flips your condition backwards and returns
false if the condition is satisfied and true if it is. In this case, it would return true only if height
>= 95.

INPUT
To obtain input from the user, you can use the ​input() function. But in order to do that, you
need to assign a variable to it (see the review section). For example, if you wanted to get the
user’s name, then you would assign the input to a name variable, like this: ​userName =
input()

However, if you would like to assign the input to a variable other than a string, you will have
to convert it to the target variable type. For example, if I wanted to get their height, I would
have to make the input into a float: h​ eight = float(input()) . The f​ loat(x) part means that
whatever is inside the parentheses will be converted into a float number.

COMMENTING
You may be wondering about the weird red stuff you sometimes see at the top of examples.
Comments are portions of code that don’t run or affect code execution at all. They act to
describe portions of code for the programmer to read so he/she understands exactly what is
going on in the program at all times. They can also be used to remind the programmer what
still needs to be done.
You may be able to remember what a simple piece of code does or easily decipher what it
means, but in longer and more complex programs it is impossible to recall what everything
does or repair broken pieces of code without the necessary descriptions.
Think of your code as a collection of several cans of food:
You may be able to memorize the contents of each can based on its
size and shape, but it might not be so easy to remember when you
come back a few weeks later or if you had hundreds of cans. It
would also be really hard to explain to other people.
The easiest way to solve this problem is to add nice labels:
← Unlabeled vs. Labeled cans (Which is nicer?)