Python: Some Basics

Welcome to python, my personal favorite programming language. It’s versatile and easy to learn, so let’s get right into it.

Disclaimer: this is by no means a comprehensive python tutorial. Here you will find basics for use in the following tutorials. If you want to learn more, check out Think Python.

Variables:

In Python, we often store things in variables. I prefer to name my variables using CamelCase, which we’ll talk about later.

Here, the variable “x” is having the integer “5” stored inside it. It’s important to note that here, we use the single equals sign “=” that means “assignment.” It is used to set something equal to something else; not to check if two things are equal.

In [1]:
x = 5

Once a variable is declared, we can use it. Here, “*” signifies multiplication.

In [2]:
x*5
Out[2]:
25

Integers:

In the previous example, we set an integer “5” to the variable “x” but now let’s see what else we can do with integers.

First, let’s confirm the type of variable “x” which we know to be an integer.

In [36]:
type(x)
Out[36]:
int

In Python, “int” is short for integer.


Floats:

“Float” is short for floating point value. We won’t go into the details of what that means, but it is worth understanding that floats are numbers with decimal representations.

In [37]:
y = 3.14
In [39]:
type(y)
Out[39]:
float
In [38]:
y*2
Out[38]:
6.28

Strings:

Think of strings as text. But this text is different from other text in Python. It’s text that is uninterpreted by Python. In Python, strings are either represented inside double quotes or single quotes but never both at the same time.

In [40]:
string = "Happy Birthday!"
In [42]:
type(string)
Out[42]:
str

In Python, “str” is short for “string”

 


 

We can index strings, cutting them up as we please.

Let’s get the first letter of our string:

In [43]:
string[0]
Out[43]:
'H'

Booleans:

In Python a boolean is either True or False. Let’s try them out.

In [44]:
z = False
In [45]:
type(z)
Out[45]:
bool

“Bool” is short for boolean.


Tuples:

You can think of tuples as pairs of items.

In [3]:
myTuple = ("Apples", 3)

 

If you only want one element from a tuple, you can using indexing to get it.

In the following example, the brackets tell Python we’re indexing and the 0 asks for the first element.

In [4]:
myTuple[0]
Out[4]:
'Apples'

Lists:

You can think of lists as collections of items.

In [5]:
myList = [1, 2, 3]

 

We can index here too. Because indexing starts at 0 and counts upward, if we want the 3rd element (3), then we have to index position 2.

In [6]:
myList[2]
Out[6]:
3

 

You can also append to lists:

In [7]:
myList.append(4)
In [8]:
myList
Out[8]:
[1, 2, 3, 4]

 

You can put tuples inside lists.

In [9]:
myList = [("Apples", 3), ("Bananas", 2), ("Pears", 1)]

Then, you can index to either specific elements, or elements contained within elements.

 


 

Here’s what I mean:

Indexing to a tuple:
In [10]:
myList[1]
Out[10]:
('Bananas', 2)

Indexing to an element inside a tuple:
In [11]:
myList[1][0]
Out[11]:
'Bananas'

You can then convert this list of tuples to a dictionary.

 


 

Dictionaries are like unsorted phone books, except there can only be one of every phone number. They’re groups of pairs of items. The first item in that pair is called a key and the second item is called a value. They’re a useful way of storing corresponding data points.

In [12]:
dict(myList)
Out[12]:
{'Apples': 3, 'Bananas': 2, 'Pears': 1}

 

Then, we can index specific keys:

In [13]:
dict(myList)["Bananas"]
Out[13]:
2

 

You can also make dictionaries without the need for lists or tuples.

In [14]:
fruits = {"Oranges": 4, "Grapes": 5, "Mangos": 6}

 

If we want to take this dictionary and turn it into a list of tuples, we can do that too.

In [15]:
fruits.items()
Out[15]:
dict_items([('Grapes', 5), ('Mangos', 6), ('Oranges', 4)])

Comments:

“#” is a special character in Python, all the text following it on a line will not be executed.

In [16]:
#This is a comment. It means that Python does not interpret anything on this line.
#I'll be using these to occasionally let you know what I'm doing.

