Learning Python

Hello World

print is a method that will print some text


In [7]:
print("Hello World")


Hello World

Indentation

Instead of using curly braces, python uses identation of blocks.

If Statements


In [15]:
x = 1

if x < 0:
    print("x is negative")
elif x == 0:
    print("x is zero")
elif 0 < x:
    print("x is positive")
else:
    print("ERROR")


x is positive

Naming conventions

Function and variable names should all be lowercase with underscore (_) separating each word.

Variables

Variables are dynamically types, we don't need to declare the type of a variable


In [22]:
var_integer = 10
var_float = 10.1
var_string = "one"

In [24]:
print(var_integer)
print(var_float)
print(var_string)


10
10.1
one

Lists

A list can contain any type (or mix of type) of variables.


In [25]:
my_list = [1, 2, 'three']
print(my_list)


[1, 2, 'three']

In [26]:
my_list.append('four')
print(my_list)


[1, 2, 'three', 'four']

In [28]:
print(my_list[0])


1

Operators


In [29]:
first_string = 'Hello'
second_string = ' '
third_string = 'World'
concatenated_string = first_string + second_string + third_string
print(concatenated_string)


Hello World

In [30]:
evens = [2, 4, 6, 8]
odds = [1, 3, 5, 7, 9]
numbers = evens + odds
print(numbers)


[2, 4, 6, 8, 1, 3, 5, 7, 9]

String Operations


In [1]:
astring = "1234567890"
print(astring[3:7])


4567

Conditions


In [2]:
name = "one"
if (name == 'one'):
    print('This is one')


This is one

In [3]:
number = "two"
if number in ["one", "two", "three", "four", "five"]:
    print('number is within array')


number is within array

Loops


In [4]:
primes = [2, 3, 5, 7, 11]
for prime in primes:
    print(prime)


2
3
5
7
11

In [5]:
count = 0
while count < 5:
    print(count)
    count += 1


0
1
2
3
4

In [6]:
count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break


0
1
2
3
4

In [7]:
for x in range(10):
    if x % 2 == 0:
        continue
    print(x)


1
3
5
7
9

Functions


In [8]:
def concatenate_and_print(astring0, astring1):
    print(astring0 + " " + astring1)
    
concatenate_and_print("Hello", "World")


Hello World

In [11]:
def sum_two_numbers(a, b):
    return a + b

sum_of_numbers = sum_two_numbers(100, 11)

print(sum_of_numbers)


111

Dictionaries

A dictionary is similar to an array, except a dictionary uses keys (instead of just numerical indexes).


In [13]:
phonebook = {}
phonebook["John"] = 1111111
phonebook["Tom"] = 2222222
phonebook["Jane"] = 3333333
print(phonebook)


{'John': 1111111, 'Tom': 2222222, 'Jane': 3333333}

In [14]:
del phonebook["John"]
print(phonebook)


{'Tom': 2222222, 'Jane': 3333333}

In [ ]: