Python turbo-start guide

A guide to help people new to python get a boost in learning the language

Contents

Hello world

print("Hello World")

Breakdown

print() is the builtin python function for printing or displaying something in the terminal/command line. The () are the container where you put the information to be displayed

"Hello World" is a string that the print() function displays in this code

Syntax

Python uses indents/tabs to indicate when a line of code is inside a statement, example:

if variable == True:   # <-- statement
    print("it's true!")

Notice in the above code in addition to an indent, a colon ":" is used before the indented line to indicate that whatever follows has to be inside the statement.

One more thing to notice is, unlike many languages, python doesn't use a semicolon ";" to indicate the end of a line.

Variables

variable = "penguin"

A variable is a container for information that exists for as long as a program runs. In the code above variable is the container which can be used to call the variable later on and "penguin" is the information inside the container

Data types

String

"This is a string"

Strings are made with quotes surrounding the string, and they can be either single or double quotes

You can convert something to a string by putting it inside the builtin str() function

str(numberVariable)

You can add a string to another string:

"a string" + "another string"

Integer

12

Nothing special here, just a plain integer or non-decimal non-imaginary number that can be positive or negative

Float

12.321

Basically the same as Integer except it's a decimal number

List

alist = ["a string", 1, 1.21, "another string"]

To indicate something as a list we put brackets [] around it. Anything can be in a list and everything in a list is separated by a comma ","

To call up something from a list you use an index aka the number assigned to that something (an instance):

alist[0]

The indexes always start from zero and go up from there

You can add something to a list by using .append():

alist.append("something new")

this will add "something new" to the end of the list

Remove something from the list by using the index:

alist.pop(2)

Remove something from the list by using the instance itself:

alist.remove("something new")

Or we can assign another instance to a specified index:

alist[1] = "something else"

Dictionary

adict = {"one" : "first number", "two" : "second number"}

To indicate a dictionary we put {} around it. In the example above "one" is a key and "first number" is a value. We use the keys to get the values like we use indexes in lists to get the instances. We can also reassign a value to a key or make a whole new key much like we make variables:

adict["three"] = "third number"

Statements

If, elif, else

if variable == another_variable:
    some code
elif variable == whole_other_variable:
    some other code
else:
    final code if nothing works

This statement works on conditions, if a condition is true it execute the code, if not it moves on. if is the first check point to check for a condition, after that you can add as many elif as you'd like for additional checkpoints in case the previous one(s) didn't work. else is the last resort when nothing works.

The == is checking for instances on both sides to be the same.

Some other operators are:
<= smaller or equal to
>= bigger or equal to
!= not equal to

The if or elif statement also counts 1 or True as true, and 0 or False as false:

if 1:
    some code
elif 0:
    some more code

While

while True:
    if something:
        break
    elif something_else:
        continue

while is a loop that keeps executing the code inside of it over and over again until it finds a condition that stops it

In the code above there is break and continue. break makes the program exit the loop when the program finds it. continue tells the program to go to the start of the loop without going through anything in the loop that's after continue.

For

for i in range(5):
    print(i)

Another loop, this one however keeps running for a set amount of times, in the case above it will run for 5 times and the count will start at 0. A for loop creates a variable the name of which you give it, in this case i, and updates it every cycle. The for loop can work with any data type, if you give it a list:

for instance in alist:
    print(instance)

it will go over the list's instances and for each cycle it will assign the instance it's at to the variable.

Try, except

try:
    alist[i] = "I don't know... something"
except IndexError:
    print("oops, we got an error")

try except handles or rather catches errors. The code inside try: is the code where we anticipate an error to happen. When we get the error, instead of exiting the program with a traceback it goes to except: and if we specify an error to catch like above it looks for that error, otherwise it catches any error that happens inside the try: code.

File handling

with open(file.txt, "r") as f:
    print(f.read())

Above code opens file.txt in a read only mode "r" and assigns f for any work on the file such as the f.read()

modes to open the file with:
w open file for write only
r open file for read only
a open file for append only
There are more modes out there, I'm just keeping it to the basics here.

Other useful stuff

pass

If you need code that doesn't do anything, pass is your friend

"".join(alist)

"".join() basically converts a list to a string, what ever you put inbetween the quotes is what it will put inbetween each instance when joining them together. Just make sure your list has only strings.

2 Replies to “Python turbo-start guide”

Leave a Reply

Your email address will not be published.