Python Basics
Zhu, Justin

Python Basics
Sat, Dec 29, 2018


Foundations of Python programming

This post will be about some of the most important syntax components in Python. This should read as a quick review (“cheatsheet”) for some of those things specific to the Python language that I need to refer back to every now and then.

Integers and Floating point numbers

Python is an untyped language, meaning you do not have to define the type of the variable. Integers are numbers without a decimal point and floating point numbers are numbers with a decimal point.

Therefore, typecasting will be pretty important in Python when we are converting between values.

For example,

integer = 7
floatingvalue = float(integer) # prints out 7.0
print(integer / floatingvalue) # prints out 1.0 -- float format takes precedence

Operators

Operators are mathematical expressions that change our integer values and floating-point values.
The operators are just like that in Java and C

ans 1 + 1 - 2 / 2 * 2

# ans = 1 since 1 + 1 - 2 / 2 * 2 = 
# 1 + 1 - (2 / 2) * 2 = 
# 1 + 1 - (1 * 2) = 1 + 1 - 2 = 0

Order of operations is obeyed in Python.

Taking the power of an integer, $a^x$ uses two asterisks:

squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)

Strings

Strings can be represented with single quotes or double quotes. The difference between single quote and double quotes is that using double quotes makes it easy to include apostrophes.

Therefore use double-quotes instead of single quotes for consistency.

Concatenation is adding strings.

helloworld = "hello" + " " + "world"
print(helloworld)

lotsofhellos = "hello" * 10
print(lotsofhellos)

Python uses C-style string formatting to create new, formatted strings. The “%” operator is used to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s” and “%d”.

# This prints out "Hello, Justin!"
name = "Justin"
print("Hello, %s!" % name)
# This prints out "Justin turned 19 years old in 2018."
name = "Justin"
age = 19
year = 2018
print("%s turned %d years old in %d." % (name, age, year))

Any object which is not a string can be formatted using the %s operator as well. The string which returns from the “repr” method of that object is formatted as the string. For example:

# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)

Formatting specifiers

Here are some basic argument specifiers:

%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.[number of digits]f - Floating point numbers with a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

len(string)

Finding the length of a string in Python

string.index()

astring = "Hello world!"
print(astring.index("o")) # prints out 5

string.count()

astring = "Hello world!" 
print(astring.count("l")) # prints out 3

string[start:stop:step]

astring = "Hello world!"
print(astring[3:7]) # prints out "lo w"
print(astring[3:7:1]) # prints out "lo w"

Reversing a string

astring = "Hello world!"
print(astring[::-1]) # prints out "!dlrow olleH"

##string.upper() and string.lower()

astring = "Hello world!"
print(astring.upper()) # prints out "HELLO WORLD!"
print(astring.lower()) # prints out "hello world!"

Assigning variables

Best to do it in one line since concision makes for good code.

a, b, c, e, f = 1, 2, 3, "hello", 4
print(a, b) # (1, 2)
print(a, b, c) # (1, 2, 3)
print(a + b + c) # 6
print(e, f) # ('hello', 4)

We can use the assignment value of None when assigning a new variable.

variable = None
print(variable) # None
variable = 1 # We now assign 1 to "variable"
print(variable) # 1

Lists

Appending, indexing, and deleting variables.

mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

Lists can be joined.

even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)

Lists can also be duplicated with multiplication operator.

print([1,2,3] * 3)

string.split()

One of the most important functions in Python! It converts a string into a list by splitting substrings according to a character.

# Creates a list 
astring = "Hello world!"
afewwords = astring.split() # default is to split based on any whitespace
print(afewwords) # ['Hello', 'world!']
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x) # ['apple', 'banana', 'cherry', 'orange']

We can also split the string into a list with max x items:

txt = "apple#banana#cherry#orange"
x = txt.split("#", 1)
print(x) # ['apple', 'banana#cherry#orange']

Dictionaries

A dictionary is like a list, but contains keys and values instead of indexes. In other words, a hash table.

Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.

# Create a new dictionary using braces
schedule = {}
# Insert new key and value
schedule["Monday"] = "Cardio"
schedule["Tuesday"] = "Lifts"
schedule["Wednesday"] = "Yoga"

print(schedule) # Prints out {'Tuesday': 'Lifts', 'Wednesday': 'Yoga', 'Monday': 'Cardio'}

dictionary.items()

Iterate over key value pairs in a dictionary using dictionary.items().

Unlike that of a list, order of values in a dictionary is not preserved.

for weekday, exercise in schedule.items():
    print("I do %s on %s" % (exercise, weekday))

dictionary.pop()

Remove a key and all the values associated with that key using the pop function

schedule.pop("Tuesday")
print(schedule) # Prints out {'Wednesday': 'Yoga', 'Monday': 'Cardio'}

Conditions

Indentation is key. On vim, indent simply with ‘gg=G’

Conditions are a good way to debug code.

x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

if, elif, else, in, and, or, not, is

name = "Justin"
name2 = "Justin"
conditionone = True
conditiontwo = False
if name in ["Justin", "Aris"]:
    print("Your name is either Justin or Aris.")
if name is name2:
    print("name and name2 are the same instances")
if conditionone and conditiontwo:
    print("Both conditionone and conditiontwo are true")
if conditionone or conditiontwo:
    print("Either conditionone or conditiontwo are true")
elif not conditionone:
    print("Print this if the previous statement was not true and conditionone is not true")
elif not conditiontwo:
    print("Print this if the previous if and subsequent elif statements were not true and conditiontwo is not true")
else:
    print("Print this if all previous if and elif statements are not true")

Loops

# Loop over all the values in an array
primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

range and xrange

Difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator object, which is more efficient because of yielding and generators. Being said, Python 3’s range function behaves like xrange.

Therefore, use xrange over range in Python 2.

# Prints out the numbers 0,1,2,3,4
for x in xrange(5):
    print(x)

# Prints out 3,5,7
for x in xrange(3, 8, 2):
    print(x)

while

# Prints out 0,1,2,3,4

count = 0
while count < 5:
    print(count)
    count += 1  # This is the same as count = count + 1

break and continue

Break is used to exit a for loop or a while loop.

Continue is used to skip the current block, and return to the “for” or “while” statement.

# Prints out 0,1,2,3,4
count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)

loops and else statements

When the loop condition of “for” or “while” statement fails then code part in “else” is executed.

# Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))

If break statement is executed inside for loop then the “else” part is skipped.

# Prints out 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("this is not printed because for loop is terminated because of break but not due to fail in condition")

Functions, Classes, and Objects

Functions return an output with zero or more parameters

def function_name(parameter1, parameter2):
    output = parameter1 + parameter2
    return output

We can call a function with just one line

function_name(1, 1) # returns two

Classes are a template for creating objects.

Objects encapsulate functions and variables into a single entity.

The classic analogy is that classes are blueprints for a house while objects are the houses themselves.

Mind the indentation:

class MyClass:
    variable = "This is a variable inside the class."

    def function(self):
        print("This is a message inside the class.")

Creating an object is very similar to creating a function.

Once we created an object, we can access all of those variables and functions for the class using the dot operator.

myobject = MyClass()

print(myobject.variable) # Prints out "This is a variable inside the class."

myobject.function() # Prints out "This is a message inside the class."