In python we can add comments to code. These will be ignored by the computer so you can write in normal language instead of writing in python. Use the # symbol at the start of the comment.
On the left is single line comments, if you want to a block or multi-lined comment you use three quotation marks like on the right.
There is no exercise to this, but it is needed to know so that you can properly explain your code to any potential readers of it.
Notice that each line is numbered, all IDEs do this. For these notes I'm using Replit and Visual studio.
Each program reads from top to bottom, like reading a book. This flow gets slightly more complicated later, but it's not that bad once you know how to do it.
Use the print command to output in the console whatever you put in the brackets (). You can output whatever you want, for example:
Whenever you want to print a new line you can do one of two things:
Make a new print statement or:
use the characters "\n" without quotations to indicate to the computer to print a new line.
There's other special characters (called escape characters) in python such as:
You may not use all of these but you may use some. I put the more likely ones towards the top.
If you want to find more unicode characters you can find them here: Link to unicode
What if we need to store some information on the computer? Well this is where variables are used. Variables are like boxes that store data to be used later on in the program. Variables, like in math, can store things like numbers. Unlike math, computer science variables can hold words, numbers, and (true/false) values. A string variable holds onto words, text, letter(s), or number(s).
To give a variable a name in computer science it is best practice to you the camel method where the first word is all lower case, then each following word has a capital like this:
camelCaseMethod
However, snake case is also acceptable, that's where you seperate words using underscores like this:
snake_case_method
Do not use one character names, nor use numbers in your variable names. Spell out the words.
Always declare your variables at the beginning of your code if you can. This helps organize your code so that there isn't stuff everywhere.
To give a variable a value you have to use the = sign after it. To set a string value to the variable it needs to be in between quotation marks “like this”.
Line 1: firstName is a string variable that is set to Keith, it's holding this word
Line 2: lastName is also a string variable but it's set to Smith
Line 4: prints the content of the variable firstName so it outputs Keith
Line 5: prints the content of the variable lastName so it outputs Smith
Line 6: prints the contents of both firstName and lastName together so it outputs KeithSmith
Line 7: does the same as line 6, but because we have a comma the computer treats this as a space so it outputs Keith Smith instead.
Note: There's a difference between using a plus and a space inside the print statement. You can use them interchangeably as needed. Plusses can also be used to combine strings:
Line 12: set fullName to firstName and lastName combined so it's KeithSmith
Line 13: prints fullName (KeithSmith)
Line 14: resets the value to the firstName, a space, and the lastName. (Keith Smith)
Line 15: outputs the fullName (Keith Smith)
We can also just store sentences and paragraphs in string variables to have them displayed later:
Line 19: the variable sentence is holding text with mutliple words
Line 21: the string variable paragraph is holding multiple lines starting and ending with triple quotation marks
Line 25: prints the sentence variable contents
Line 26: print the paragraph variable contents
You can also have escape characters in the strings.
Line 2: quote variable has a quotation mark and new line escape character in itLine 3: author variable has a newline escape character in it.
Line 5-6: outputs the quote and author
There's also different functions (or methods) that you can use to modify string variables
We can also output formatted string with our print statement, separate text and variables using commas:
Line 1: creates a string variable
Line 2: outputs the string variable in full caps.
I can't teach you all possible string methods, but here's a link to a list of more common ones: String methods
Character means a letter, number, space, or symbol. Strings are made of a "string" of characters.
If you want to only show part of a string you use [brackets] after the string variable. The first character is at 0 since computers start counting at 0.
Line 1: set the test to Hello friends!
Line 3: outputs the first character (H) because computers start counting at zero
Line 4: outputs the 9th character. It includes the space when counting characters.
Line 5: outputs the first character to the 6th. (Hello) starts at 0 then outputs 5 characters after it.
Line 7: outputs the 8th character from the end. (f)
Line 8: outputs the last character (!), because it outputs the 13th character... because there's 14 characters (because len(text) = 14) then subtract one because computers start counting at 0. So the actual last character is the 13th because the first is the 0th.
Line 9: outputs from the 8th character from the end all the way to the end.
Use a consistent naming convention, don't mix snake case and camel case together.
Use meaningful variable names. Shortened words can be acceptable but be mindful of potentially confusing scenarios like temp could mean temperature or temporary.
There are two types of number variables in python that we can use.
Integers: Whole numbers
Floats: numbers with decimals
When naming your variables use appropriate names. Luckily we don't have to tell python to use integer or float it will interpret this because python is an interpreted language.
Line 8 there's a spelling mistake :(
Line 1: age is an integer variable set to 15, because age is often given in a whole number
Line 2: height is an integer variable set to 180. This could also be a float later on.
Line 4: temperature is a float variable set to 98.6, since temperature can often be given with decimals
Line 6: outputs age
Line 7: prints the height but formats it so it says the word height before it and cm after. We can change the variable on line 2 and it will keep the proper format!
Line 8: same idea as line 7 but instead we can change the value on line 4 to keep proper format
This is pretty useful code, but we can do much more. Since these are numbers and computers are just sophisticated calculators we can actually do calculations with them! Here's the operators we can use:
Here's how to use some of them:
Note: Now it's time to start sectioning your code if you haven't yet. This is a small program but most programs will have at least 3-4 sections. The sections here are commented to tell the reader that there's variables at the top, then process, then output.
Line 2: first number variable is set to 5
Line 3: second number variable is set to 3
Line 6: adds the variables together and stores the answer in the sum variable (8)
Line 7: subtracts the two variables and stores the answer in the sub variable (2)
Line 9: multiplies the variables and stores the answer in the product variable (15)
Line 10: divides 10 by the first variable and stores the answer in div (2)
Line 11: divides 10 by the second variable and stores the answer in divTwo (3.33... because 10/3 is 3.3333...)
Lines 14 - 19: Outputs our calculations in order to see them.
Notes:
You can divide two variables by each other, I just did it this way to show you can get decimals and non-decimal answers from integers.
divTwo has a slight rounding error, but this is still a good approximation. This error happens due to memory space and computers can't hold infinite decimals.
Okay those are the vanilla of operators, here's the more unusual ones:
Line 2: declared multiple variables in one line, you can do this with multiple types too. numOne is 5, and numTwo is 3.
Line 5: calculates 5 to the power of 3 and stores answer in exp
Line 8: floor division of 7 by 3 so 2 since floor division always rounds down to nearest whole number
Line 9: modulus is used to calculate the remainder. 7 mod 3 is 1 since that would be the remainder in this division.
Lines 12-14: Outputs our results.
You can even use these math operators in print statements, but be careful that you use commas so the computer doesn't get confused and throw an error.
Rules of BEDMAS also apply so be careful when calculating multi-step formulas.
While it is more efficient to code multiple variables on one line it is difficult to read once it goes beyond 3, so keep that in mind. It's also a good idea to not mix data types in single line declarations since that is not a common practice.
You may use shortened words for variables as long as it doesn't get too confusing.
Comment your sections of code if you have them, variables, input, process, and output need their own sections.
Assignment Operators
If you wanted to add one to a counter you could do this:
counter = counter + 1, but it's much better to do this:
counter += 1
This works for all operators, examine the following example and read the comments to further your understanding.
Being able to make programs that do processing and output is all fine and dandy but if you can’t take in user input it’s not very useful. Imagine trying to use your favorite social media platform without being able to post anything or playing your favorite video game without being able to use any controls (this would basically be a video).
Here’s how to take in information (input) from the user:
This will let the user to type in a word or a number
But when you enter a number you can't do any math with it (yet).
This also doesn't work to store any data yet since we need to use both input and a variable. Input always comes in as a string:
Line 2: takes an input and stores it in the name variable. It will be stored as a string by default.
Line 4: outputs the name entered into a sentence.
Now we can also give the user instructions, you can use the brackets in the input to do this:
Before we can input numbers we need to know how to change data types from string into int or float variables, this is called typecasting. We need to know this because inputs by default are always string, this is a somewhat common thing that happens in many other programming languages.
Here's how to typecast from string to int or float, it's pretty easy:
Okay but the issue is we're not storing these in variables so this code essentially did nothing so let's fix this:
Line 2: makes "15" into an integer and stores it in the radius variable
Line 3: makes "3.14" into a float and stores it in the pi variable
Line 6: outputs the circumference calculated.
Okay but how is this useful? Well what if we took an intput for radius instead?! That would make our program a circumference calculator.
Line 2 was modified so now it takes whatever is typed in and turns it into an integer, recall that any input is by default a string. The number is stored in memory to be used in line 6 to perform a calculation. It then calculates the circumference.
If the user doesn't type in an integer the program crashes. Let's fix this so they can enter a decimal. Try it yourself then come back to see if you got it right.
Line 2 I changed int to float so we can now enter decimals. If the user enters words it will still crash the program. We don't learn how to dealt with this problem until grade 11. Unfortunately there's no instructions for the user, let's add some so the user knows what to do:
Line 2 I added instructions in the input brackets. Be careful of the brackets, I opened two so I had to close two.
Typecast integers like age, number of people, etc. to integers not floats. Floats take up more memory and should only be used for numbers with decimals.
If you can use the input statement to give instructions do so. No need for an extra print statement.
You should collect your inputs in one section (if possible) and label the section with a comment.
Formatting print statements with pluses and commas and \ characters is such a pain. This is why using f strings is so useful. All you have to do is put f before the quotation marks, then put the variables in {braces} to get started.
Line 1-3: set the variable values (alternatively you cold scan them)
Line 5: I print the string with the variables inside of them exactly where I want them! But how is this useful? Well we can give them space so that the print statement is more formatted:
Line 5: I changed quantity, so now it will take up 3 spaces with zeroes in front of the quantity. If the quantity was 4 digits it would
Alternatively we can pad numbers with spaces by deleting the zero in front.
Line 5: Now you'll notice in the output that the 1 is spaced over. This is because the string allocates (reserves) 3 character spaces for the quantity if it needs it, if it doesn't then it fills it with spaces!
Okay but what about decimals?
Line 1: defined pi so you can see some of the digits
Line 2: prints out up to 4 digits AFTER the decimal. This makes outputting formatted numbers much nicer. This prints the number all the way left, so we can combine this with padding:
Line 2: added a '>' char and 10 before the decimal (this will allocate 10 character spaces for the number including the decimal and all digits)
Line 3: added the '^'s to show you where the spaces are in the output
Look at the output, after the '>' symbol there are 4 spaces then pi shows up. That's because there's 6 characters in pi including the decimal. So we're left over with 4 spaces. This can help with padding numbers and aligning them left. This is common with prices to align the decimals in prices.
How do we do this with string though?
Using the older example again,
Line 5: used item:>15 which gives a string 15 characters of space and fills in front of it with spaces if it doesn't use all the characters
Line 6: used to show spacing
Alternatively we can switch around the symbol to move it left and fill the end with spaces
Line 5: switched around the sigh from > to <
Line 6: using this to show spaces in the output
Notice that now there's 4 spaces AFTER the item name, this is because it aligns it left now.
If you want to get even more fancy you can also do calculations inside the {braces} but I'll leave that up to you.