author: Scott Morgan summary: Welcome to learning programming! Take the plunge and getting familiar with all the required tools. id: part-1 categories: python-programming environments: Web status: Published feedback link: https://github.com/Scott3142/python-programming analytics account: UA-49751789-4
Duration: 01:00:00
As you’ve seen in the Getting Started section of this course, the print command print("Hello world")
prints the text “Hello world”.
print("Hello world!")
In this material, text boxes like the one above demonstrate an output produced by the example code. Accordingly, the above program would produce the print output “Hello World!”. You can try any of these examples in the exercise template named “sandbox”, which you will find in the Github repository you cloned in the first part.
You can print any text you want with print
, as long as you use the command print("arbitrary text")
. The command below will print the text “Hello there!”.
print("Hello there!")
In Python, our programs will include some boilerplate code to function. This boilerplate, an example of which is shown below, for example tells the computer what your function is called. Below, the name of the function is main
.
def main():
print("Text to be printed")
if __name__ == '__main__':
main()
Execution of the program starts from the line that says main()
. This command invokes the function main
and runs it. Commands are executed inside main
one line at a time from the top. In the above example, print("Text to be printed")
is the only command to be executed. Its output is:
The examples in the material will not always show the template, but you can assume that your program file has one. As such, the examples might be as short as a single line, such as the example below that illustrates the print command.
print("Hello world")
In reality, the above example, when written as a full Python program, looks like so:
def hello_world():
print("Hello world")
if __name__ == '__main__':
hello_world()
Here’s the second programming exercise of this course. If you’d like, you can watch the video below which covers how to solve the exercise first:
See here for an overview of how to set up a local development environment, including how to test the code before submitting it to Github. The video below talks you through this process.
replace-with-video
Programs are constructed command-by-command, where each command is placed on a new line. In the example below, the command print()
appears twice, which means that two print commands are being executed in the program.
def new_main():
print("Hello world!")
print("... and the universe!")
if __name__ == '__main__':
new_main()
The program above will print:
The programming exercises will be checked by Python’s tester when uploaded to Github. The tester is very meticulous and the guidelines in the assignments regarding the print format are very precise. If the assignment expects you to print a parenthesis, you must print the parenthesis.
This preciseness with regard to the output is relevant in programming in a more general sense. Missing a single character may cause an error. Novice programmers often enter a comma instead of a dot, or write, for instance prnt
instead of print
, leave out apostrophes, or forget a bracket after a command. Any one of these would cause an error and cause the program execution to fail.
Learning programming is, in fact, a path full of mistakes – and every error message is a chance to learn. Keep a look out for any error messages in Atom and try to read the test errors!
The information to be printed by the print command, i.e. its parameters, are passed to it by placing them inside the parentheses ()
that follow the command. For example, passing Hi
as a parameter to the print
command is done like this: print("Hi")
.
Commands can be separated with a semicolon ;
but this is not necessary or recommended in Python. We could, if we wanted to, write almost everything on a single line. However, that would be difficult to understand.
print("Hello "); print("world"); print("!\n");
Although the previous example works, it’s important to be considerate of other programmers (and your future self!) and to use line breaks. That way, anyone reading the program knows that each line does only a single concrete thing. Other languages (like Java) might require semicolons at the end of lines. We don’t need to do this in Python.
Source code can be commented to clarify it or to add notes. Single-line comments are marked with a hash #
. Everything following them on the same line is interpreted as a comment. Python does not really [see below] have a syntax for multi line comments, so to add a multiline comment you could insert a #
for each line.
Below is an example of a program where both are used.
def comments():
#Printing
print("Text to print")
print("More text to print!")
# Next:
# more on printing
# more practice
# variables
# ...
#
print("Some other text to print")
# print("Trying stuff out")
if __name__ == '__main__':
comments()
The last line of the example shows a particularly handy use-case for comments. Code that has been written does not need to be deleted to try out something else.
__doc__
special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. We will revisit these concepts later.Duration: 01:00:00
Input refers to text written by the user read by the program. Input is always read as a string. For reading input, we use the input
tool that comes with Python. The tool can be used with the command input_string = input('This text is printed to screen.')
Below is an example of a program which asks for user input, reads the string entered by the user, and then prints it.
def user_input():
input_string = input('Write a message:')
print(input_string)
if __name__ == '__main__':
user_input()
More precisely, input is read and holds until the user writes something. When the user writes something and presses enter, the provided string is assigned to the string variable input_string
. The program is then able to reference the variable message later on — in the example above, the variable message is referenced in the print command.
When the program is run, its output can look like the example below. In this example, the user has written the text “Hello world” — user input is marked in the sample examples.
As you might have noticed, in programming we refer to “strings” rather than “text”. The term “string” is shorthand for “string of characters” which describes how the computer sees text on a more fundamental level: as a sequence of individual characters.
We’ve so far used strings in two ways. When practicing the print command, we passed the string to be printed to the print command in quotation marks, and when practicing reading input, we saved the string we read to a variable.
In practice, variables are named containers that contain information of some specified type and have a name. Typically, and almost always in Python, a variable is also assigned a value during its declaration. You can assign a value by following the declaration with an equals sign followed by the value.
A string variable called message
that is assigned the value “Hello world!” is declared like this:
message = "Hello world!"
When a variable is created, a specific container is made available within the program, the contents of which can later be referenced. Variables are referenced by their name. For instance, creating and printing a string variable is done as shown below:
message = "Hello world!"
print(message)
A string enclosed in a programming language’s quotation marks is called a “string literal”, i.e., a string with a specified value. A common programming mistake is trying to put quotation marks around variable names. If there were quotation marks around the string variable message
, the program would print the text “message” instead of the “Hello world!” text held by the message
variable.
message = "Hello world!"
print("message")
The string to be printed can be formed from multiple strings using the +
operator. For example, the program below prints “Hello world!” on one line.
def main():
print("Hello " + "world!")
if __name__ == '__main__':
main()
The same method can be used to join a string literal and the value of a string variable.
def main():
message = "Hello world!"
print(message + "... and the universe!")
if __name__ == '__main__':
main()
We can do the same with any number of strings.
def main():
start = "My name is "
end = ", James Bond"
print(start + "Bond" + end)
if __name__ == '__main__':
main()
The input
command reads the user’s input and returns a string. If we then want to use the string in the program, it must be saved to a string variable. A value saved to a variable can be used repeatedly. In the example below, the user input is printed twice.
def main():
message = input('Write a message:')
print(message)
print(message)
if __name__ == '__main__':
main()
We noticed in the “Hi Ava Lovelace!” exercise that string literals and string variables can be joined using the +
-operator. The example below demonstrates a program that takes user input and prints it concatenated with a string literal.
def main():
message = input('Write a message:')
print('You wrote: ' + message)
if __name__ == '__main__':
main()
When the program’s execution comes to a statement that attempts to read input from the user (the command input()
), the execution stops and waits. The execution continues only after the user has written some input and pressed enter.
In the example below, the program prompts the user for three strings. First, the program prints Write the first string:
, and then waits for user input. When the user writes some text, the program prints Write the second string:
, and then waits for user input again. This continues for a third time, after which the program prints all three strings.
def main():
first = input('Write the first string:')
second = input('Write the second string:')
third = input('Write the third string:')
print('You wrote: ')
print(first)
print(second)
print(third)
if __name__ == '__main__':
main()
In the previous example, we saved the user input to three different string variables. This can be done as long as the variables all have different names (in the example, the names are first
, second
and third
).
def main():
first = input('Write the first string:')
second = input('Write the second string:')
third = input('Write the third string:')
print('You wrote: ')
print(first)
print(second)
print(third)
if __name__ == '__main__':
main()
We can form more complicated texts whose content changes depending on the user’s input by using more strings. In the example below, the user is told a bit more about the texts they wrote – notice that the order in which the strings are printed can be changed. In the example below, the third input string is printed first.
def main():
first = input('Write the first string:')
second = input('Write the second string:')
third = input('Write the third string:')
print("Last string you wrote was " + third + ", which ")
print("was preceded by " + second+ ".")
print("The first string was" + first + ".")
print("All together: " + first + second + third)
if __name__ == '__main__':
main()
Duration: 01:00:00
We’ve already familiarized ourselves with strings to a degree while dealing with user inputs. Let’s turn our attention to learning about other variable types commonly used in Python.
A variable can be thought of as a container in which information of a given type can be stored. Examples of these different types include text (string
), whole numbers (int
), floating-point numbers (float
), and whether something is true or false (boolean
). A value is assigned to a variable using the equals sign (=
).
months = 12
In the statement above, the value of 12 is assigned to a variable called months. The statement could be read as: “the variable months is assigned the value 12”. Note that type declaration is implicit in Python, and you don’t necessarily have to declare the type in the assignment.
A variable’s value can be joined to a string using the + sign, as seen in the following example.
text = "contains text"
whole_number = 123
floating_point = 3.141592653
true_or_false = True
print("Text variable: " + text)
print("Integer variable: " + str(whole_number))
print("Floating-point variable: " + str(floating_point))
print("Boolean: " + str(true_or_false))
Note that any variable types that aren’t originally declared as strings, must be converted into a string with the str()
command either before or during printing.
A variable exists from the moment of its declaration, and its initial value is preserved until another value is assigned to it. You can change a variable’s value using a statement that comprises the variable name, an equals sign, and the new value to be assigned.
number = 123
print("The value of the variable is " + str(number))
number = 42
print("The value of the variable is " + str(number))
Let’s look at the preceding program’s execution step-by-step. When a variable appears in the program for the first time, the computer creates a ‘named container’ for the variable. Then, the value on the right side of the equals sign is copied into this named container.
Whenever a variable is referenced by its name in a program – here, we want to print the string “The value of the variable is “ followed by the value of the number
variable – its value is retrieved from a container that has the corresponding name.
The variable is then referenced again by its name in the program – we again want to print the string “The value of the variable is “ followed by the value of the number
variable. We proceed as normal, retrieving the value of number
from a container having its name.
At the end of the program, you’ll notice that the original value of the variable has vanished. A variable can hold only one value at a time.
Unlike some other programming languages, you can also redefine a variable to have a different implicit type:
number = 123
print("The value of the variable is " + str(number))
number = 42.6
print("The value of the variable is " + str(number))
In the first example, the variable number
had the type int
in line 1 and was reassigned to another int
type in line 4. In the second example, the variable number
had the type int
in line 1 and was reassigned to float
type in line 4. This is prefectly fine in Python but may be strange if coming from other languages like Java.
If you are used to certain other programming languages such as Java, you may have seen explicit declaration of type, such as:
boolean myBool = false;
int value = 10;
This is not necessary in Python and Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable.
Python is smart enough to understand the operations you are trying to achieve and will operate accordingly. For example, the program below:
number1 = 1
number2 = 2
print(number1/number2)
will output:
whereas the similar Java code
int number1 = 1;
int number2 = 2;
System.out.println(number1/number2);
would output:
since both types are integers. We will not go too much further into the mechanisms of type declaration in Python here, but you can read more about it here.
Naming variables is a fundamental aspect of describing a program. Let’s look at two examples.
a = 3.14
b = 22.0
c = a * b * b
print(c)
pi = 3.14
radius = 22
surface_area = pi * radius * radius
print(surface_area)
Both of the preceding examples function the same way and output the same result. One of them is, however, much more understandable. The objective here is to compute the surface area of a circle. The value of pi is defined in the first row, the circle’s radius in the second, and the surface area calculated in the third.
Variable naming is limited by certain constraints.
Variable names cannot contain certain special symbols, such as exclamation marks (!). Spaces are also not allowed, since they’re used to separate parts of commands. Instead of spaces, the convention in many programming languages is to either use a style known as snake_case or camelCase to delimit words. Python variable names are always written in snake_case.
camelCaseVariable = 7 # will work, but not convention in Python
snake_case_variable = 7 # this is the format recommended by Python
Python has community guidelines on how code should be formatted. You can view the guide here. We will follow these guidelines as much as practicable in this course.
Numbers can be used within a variable name as long as the name does not begin with a number. Also, a name cannot consists of numbers only.
7variable = 4 # Not allowed!
variable7 = 4 # Allowed, but is not a descriptive variable name
In the text-based user interfaces that we’ve used in our programs, the user’s input is always read as a string, since the user writes their input as text. Reading strings from the user has become familiar by this point - we do it using the input
command.
text = input("Write text and press enter ")
print("You wrote " + text)
Other input types, such as integers, floats, and booleans must be converted to the target variable’s type with the help of the int
, float
or bool
methods provided by Python.
A variable’s type can be specificed after reading user input data. For example, a variable containing the string “text” is declared when read with the input
call, and an integer having the value 42 can be declared using int(varable_name)
.
A variable’s type determines the types of values that can be assigned to it. String types hold text, int types whole numbers, float floating-point numbers, and boolean types are either true or false.
As such, the possible values of a given variable type are limited. For example, a string cannot contain an integer, nor can a float contain a boolean value.
Type | Example | Accepted values |
---|---|---|
Whole number, i.e., int |
value = 4 |
An integer can contain any whole number. Some programming languages have bounds for integer values to do with 32 or 64-bit representations but since Python 3, the values of int have been allowed to be unbounded. |
Floating-point number, i.e., float |
value = 4.2 |
Floating-point numbers contain decimal numbers, with the greatest possible value being 1.7976931348623157e+308 (a huge value). When a decimal number is represented with a floating-point number, the value can be inaccurate as floating-points are incapable of representing all decimal numbers. You can see this inaccuracy if you run (for example) the command 1.2 - 1.0 in a Python file. Unless you are doing some serious scientific computing, you shouldn’t need to worry much about these errors in practice. |
String |
value = "Hi!" |
A string can contain text. Strings are enclosed in quotation marks. |
True or false value, i.e., bool |
right = True |
A boolean contains either the value True or False . (Note the capitalisation.) |
The int
command converts a string to an integer. It takes the string containing the value to be converted as a parameter.
value_as_string = "42"
value = int(value_as_string)
print(value)
When using a the input
call, the reading of the value is usually inserted directly into the type conversion. This happens like so:
def main():
value = int(input("Write a value "))
print("You wrote " + str(value))
Note that we had to convert our variable back to a string in the print
statement in order to be able to concatenate it with the string “You wrote “. An error would have been thrown if we had ommited the str()
.
The float
and bool
commands convert strings to floats and booleans. Similarly to int
, they take the string containing the value to be converted as a parameter.
value_as_string = "42.6"
value = float(value_as_string)
print(value)
value_as_string = "True"
value = bool(value_as_string)
print(value)
If you try to convert a value such as value_as_string = "42.6"
to an int
, an error will be thrown:
Traceback (most recent call last):
File "sandbox.py"", line 1, in <module>
ValueError: invalid literal for int() with base 10: '42.6'
Duration: 01:00:00
The basic mathematical operations are both familiar and straightforward: addition +
, subtraction -
, multiplication *
, and division /
. The precedence is also familiar: operations are performed from left to right with the parentheses taken into account. Expressions involving *
and /
are calculated before those involving +
and -
, as is customary in elementary school mathematics.
first = 2
print(first) # prints 2
second = 4
print(second) # prints 4
sum = first + second # The sum of the values of the variables first and second is assigned to the variable sum
print(sum) # prints 6
You can affect the order of operations by using parentheses. Operations within parentheses are performed before those outside them.
calculation_with_parentheses = (1 + 1) + 3 * (2 + 5)
print(calculation_with_parentheses) # prints 23
calculation_without_parentheses = 1 + 1 + 3 * 2 + 5
print(calculation_without_parentheses) # prints 13
The example above can also be divided into steps.
calculation_with_parentheses = (1 + 1)
print(calculation_with_parentheses) # prints 2
calculation_with_parentheses = calculation_with_parentheses + 3 * (2 + 5)
print(calculation_with_parentheses) # prints 23
calculation_without_parentheses = 1 + 1
calculation_without_parentheses = calculation_without_parentheses + 3 * 2
calculation_without_parentheses = calculation_without_parentheses + 5
print(calculation_without_parentheses) # prints 13
value = 1 + 1 + 3 * 2 + 5
above is performed before the result is assigned to the variable.An expression is evaluated where it occurs in the program’s source code. As such, the evaluation can occur within a print statement, if the expression is used in calculating the value of the print statement’s parameter.
first = 2
second = 4
print(first + second) # prints 6
print(2 + second - first - second) # prints 0
An expression does not change the value stored in a variable unless the expression’s result is assigned to a variable or used as a parameter, for instance, in printing.
first = 2
second = 4
first + second
we would get the output
Note that when working with numbers, the print
statement is implicit. It is not recommended to omit the print
statement intentionally, unless working with very simple programs as it can often lead to confusion.
The command print
prints the value of a variable. The string literal to be printed, which is marked by quotation marks, can be appended with other content by using the operation +
.
length = 42
print("Length " + str(length))
print("here is an integer --> " + str(2))
print(str(2) + " <-- here is an integer")
If one of the operands of the operation +
is a string, the other operand must be changed into a string too during program execution. In the example below, the integer 2
is turned into the string “2”, and a string has been appended to it.
The precedence introduced earlier also apply here:
print("Four: " + str(2 + 2))
print("But! Twenty-two: " + str(2) + str(2))
Applying this knowledge, we can create an expression consisting of some text and a variable, which is evaluated in connection with the printing:
x = 10
print("The value of the variable x is: " + str(x))
y = 5
z = 6
print("y is " + str(y) + " and z is " + str(z))
Division is accomplished in a similar way to addition and multiplication, but we have to be careful dividing by zero or something close to zero.
result = 3 / 2
print(result)
When a computer executes program code, it does it one command at a time, always advancing exactly as specified by the code. When a value is assigned to a variable, the same chain of events always occurs: the value on the right-hand side of the equality sign is copied and assigned to the variable on the left-hand side (i.e., copied to the location specified by that variable).
It’s crucial for a programmer to understand that assigning a value to a variable always does the same thing.
Here’s three common misunderstandings related to assigning a value to a variable:
Viewing value assignment as a transfer instead of a copy operation: once first = second
has been executed, it’s often assumed that the value of the variable second
has been moved to the value of the variable first
, and that the variable second
no longer holds a value, or that its value is 0, for instance. This is incorrect, as executing first = second
means that the value in the position specified by second
is merely copied to the place specified by the variable first
. Hence, the variable second
is not modified.
Viewing value assignment as creating a dependency instead of being a copy operation: once first = second
has been executed, it’s often assumed that any change in the value of the variable second
is automatically also reflected in the value of the variable first
. This is incorrect; assignment – i.e., copying – is a one-off event. It only occurs when the program code first = second
is executed.
The third misunderstanding concerns the direction of copying: it’s often thought that in executing first = second
the value of the variable first
is set as the value of the variable second
. The confusion also manifests itself in situations where the programmer accidentally writes e.g. 42 = value
– fortunately, IDEs provide support on this issue too.
Perhaps the best way to understand a program’s execution flow is through the use of pen and paper. As you’re reading the program, write down the names of any new variables, while making a note of how the values of the variables in the code change line by line. Let’s demonstrate the execution with the following program code:
line 1: first = (1 + 1)
line 2: second = first + 3 * (2 + 5)
line 3:
line 4: first = 5
line 5:
line 6: third = first + second
line 7: print(first)
line 8: print(second)
line 9: print(third)
The execution flow of the program above has been broken down below.
Duration: 01:00:00
Our programs have so far been linear. In other words, the programs have executed from top to bottom without major surprises or conditional behaviour. However, we usually want to add conditional logic to our programs. By this we mean functionality that’s in one way or another dependent on the state of the program’s variables.
To branch the execution of a program based on user input, for example, we need to use something known as a conditional statement. The simplest conditional statement looks something like this.
print("Hello, world!")
if True:
print("This code is unavoidable!")
A conditional statement begins with the keyword if
followed by a condition, which is evaluated when the conditional statement is reached. The result of the evaluation is a boolean value. No evaluation occurred above. Instead, a boolean value (True
) was explicitly used in the conditional statement.
The condition is followed by a block, which is indented beneath. The source code inside the block is executed if the expression inside the parentheses evaluates to True
.
Let’s look at an example where we compare numbers in the conditional statement.
number = 11
if (number > 10):
print("The number was greater than 10")
If the expression in the conditional statement evaluates to true, the execution of the program progresses to the block defined by the conditional statement. In the example above, the conditional is “if the number in the variable is greater than 10”. On the other hand, if the expression evaluates to false, the execution moves on to the statement after the closing curly bracket of the current conditional statement.
A code block refers to a section with a particular indentation level from the left hand-side.
Most of our programs have included a recurring snippet def main():
, which begins a block, with the code inside the function indented below.
Blocks define a program’s structure and its bounds. A conditional statement also marks the start of a new code block.
# Look at the indentation below, which marks the blocks
def main(): #start block 1
number = 10 #inside block 1
if (number > 5): #start block 2
print('This is greater than 5!') #inside block 2
if __name__ == '__main__':
main() #outside block 1 and 2 but inside the if block
In addition to the defining program structure and functionality, block statements also have an effect on the readability of a program. Code living inside a block is indented. For example, any source code inside the block of a conditional statement is indented deeper than the if
command that started the conditional statement. Indents can also be added by pressing the tab key (the key to the left of ‘q’). When the block ends, the indentation also ends. Python has explicit style guidelines on how code should be indented in the PEP 8 guidelines discussed previously. It boils down to:
The example below is incorrectly indented and will result in an error.
if (number > 10):
number = 9
The example below is correctly indented.
if (number > 10):
number = 9