Login

Python Tutorial - Basics

This is a beginner Python tutorial that will walk you through the basics. Python is a great language for beginners, it's very readable and easy to use. Let's jump in.

Hello World

The first app that you write in any language is going to be Hello World, you just write:

>>> print("Hello World")
Hello World

With print() you can output information to your console, it's called the Standard Output - stdout.
Try it out:

Data Types and Variables

You can't do much without variables. Variables are how you store and pass values around. There are a few basic data types you should get familiar with: boolean, string, integer, float. There are more than that, but these will get you on your way. Here are some examples of each:

# Boolean
>>> a = True
>>> b = False
# String
>>> c = 'Hello'
>>> d = "There" # either ' or " works
# Integer
>>> e = 5
>>> f = -4
# Float
>>> g = 1.03

And of course you can do various operations with variables - like in math

>>> x = e + f + 1 # this will be 2
>>> g = c + " " + d # "Hello There"
>>> print(g + x) # This will not work!
TypeError: unsupported operand type(s) for +: 'int' and 'str'
# Can't combine strings and numbers like that

>>> print(g + str(x)) # converting number to string
Hello There2

# or

>>> print("%s%s" % (g, x)) # but this is a little more advanced
Hello There2

Why don't you try?

Structures

Let's go over some of the most common structures in Python

List

Just like the name says it's a list of things, here's an example of a list of integers:

>>> a = [5, 2, 8, 3]

A list is ordered and indexable, meaning you can grab something by index. You can also add and remove things from it.

>>> b = a[0] # indexes always start with 0
>>> c = a[2]
>>> print(b + c)
13
>>> a.append(2)
>>> print(a)
[5, 2, 8, 3, 2]

Want to check out all the functions you can call on a list? take a look at the Python official documentation.

Tuple

Similar to a list, but you can't change it once it's created

>>> a = ("hey", "there")

You can, grab items from it by index, just like a list. But you can't modify it. It's good for when you need something that you know where everything will be

>>> a = ("John", "1111 S Belleview Dr")
>>> name, address = a
>>> print(name)
John
Set

A Set is slightly different than a list, it's unordered and unindexed. You can't just pull out something from it like you would with a list. It also doesn't support duplicates. It's a good, fast structure for when you need to look something up.

>>> invited_guests = ["john", "kate", "mary", "john"]
>>> unique_invited_guests = set(invited_guests)
>>> print(unique_invited_guests)
{'mary', 'kate', 'john'}
# let's check if 'kate' can make it
>>> print('kate' in unique_invited_guests) # nice and fast lookup
True
Dictionary

Along with List, a Dictionary is something you will constantly use. It's a key/value structure. it's unordered and you can only index it by the key.

>>> ages = {'kate': 24, 'john': 53, 'jeff': 20}
>>> print(ages['john'])
53

You can also mix data structures

>>> data = {
...          'kate': ('smith', 23, 'female'),
...         'john': ('brown', 53, 'male')
...}
>>> print(data['kate'][2])
female
Test

Control Flow

To be able to actually do anything useful with those variables and structures, you need to be able to control the flow of the application

If/Else

Using if/else and conditions we can control what our program does. Let's continue with the example above, we are inviting guests to our kid's birthday party, and we only want to invite them if they are below a certain age.

>>> name, age = "john", 20
>>> if age <= 12:
>>>    print("invited")
# We aren't going to invite john because he didn't pass our condition

You can use only 'if', or add 'elif' and 'else' for more control

>>> name, age = "john", 80
>>> if age > 3 and age <= 12:
>>>    print("invited")
>>> elif age > 12:
>>>    print("not invited")
>>> elif age > 65:
>>>    print("invited to party #2")
>>> else:
>>>     print("too young")
not invited

I threw a little curve ball in there, the second condition got evaluated first and we didn't invite, even though John should have been invited to party #2. Any idea how to solve that?


For Loop

What if we want to iterate over something? That's what a For loop is for

>>> names = ['john', 'kate', 'sarah']
>>> for name in name:
>>>     print(name)
john
kate
sarah

Or we want to do it by index

>>> names = ['john', 'kate', 'sarah']
>>> for i in range(0, len(names)):
>>>     print(names[i])
john
kate
sarah
While loop

A while loop will keep looping until the condition becomes False

>>> names = ['john', 'kate', 'sarah']
>>> i = 0
>>> while names[i] != 'sarah':
>>>     print(names[i])
>>>     i += 1
john
kate

You can also use 'continue' and 'break' to either continue the loop no matter where you are or to break out of it. Works for both for and while loops

>>> i = 0
>>> while True:
>>>     if i == 2:
>>>         i += 1 # have to remember to increment or we'll be stuck here forever
>>>         continue
>>>     if i == 4:
>>>         break
>>>     print(i)
>>>     i += 1
0
1
3
Check out the Python official documentation for more examples

Test

Ok, let's put all of that together:

Done

Great Job! Even though you are just starting and this stuff seems hard, programming is just a matter of practicing over and over. At some point all this stuff becomes second nature.