A Basic Guide to Python

Input and output

I/O (input and output) are the methods through which your user can interact with the computer. Generally we think of these in the form of buttons and graphical user interfaces (GUI) but those can be very technical.

All programming languages have the most primitive formats of I/O using a terminal (a.k.a Command Line Interface or CLI).

Input

To have a user input data from the terminal, use the function

input()

e.g.

x = input("Enter a number")

This will display the text “Enter a number” on the screen, wait for the user to enter a value (the user tells the system they have finished their entry by pressing ‘Enter’), then finally store this value in the variable x

Output

To have the program display text in the terminal use

print()

e.g.

print("Hello") # prints "Hello"

x = 5
print(x) # prints "5"

x = 4
y = 5
print(x + y) #prints "9"

Assignment

All programming languages are able to store data in the memory of the computer for as long as the computer is running. This storage is called a variable.

The structure of a variable

A variable has 4 main components:

Declaring a variable

To create a variable is called Declaring.

To declare a variable in python, you simply state its identifier then assign a value using ”=”. e.g.

variable = 5
x = 6
y = 3
z = x + (y * 2) #z = 12

Identifiers

The Identifier for a variable is essentially its name. This has no effect on the data type of the variable nor the type of data it can store. The only rules for the identifier are that:

Data Types

The Data type of a variable is the type of data it can store, this is important since in a computer all data is technically a number, which is then interpreted differently based on the data type. For example as an integer, the number 65 is the number 65. But as a string, the number 65 is interpreted as the letter “a”.

Python has something called inferred data types. This means that the programming language is guessed based on the data that is being put into the variable.

Despite this, it is still useful to be aware of the different types in python and how to use them properly.

Primitive Data Types

The most basic data types in python are called Primitive Types

NameDescriptionExample
stringText (Unicode)"Hello World"
integerA Whole Number (positive or negative)5
floatA decimal Number3.5
complexA complex or imaginary number5j
booleanA true or falsex = True
y = False
bytesA sequential set of bytesb255 (11111111 in binary)
NoneTypeNullNoneType

List Data Types

A List type is able to store a sequence of variables

NameDescriptionDeclarationAccess
ListA list that may be edited and can contain duplicate valueslist = [1, 2, 5, 2, 7]list[3] = 2
TubleA list which cannot be edited after being createdtuble = [1, 2, 5, 2, 7]tuble[3] = 2
SetA list of a set size, which can have values added to and removed from and cannot contain duplicatesset = {1, 2, 5, 6, 7}set[3] = 6
DictionaryA list where each value is associated with a key, the value can be the same as another value but a key cannot be the same as another keydict = {1: "item1", 2: "item2", 3: "item1"}dict[3] = "item1"

Scope

Scope is the area within code where a variable or function can be accessed.

Any variable can be accessed in an area that has the same or more indentation than where it was declared.

e.g.

x = 5
if (True):
    y = x + 5 #this code will work as x is still in scope here

z = x + y #this code will not work as y is not in scope here

Arithmetic Operators

NameDescriptionSymbolUsage
addadds 2 numbers together+x = 1 + 1 x = 2
subtracttakes the second number from the first-x = 2 - 1 x = 1
multiplymultiplies 2 numbers*x = 3 * 2 x = 6
dividedivides the first number by the second/x = 5 / 2 x = 2.5
integer dividedivides the first number by the second and returns the integer part//x = 5 // 2 x = 2
exponentgives the first number to the power of the second number**x = 3 ** 2 x = 9
modulusinteger divides the 2 numbers then returns the remainder%x = 5 % 2 x = 1

Selection

Selection is another essential part of any programming language, it is used to choose which block of code should run based on a boolean condition

This is achieved through an IF Statement

IF Statment

An if statement will run 1 block of code if a condition is true

x = 5
y = input("Enter a number")

if v1 == v2:
    print("hi")

ELSE Statement

An else statment runs code if the condition is false

x = 5
y = input("Enter a number")

if x == y:
    print("hi")
else:
    print("bye")

ELIF Statement

An elif statement allows you to chain ifs to continuously test multiple conditions until 1 is correct (you can also end this with an else to catch any other posibility)

x = 5
y = input("Enter a number")

if x == y:
    print("hi")
elif y = z:
    print("howdy")
else:
    print("bye")

An else statement must always be at the end of this chain.

Nested IF

A Nested if statement is an if statement inside of another if statement

x = input("Enter a number")

if x > 5:
    if x < 6:
        print("hello")
    else:
        print("goodbye")
else:
    print("ahhhhh")

Boolean Operators

A condition is what is tested in an if statement and must be a boolean value.

Boolean values can be tested using a boolean operator.

for the sake of these, assume x = 32

NameDescriptionSymbolUsage
EqualChecks to see if a value is equal to another value==x == 32 is true
Greater thanChecks to see if a value is greater than another value>x > 31 is true
Less thanChecks to see if a value is less than another value<x < 33 is true
Greater than or equal toChecks to see if a value is greater than or equal to another value>=x >= 32 is true
Less than or equal toChecks to see if a value is less than or equal to another value<=x <= 32 is true
Not equalChecks to see if a value is not equal to another value!=x != 17 is true
ANDCompares 2 values, if both are true then returns true, otherwise returns falseandTrue and False is false
ORCompares 2 values, if at least 1 is true then returns trueorTrue or False is true
NOTCoverts a boolean to its inverse (true becomes false and false becomes true)notnot False is true

Iteration

Iteration is the process of running a block of code multiple times

Unconditional Loops

An unconditional loop will run a block of code a set number of times, this is often referred to as a for loop.

A for loop has 3 parts, the start, end and step. A for loop will assign the start to a variable (i in this case). Each time the loop goes around, it will add the step to the value of i until it is greater than the end.

for i in range(1, 10, 2):
    print(i)

This block of code will run 5 times, each time printing the value of i (1, 3, 5, 7, 9)

A for loop can also be used to loop through each item in a list

testList = ["value1", "value2", "value3"]
for item in testList:
    print(item)

This will loop through each item in testList and print it to the terminal.

Conditional Loops

A conditional loop is a loop which will run a block of code until a condition is false.

x = 5
while x < 10:
    x + 1

This will run 5 times, each time adding 1 to x until x is not less than 10

Functions

A function is a block of code that can be run within another block of code

Parts of a function

In python, a function has 4 main components:

Declaring a function

To create a function is called declaring a function. It should be noted that declaring a function does not cause that function to run, it will not run until it is called

def functionName():
    print("Function is running")

Calling Functions

To call a function is to cause it to actually run at that point in the code

def writeHello(): #this line declares the function however it does not run
    print("Hello World")
    print("How are you today")

writeHello() #this line calls the function so that itll actually run

Returns

A function can be made to return a value using the return keyword.

def getPI():
    return 3.14152653589

x = getPI()

Passing Values

A function can be given values to use

def addOne(number):
    return number + 1

x = addOne(5) #x = 6