Programming stands for the abstraction and translation of real life instructions into instructions that a computer can understand.
Many people don't quite grasp the difference between the process of computers, so I will list core differences below.
In a nutshell, the Turing machine is a device that has a pointer and a set of instructions. Think of it as a person who can only do one task at a time and be given a next task.
This means that there cannot be any concurrent instructions
For example
Run 10 times
Swing arms 10 times
Will just result in running, and then swinging arms
To perform seeminly concurrent instructions,
For 10 times:
Run
Swing arms
Note: multicore CPUs are able to perform this kind of task, but you have to learn how this is achieved in single core.
The sentence My score is higher than you
does not make sense to a computer.
This is because My score (Number)
is not comparable to you (Person)
.
If you want to compare, say My score is higher than your score
.
The following statement If Variable is "Hello" or "Hi"
is understood by humans as If Variable is "Hello"
or If Variable is "Hi"
However, it is interpreted as If Variable is "Hello"
or "If "hi"
. Your syntactical understanding of the English language will not carry over to a programming language.
Lets say you want to go inside a movie theater. You forgot your tickets to the movie but you still try to go in. The guard will tell you You don't have your tickets. You cannot go in
. A compiler/interpreter might tell you: Unauthenticated entity is not authorized to enter or has insufficient permissions
. A good language might give you an even better error: Entity person has missing attribute 'ticket' or missing permission: 'administrator', 'owner', 'staff'
. The point is the language doesn't know whether the person trying to access is supposed to be. A guard obviously knows that you are a customer, but from a language's perspective, you might be an administrator with a missing administrator position. The point is, the language will always try to give accurate error messages from its perspective.
Here is an example from python
str = "You got: "
a = 10
b = 20
print(str)
print(str(a + b))
# TypeError: 'str' object is not callable
This error doesn't sense to a human. But try thinking it from a computer's perspective. A function is called via ()
, and the programmer is attempting to call str
. However, str
is now a string, making it an uncallable object or, simply, a non-function. So in this context, the human error would be: str was assigned to "You got 10:" and is now a string. Thus, the variable str is no longer a function you can call
.
Now with those out of the way, you are ready to start programming in python
Date is split into two types: objects and primitives. Objects are more complicated than primitives but they are versitile. This tutorial does not cover objects and OOP (object oriented programming) as I believe that it is not relevant for beginners.
A primitive is pretty self explanitory. It is a single value.
It is worth noting, however, that different programming languages have different ideas on what should be considered a single value, and thus have different implementations. In our case with Python, these so called "primitives" are actually object implementations, but we call them primitives because it is recommended to treat it like so.
For example, C thinks that "Hello" is a collection of 'H', 'e', 'l', 'l', 'o', which is an object.
Python thinks that "Hello" should be just "Hello" and the developer should treat it like a primitive.
Java thinks that numbers above a certain size are a collection of bytes which is an object.
Python thinks that any number, regardless of its size, should be a primitive.
Since we are doing Python, here are the list of primitives and objects.
- int - Integer: stores a whole number (no decimal points)
- float - Float: stores a floating point decimal number (not to be confused with Decimal)
- str - String: stores a sequence of characters
- bool - Boolean: stores a true or false value
- NoneType - None: stores a value that represents "nothing"
- list - List: Stores a list of values
- set - Set: Stores a set of values
- dict - Dictionary: Stores a set of key-value pairs
- tuple - Tuple: Stores a list of values that cannot be changed
- And some other types such as
- decimal.Decimal - Decimal: Stores a fixed point decimal number (not to be confused with float)
- datetime.datetime - Datetime: Stores a date and time
- datetime.date - Date: Stores a date
- ... and many more
The reason why this is primitive and object difference is important is because it decides how variables are copied over.
a = 1
b = a
b += 1
print(a, b) # 1, 2
c = []
d = c
d += [1] # appends 1 to the list
print(c, d) # [1], [1]
The above code is the main source of confusion for beginners. Which is why I am explaining it before diving in
A statement and expression are two different things in Python.
A statement always executes something, but does not return a value.
An expression can execute something, and returns a value.
# Statement
a = 1
# Expression
1 + 1
# Statement that has an expression
a = 1 + 1
# Expression and an execution
print_hello_and_return_3()
# A statement that has an expression and an execution
code = print_hello_and_return3()
Note: in Python 3.8+ there is an operator called the warlus operator
:=
. This is a unique case of a statement being an expression. I highly suggest that you don't use it until you get comfortable with the language as it is easy to misuse.
Python is a whitespace sensitive language, meaning that the whitespace will cause issues if you don't put the correct count. This is an easy concept to understand.
if True:
print("hi")
# Wrong
if True:
print("Hi")
#Correct
A variable must start with a letter or underscore, and the remaining part can have numbers
valid:
_
_hi
John3
invalid:
3
3_3
.hi
some_number = 1
some_float = 1.0
some_string = "Hello"
some_boolean = True # True, False. You have to capitalize
# For loop
# Syntax: for <variable> in <iterable (list)>:
for i in [1,2,3]:
print(i)
for i in range(1, 4):
# `range` is a function that returns an iterator which acts like a list.
# Try `print(list(range(4)))`
print(i)
# While loop
# Syntax: while <condition>:
i = 0
while i < 4:
print(i)
i += 1
# Both for and while
break # breaks out of the loop
continue # go to the top of the loop
# Example
for i in range(4):
if i == 2:
break
print(i)
# Prints 0, 1
for i in range(4):
if i == 2:
continue
print(i)
# Prints 0, 1, 3
# If, elif, else clause
# Syntax:
# if <condition>:
# elif <condition>:
# else <condition>:
# There can only be one if and else in a chain, and everything else is else-if (elif)
if True:
print("hi")
if 3 == 4:
print("hi")
elif 3 == 3:
print("hi")
else:
print("hi")
user_input = input("Prompt: What is your name? ")
# The remaining code will not run until user has pressed Enter
print(user_input)
# +
1 + 1 # Add two numbers
"Hello" + "World" # Concatenate two strings -> "HelloWorld"
# -
1 - 1 # Subtract two numbers
# *
1 * 1 # Multiply two numbers
"Hello" * 3 # Repeat string "HelloHelloHello"
# /
1 / 1 # Divide two numbers (floating point division 7/2 => 3.5)
# //
1 // 1 # Integer division 7//2 => 3
# %
1 % 1 # Modulo 7 % 2 => 1
# == Equals
1 == 1 # True
1 == 2 # False
# != Not equals
1 != 1 # False
1 != 2 # True
# >, <, >=, <=
# Greater than, less than, greater than or equal, less than or equal
1 > 0 # True
1 > 1 # False
1 > 2 # False
# Note: >= and <=, both have = coming after the comparator
1 >= 0 # True
1 >= 1 # True
1 >= 2 # False
# Fun fact
1 > 0
not (1 <= 0)
# These two are the same expression
# and
True and True # True
True and False # False
False and True # False
False and False # False
# or
True and True # True
True and False # True
False and True # True
False and False # False
# not
not True # False
not False # True
# +=, -=, *=, /= etc... Shorthand assignment operator
# Syntax: <identifier> <operator>= <expression>
a += 2 # a = a + 2
a *= 2 # a = a * 2
# list expression
[1,2,3]
# Concatnate list (returns a new list)
[1,2,3] + [4,5,6] # [1,2,3,4,5,6]
# Check if item is in list
1 in [1,2,3] # True
# Syntax: def <variable>(param1, param2, param3...):
def print_hi():
print("hi")
def sum_numbers(a, b):
return a + b
# Check if a user input has the word hello or hi in it
user_input = input("Say hi")
words = user_input.split(" ")
print(words)
for word in words:
print("Checking word: " + word)
if word == "hello" or word == "hi":
print("There is a hi")
break
# If there wasn't a break
else:
print("We did not find the word 'hello' or 'hi'")
print("end of program")