Importing Modules:

In Python, a module is a package containing pre-written code that we can use.

In [17]:
#Python recognizes special keywords like "import."
import math

Now, we have the code contained within that packages available to us.


From the math module, we use the radians function to convert from degrees to radians.

In [18]:
math.radians(360)
Out[18]:
6.283185307179586

Now, if all you wanted was just the radians function from the math module, you could import only that.

In [19]:
#Python recognizes special keywords like "from."
from math import radians
In [20]:
radians(180)
Out[20]:
3.141592653589793

But let’s say you want the entirety of the webbrowser module but you’re sick of typing “webbrowser” every time. Then, you can change what you call that module.

In [21]:
#Python recognizes special keywords like "as."
import webbrowser as web
In [22]:
web.open('https://pymotw.com/2/webbrowser/')
Out[22]:
True

Loops:

Sometimes we want to run the same code multiple times.

In [23]:
print("Test!")
print("Test!")
print("Test!")
Test!
Test!
Test!

 

But it can be pretty annoying rewriting code over and over.

Luckily, we have “for” loops.

In [24]:
for i in range(3):
    print("Test!")
Test!
Test!
Test!

 

There are also “while” loops. They run for as long as a condition is true. Here’s a tough example.

In [25]:
i = 0               #We start to increment at 0.
while i < 10:       #We check to see if i is less than 10.
    print(i)        #We print i.
    i = i + 1       #This means to add 1 to i, and save it as i. Think of it as incrementing.
0
1
2
3
4
5
6
7
8
9

 

The same end can be achieved in a for loop. Here’s how that would be done:

In [26]:
for i in range(10):
    print(i)
0
1
2
3
4
5
6
7
8
9

Making your own function:

Up until this point, we’ve been using functions we knew already existed. If you want to make your own functions, you can do that too. Here, “def” is short for “define” and it says that the following code is the name of the function. Naming customs vary, but I’m a personal fan of CamelCase. In parentheses we give it an input, and return just tells it what output to give.

In [27]:
def radiansToDegrees(radians):
    return radians * (180/3.141592653589793)

 

Then we can run our function.

In [28]:
radiansToDegrees(3)
Out[28]:
171.88733853924697

List comprehension:

Let’s say you want to make a list but appending to it in a for loop seems tedious. Thankfully, we have list comprehension, which lets us build lists more easily.

In [29]:
fruitsDictionary = {"Apples": 1, "Bananas": 2, "Grapes": 3, "Oranges": 4}

 

Now we have a dictionary, but what if we only want the names of the fruits? Here’s how we get them out and into a list.

In [30]:
fruitsList = [fruit for fruit, number in fruitsDictionary.items()]
In [31]:
fruitsList
Out[31]:
['Grapes', 'Apples', 'Oranges', 'Bananas']

Conditionals:

Often, we only want code to run under specific circumstances. Conditionals make this possible. Think of them like single-use “while” loops.

In [32]:
if 1 < 2:
    print("1 is less than 2!")
1 is less than 2!

 

You can think of “else” as meaning something like “otherwise.” It’s every case other than the “if.”

In [33]:
if 1 < 0:
    print("1 is less than 0!")
else:
    print("1 is not less than 0!")
1 is not less than 0!

 

“elif” is short for “else if” and goes in between your if and else. It’s used to cover whatever remaining cases you want to check for.

In [34]:
if 1 < 0:
    print("1 is less than 0!")
elif 1 == 1:
    print("1 is equal to 1!")
else:
    print("Something else is true!")
1 is equal to 1!

Exceptions: sometimes stuff goes wrong

When code breaks, it can be frustrating. Luckily, Python lets us respond to exceptions in our code really easily.

In [35]:
try:
    1/0 #What's 1 divided by 0?
except ZeroDivisionError:
    print("You can't divide by zero!")
You can't divide by zero!

Now you have the basics necessary to move on not just in these tutorials, but in Python as well.


<–Go Back to Resource Guides Main Page
<–Go Back to Coding Resource Guides Main Page