Skip to content

Introductory Guide Part 2 — Introduction to Python (CrashCourse)

Abailey291 edited this page Oct 5, 2020 · 32 revisions

Chapter 2: What is 'Python'? How do I use it?

Python is a computer language that is HIGHLY useful both in computer science and computation neuroscience. The following will provide an introduction to some of the basics of Python.

Please be free to use this guide as a working model; a kind of book that CAN and SHOULD be updated as time goes on and more details are brought to the table. Also note that while there are several parts to this section, like the chapters of a book, you can scroll to whichever section YOU NEED (yes, you!) to be able to brush up on a basic concept as you code (or debug) your way through computer code.

Part. 1: Hello World

With that, let's begin. Say that you want to print text, or in computing language, a script.

To print a script, write and control enter: print(“Hello World”)

The main idea of Python is that it is a language. Hence, one must know the basics in order to use the coding programs! The more code there is, the more complex the task.

Part 2: How to write a basic program

To draw a shape:
print(“ |”)

print(“ /|”)

NOTE: The computer executes each code in order. Hence, must be careful!

Part 3: Variables

In computer science lingo, a variable is a container to store information (either a script or a number). Just as y = mx +by + c reflects more than letters, variables here also carry a greater meaning (only now can be words or numbers, or EVEN BRAIN VOXELS!!!!)

Using a container (variable) makes it much easier to store information and manage them.

To apply the concept of a variable, let’s say that we have a text. Running it gives us:

i.e. print(“To be or not to be, ”)

print(“that is the question.”)

print(“To die, to sleep, no more...”)

print(“aye, there's the rub.”)

But say that one wanted to play a game of MadLibs where they wanted to change a word in the story (e.g., ‘be’). One could manually always change the word... or, one could change the word ‘be’ to a variable; doing so makes the task faster and more precise.

To do so, let's define the variables character_word and second_word

character_word (underscore is preferred in python for variable names) = “be” second_word = “sleep”

We can now replace the variable inside of the statement. How?

print(“To ” + character_word + “or not to ” + character_word + “, ”)

There you have it! So we have the text + the value of our variable that can be directly edited; altogether making our game of MadLibs possible. Notice the small spacings and the quotes of the comma, however, to ensure that the script can be fully defined.

If you need to store different information after, just change the value inside of the variable.

i.e.

character_word = “be”

print(“To ” + character_word + “or not to ” + character_word + “, ”)

character_word = “cry”

print(“To ” + character_word + “or not to ” + character_word + “, ”)

Part 4: NUMB3RS

So far, we have been working with strings; this is simply plain text.

Another form = numbers. To store numbers in a variable, you don’t need quotation marks. Can use whole or decimal numbers.

**ONE VERY IMPORTANT CONCEPT IS THAT OF A BOOLIAN! **

Boolian numbers = 0 or 1.

Namely, TRUE or FALSE information.

i.e.

is_male = TRUE or FALSE

Say that we want to work with strings in Python:

print(“hello world”)

But, say that you wanted to have this on two different lines:

To do so:

print(“hello\nworld”)

To add a backslash:

print(“hello\world”)

To add a specific punctuation mark (i.e. “"), write

print(“hello\”world””)

BUT!!! One of the coolest thing is that we can create a string variable:

Phrase = “I can’t get”

print(phrase)

This would give you: “I can’t get”

But we can also add other information through a process known as concatenation = adding details to your script.

i.e.

print (phrase + “ no satisfaction”)

** TADAH! You’re now both a pro at typing strings as well as at typing rock lyrics from the 1960s**.

Part V: Functions

Functions, in a phrase, are amazing.

A function is a code that performs a task for us. For example, a function can be used to modify a string and provide us with information.

The most basic function is used for strings:

  1. To have all strings in lower case:

print(phrase.lower())

  1. Similarly to upper case:

print(Phrase.upper())

  1. To check whether all the strings are upper or lower, use:

print(phrase.isupper())

  1. To do both at once:

print(phrase.upper().isupper())

  1. To figure out the length of the string

print(len(phrase))

  1. To get individual characters in a string, use

print(phrase[0])

NOTE: STRINGS BEGIN AT ZERO in Python.

  1. Another function for the length:

print(phrase.index(PARAMETER)

A parameter, is a value of a function (i.e. “can”).

If NOTHING is there, you get an error response.

  1. Print(phrase.replace(“can’t”, “can”))

**This last function directly replaces one word with another. **

Part 6: WORKING WITH NUMBERS AND FUNCTIONS, using MATH!

One can use decimals and basic arithmetic in Python automatically.

To make more complex mathematical statements, PYTHON WORKS USING BEDMAS RULES (Brackets, Exponents, Division, Multiplication, Addition, Subtraction).

But there are also some interesting tricks:

print (10 % 3)

**This gives the remainder of the division of 3 into 10. **

Can also define a variable. num = 5

To convert into a string,

print(str(num))

**Can also use functions!!! The most common are: **

  1. print(abs(num)). Gives the absolute number.

  2. Print(pow(3,2)) = 3 to the power of 2.

  3. Print(max(4,6)) = tells you the higher number.

  4. Print(min(4,8)) = gives the lowest number.

  5. Print(round(3.7)) = rounds the number.

  6. from math import = Used for more complicated mathematics. (all of these functions are also available by importing numpy, which deals more effectively with multidimensional data)

    • a. print(floor(3.7) = takes the lowest number
    • b. print(ceil(3.7) = takes the highest number
  7. print(sqrt(number)) = This is the square root function

**Part 7: Getting input from users: **

Input(ADD USER PROMPT; information used to access the info) i.e.

“Enter your name: (“")

Can use this as a variable. i.e.

name = input(name)

Such that,

name = input(“Enter your name: “))

age = input(“Enter your age: “))

i.e.

print(“Hello” + name + “! You are ” + age”)

**A cool example: Creating a little function. **

Num1 = input(“Enter a number: “)

Num2 = input(“Enter another number: “)

Result = num1 + num2:

Print(result)

But this doesn’t work. Why? Because Python interprets the above statement as a string.

To get to a whole number, use:

Result = int(num1) + int(num2)

Note here that the int function works for whole numbers.

To use numbers as whole numbers, use the following function:

float(num1) + float(num2)

Here’s a fun example: How do you make a sequence that selects odd numbers from 1 to 10?

Answer:

Begin = int(input("Enter number"))

End = int(input("Enter end number"))

for i in range(Begin, End):

if int(i%2) == 1:

   `` print(i)``

TADAH!!!

One QUARTER WAY MARK! AND QUIZ TIME (not really...)

Say that we now want all prime numbers within this range:

Begin = int(input("Enter number"))

End = int(input("Enter end number"))

for i in range(Begin, End):

``for i > 1:

       for n in range(2, End):

         if (val % n) == 0:

               break

       else:

           print(val)

Another fun example (with MadLibs)

Print(“Roses are red”)

Print(“Violets are blue”)

Print(“I love tapioca pudding”)

Print(“I may or may not be in my late eighties”)

Ok, so so far, we just have a lot of scripts.

Say that we want to switch things up a bit, by defining a few variables:

Adjective = input(“Enter a colour”)

Flower_name = input(“Enter a flower name”)

Noun = input(“Enter a noun”)

Age = input(“Enter a life decade range”)

THEN, we can say:

Print(“Roses are ” + Adjective)

Print(Flower_name + “are blue”)

Print(“I love” + Noun)

Print(“I may or may not be in my late” + Age)

PART 8: THE AWESOME POWER OF LISTS! (We use a lot of these)

Lists are structures that store large amounts of information.

A lot of times, one will be working with large amounts of data. So, one needs to manage it and organize well.

Generally, we create a list and then use it throughout the program.

Creat ae a list is much creating a variable.

i.e.

friends = [“Tom”, “Bill”, “Will”]

Can then access individual items in this.

Can use strings, numbers or Boolians.

To see, can do:

Print(friends)

Can also access via index, but remember: THE INDEX STARTS AT 0.

To access one element in an index, write:

Print(friends[Bill])

or

Print(friends[1])

Note: If you use negatives, it indexes at the end of the list. i.e. print(friends[-1]) = from the back of the list. Position -1 is the first position from the end of the list.

SIDE NOTE

To specify everything beyond a certain point, use the term:

Print(friends[1:])

**THIS IS VERY USEFUL **

It accesses everything PAST position 1 (including 1) in the list.

In our Tom, Bill and Will example, this would mean that we would see Bill and Will (positions 1 and 2, respectively)

Part 9: RANGES in LISTS

To select a range, place another value after the colon.

Say that you wish to change a value however. i.e. Bill to Julia (you want to diversity your friends and Bill's just been a jerk lately).

friends = [“Tom”, “Bill”, “Will”]

friends[1] = Julia

print(friends[1])

This would now provide the name Julia instead of Bill.

Part 10: Lists in Python using functions!

When working with values, lists can be incredibly useful. Hence, a serie sof functions exists for them. So, say we have a list.

friends = [“Venkmann”, “Stantz”, “Zedemore”, “Spengler”]

lucky_numbers = [2, 4, 6, 8]

One cool function is called the append function. It’s used to append two lists together.

i.e.

friends.append(lucky_numbers)

print(friends)

Similarly, we can add details onto a list using the append function.

i.e.,

friends.append(“Louis Tully”)

print(friends)

To add something into the middle of the list, use the insert function:

Friends.insert(1, “John”)

Print(friends)

To remove, use the remove function:

friends.remove(“Venkman”)

Print(friends)

We can also remove all the elements from a list. Use the clear function:

friends.clear()

print (friends)

Another function removes the last element from the list use the pop function:

friends.pop()

To see if something is in a list to see if it's there, use the index function:

friends.index(“Venkman”)

Can also count the number of occurances a number is in a list using the count function:

Print(Friends.count(“INSERT NAME”))

Can also sort the list in alphabetical (strings) or ascending number(num) order using the sort function:

Print(friends.sort())

Can also copy a function by defining another function:

friends_2 = friends.copy()

Part 11: TUPLES AND MORE TUPLES!

Tuples are nothing other than a data structure; a container to store multiple pieces of info. Similar to lsts, but with a few differences.

i.e.

coordinates = (4, 5)

Tuples cannot be changed or modified.

Print(coordinates[0]) = 4

BUT CANNOT CHANGE THE ELEMENTS.

Differences between tuples and lists = one is immutable, one is not. Lists are used more often, but tuples can exist.

i.e.

coordinates = [(4, 5), (6,7), (8,9)]

The above is a group of tuples.

Part 12: Intermediate Functions

Collection of code to perform a task = definition. Helps to organize code more easily.

Say that we wish to have a function that says hello to the user.

i.e. def (the key statement).

def say_hi():

       ``print(“Hello world”)``

MUST BE INDENTED TO WORK!!!!

For the function to work, we need to call it. When one writes “sayhi”, the program functions!

We can also add more information to the function; we do this by adding parameters.

Say that we want the function to know who to say hello to.

To do this:

def say_hi(“name”):

          ``print(“Hello” + name)``

We can even use more parameters:

def say_hi(“name”, “age”):

``print(“Hello” + name + “, you don’t look a day over” + str(age) + “years old”)``

Note: Whenever one needs to add more details, be sure to create more functions.

Part 13: The RETURN Statement

Recall that python functions are a collection of code used for a particular task. To perform the task, we can call a function. Usually, we just call it. But sometimes we want information ack from the function; hence, we want not only an execution of the task, but also a communication of what occurred. This is what return does; it returns information from a function.

Say we want to cube a number.

To create a function to cube a number, we might thing we should write:

Def cube(num):

``num * num * num``

cube(3)

But, if we run it, nothing HAPPENS!!!

In fact, the cube function doesn’t do anything. It doesn’t work even if you write out the function.

To get around this, we need to add a return statement:

Def cube(num):

`Return num*num*num`

Print(cube(3))

Now it works!

Can do this with any number.

**This is the basic idea of the return statement – it’s used to return a value to the caller. **

Now say that we set a result = cube(4). This stores the value that is returned.

Hence, return statement can be useful for getting information from a function.

Note that the print(cube(4)) has 4 as a parameter; the return function gives us **the value of this function. **

CANNOT PUT CODE AFTER THE RETURN STATEMENT. The function ends there.

Part 14 A: IF STATEMENTS/LOOPS

Useful to execute a code when certain conditions are true and to execute another statement when those conditions are not met. Helps us to respond to data.

**If statements are used throughout everyday life; they are conditional situations. **

Say for instance we have the following case from this very iffy poem:

"I am at a restaurant. If I want to eat meat I order steak Otherwise, I order a salad."

This is an if statement, but also provides another situation if the condition is not met.

We can even have a more complicated situation by adding other conditions:

I am at a restaurant. If I want to eat meat I order steak Otherwise, if I want pasta I order penne alfredo Otherwise **I order a salad. **

The idea is that if certain conditions are met (TRUE), one outcome will occur; if other conditions are met, another outcome will occur (think of this as a probability tree).

In Python, if statements can be defined by our friends, the Boolian variables. Remember: True = 1, False = 0.

For instance:

is_male = True

if is_male:

   ``print(“You are male”)``

But! If you change is_male = False, then nothing is printed.

Say that there’s another situation. One can develop a code that works along the lines of something like this:

is_male = True

if is_male:

`print(“You are male”)`

else:

`print(“You are not a male”)`

TADAH! Notice that you can make these situations quite complex.

Part 14 B SIDE TANGENT!!!

  • Now, say we decide to add another variable.

is_tall = True

Here, we learn about the almighty difference between AND and OR and is based on ** the branch of mathematics called LOGIC**:

  1. Or = only one of the criteria is met.

  2. AND = BOTH criteria are met.

For instance:

is_male = True

is_tall = True

if is_male or is_tall:

`print(“You are male or tall or both”)`

else:

`print(“You are neither a male not tall”)`

As you adjust the variables (Boolians) above, we can get different responses.

SPECIAL CASE

But say that we want to add in more conditions. What would one do?

is_male = True

is_tall = True

if is_male or is_tall:

    `print(“You are male or tall or both”)`

elif (stands for else if) is_male and not(is_tall):

`print(“You are a short male”)`

elift is not(is_male) and is_tall:

print(“You are a tall non-male”)

else:

      `print(“You are neither a male not tall”)`

This now covers all situations!

And you can now have fun adjusting the two conditions avbive to obtain different responses.

Part 15: Even MORE complex situations using Boolians!

These are for simple Boolians, but we can also do this using something known as comparison operators.

This is useful to compare numbers or strings.

Say we wish to create a function that takes the parameters we gave, to determine what the largest number is.

Def max_num (num_1, num_2, num_3):

`If num_1 >= num_1 and num_1 >= num_3:`

          `return (num_1)`

     `elif num_2 >= num_1 and num_2 >= num_3:`

return (num_2)

        `else`:

               `return(num_3)`

print(max_num(3, 4, 5))

This would give us 5 as a response. These comparisons are useful for if statements using numbers.

But can also work for strings or Boolians.

Notice the term >= is a comparison operator, used to define our comparison.

Other useful operators:

  1. == means equivalent
  2. != means not equal
  3. Means greater than

  4. < less than
  5. = greater than or equal to

  6. <= less than or equal to

These are VERY useful!

Part 16: Building a Calculator Using If statements and Operators

Say we want to create a calculator that can add, multiply, divide and subtract.

num1 = input(“Enter first number”)

Whatever the user enters, we want to convert it into a number. Usually, this is a string. But here, we want it to be a number.

To convert this into a number, we use an operator.

num1 = float(input(“Enter first number: ”))

op = input(“Enter operator: ”))

num1 = float(input(“Enter second number: ”))

Now, let's think about the operator...well, one way to do this is by typing:

If op == “+”:

`Print(num1 + num2)`

elif op == “-”:

`Print(num1 - num2)`

elif op == “/”:

`Print(num1 / num2)`

elif op == “*”:

`Print(num1 * num2)`

else: print(“Invalid operator”)

Then run!

There you have it, a mini-calculator.

Part 17: Using Dictionaries in Python

Dictionaries in Python: these are special storage places where one can store key-value pairs. One can then refer to information by its key.

Say that we want to convert a three digit month name into a full month name.

monthConversion = { “Jan”: “Janurary”,

“Feb”: “February”,

“Mar”: “March”,

“Apr”: “April”,

“May”: “May”,

“Jun”: “June”,

“Jul”: “July”,

“Aug”: “August”,

“Sep”: “September”,

“Oct”: “October”,

“Nov”: “November”,

“Dec”: “December”,

}

These are each keys with values. Now, can access via:

Print(monthConversion([“Nov”]))

Or:

print(monthConversion.get(“Dec”))

  • Keys can also be NUMBERS! Just use numbers instead of strings for the key.

**Part 18: WHILE-Loops **

THIS IS ONE OF THE MOST IMPORTANT PARTS THAT IS REQUIRED FOR NEUROIMAGING ANALYSES (it's just incredibly useful)

A 'While' loop is a code that repeats itself. It is useful as it allows one to repeat a code multiple times.

Can specify a few lines of code until a situation is false. The basic example is as follows:

i = 1

while i <= 10:

`print(i)`

i +=1 (means add 1 to i)

print(“loop finished”)

NOTICE: 'while' loops WILL repeat themselves until the condition is fully matched (namely, until the condition is not true); the condition is examined and performed until the value of i = 10.

Part 18: While Loops in Practice

Say we want to create a guessing game. We have a secret word that the user wants to interact with until he/she can guess the word. We want the user to guess the word until they get it right.

Secret_word = “cat”

Guess = “”

Guess_count = 0

Guess_limit = 3

Out_of_guesses = False

While Guess != Secret_word and not(out_of_guesses):

`If Guess_count < Guess_limit:`

	`Guess = input(“Enter guess: “)`

	`Guess_count +=1`

`Else: `

	`Out_of_guesses = True`

If out_of_guesses:

`Print(“Game over”)`

Else:

Print(“You win!”)

Say that we want to set a limit to the number of trials; that's where the guess limit comes into the code.

And there you have it, a fun way to integrate all that we’ve just learned about while loops, with variables and if statements!

Notice however the logic of the game, you have your information (the variables) from which you create a statement that will be looped (the game).

**But we use if /else statements to limit both the number of trials and the outcome message that the participant obtains. **

Part 19: FOR LOOPS

THESE ARE AS IMPORTANT AS WHILE LOOPS!

FOR loops are special types of loops. They allow us to loop over different collection in Python for discrete variables (i.e. letters or series of numbers).

for variable in “longer word”:

`print(variable)`

This gives a different letter on each trial.

For loops can also use arrays:

friends = [“Monica”, “Phoebe”, “Rachel”]

for friend in friends:

`print(friend)`

This loops through each value in the array.

**Can also loop through a series of numbers. **

for index in range(10):

`print(index)`

OR

for index in range(3, 10):

`print(index)`

Ranges are also helpful for arrays:

friends = [“Monica”, “Phoebe”, “Rachel”]

For index in range(len(friends)):

`print(friends[index])`

**This provides a range for all the values in the array. **

**For loops can also loop through strings. **

Say we have a range up to 5:

for index in range(5):

`if index == 0:`

	`print(“first iteration”)`

`else:`

	`print(“Not the first iteration”)`

Part 20: The exponent function

**This function, as its name suggests, takes a number and raises it to a power. **

Normally in Python, we could simply write:

Print(x**y)

This is xy.

But there’s aother way that one could calculate exponents. And, it uses a for loop.

Def raise_to_power (base_num, exp_num):

`result (this is a variable) = 1`

`for index in range(exp_num):`

	`result = result * base_num`

return result

print(raise_to_power (base_num, exp_num))

**And there you have it! **

*NOTE: You’re repeating the same equation exp_number of times; the information however is looped in the result variable.

_Part 21: Nested Loops and 2D lists: _

**Say that we want to have a list: **

Num_grid = [ 1, 2, 3, 4 ]

But another thing that can be done is to make all the elements inside the list a list!

` num_grid = [`
 `[1, 2, 3], `
 `[4, 5, 6], `
 `[7, 8, 9], `
 `[0]`

]

*** This has four rows and three columns**.

Say that you want to access one of the arrays.

Print(num_grid[0][0]) = 1 (in this case)

This gives the information for [row][column]

But!!!! we can even take this idea a bit further, by creating a nested-for loop (a for loop inside of a for loop).

This can be used to print out all the elements inside of this array.

For row in num_grid:

`Print (row)`

Gives each row. BUT! To give each piece, we need another piece of information.

For row in num_grid:

`For col in row:`

	`Print (col)`

This prints out each element in an array. This is how you obtain a 2D list.

**Part 22: Using what we know using a translation **

Say that we want to devise a translator that converts all vowels into the letter g.

hi => hg

How do we do this?

Well, let’s first create a translator function.

Def translate (phrase):

translation = “”:

for letter in phrase:

	`if letter in “AEIOUaeiou”:`

		`translation = translation + “g”`

	`else:`

		`translation = translation + letter`

`return translation`

print(translate(input(“Enter a phrase: ”)))

**And that’s how the for loop can be combined with an if statement. **

To keep the code simpler, we can also write:

Def translate (phrase):

translation = “”:

for letter in phrase:

	`if letter.lower in “aeiou”:`

		`if letter.isupper: `

                        `translation = translation + “G”`

		`else:`

                          `translation = translation + “g”`

	`else:`

		`translation = translation + letter`

`return translation`

print(translate(input(“Enter a phrase: ”)))

Part 23: How to make comments (VERY IMPORTANT TO REMEMBER WHAT YOU DID, or WHAT YOU WERE TRYING TO DO)

Print(“Comments are fun”)

Say that you just want to have a file for yourself. To do so, place a #.

i.e.

# This is just a side note or THIS IS WHAT THE CODE DOES

To make a comment on multiple lines, just create another comment with a little hashtag.

Comments can also be done with ‘’’.

**But officially, use #. **

Comments can also be helpful for understanding line code. Used to make sure that some codes are removed from the code.

Part 24: How to catch errors in Python (DEBUG)

i.e.,

number = int(input(“Enter a number: “))

print(number)

Say someone only mentions a written case. To handle this, use a "try/except" method.

Say if someone entered a string, we can use:

**Try**:

number = int(input(“Enter a number: “))

print(number)

except:

`print(“Invalid input”)`

Therefore, this handles the error!

We can accept certain errors. And most importantly, we can specify the type of error.

For example:

number = int(input(“Enter a number: “))

print(number)s

except ZeroDivisionError:

print(“Divided by zero”)

except ValueError:

`print(“Invalid input”)`

This can specify what the problem is. Interestingly, you can store the error as a variable.

except ZeroDivisionError as err:

prin(err)

**This will state division by zero. **

Note that the more specific one is about the type of error, the better it is; it facilitates understanding of what occurred.

Part 25: Reading from external files in Python

WE DO NOT REALLY USE THIS ONE

Individuals often want to read files outside of their Python files (i.e. text files, html)

To do so, use the Python read command.

For example, say that you want to read a file in Python.

Open(“NAME OF FILE”, mode of file).

Name of file.close()

*Name of the file is written if the file in the same directory of the Python file one is using otherwise type the relative path, or the absolute path.

Whenever you open a file, you need to close it as well.

Hence, generally, it’s a good idea that whenever you open up a file, you want to make sure that you close it at some point.

Mode include:

a. “r” = read b. “w” = write c. “a” = append d. “r+” = read and write

This open function will open the file. But generally, it’s easier to use this open function if you save it as a variable.

To find out what’s in the file, we can first:

  1. Check that the file is readable:

employee_file = open(“employees.txt”, “r”)

Print(employee_file.readable())

This will give a True or False statement as to the file’s readability.

**Note that this statement would be False if we were given permission to write in it. **

  1. To read all the information on the file, type:

employee_file = open(“employees.txt”, “r”)

Print(employee_file.read())

  1. To read one line, type:

employee_file = open(“employees.txt”, “r”)

Print(employee_file.readline())

employee_file.close()

  1. To read several lines type:

file.readlines()

**This function takes all the lines and places it in a list. **

  1. One can then access each line by their number in the list.

employee_file = open(“employees.txt”, “r”).

Print(employee_file.readlines()[0])

employee_file.close()

_In this case, this shows the first item in the list. _

  1. One can also use the read-lines function using for loop.

employee_file = open(“employees.txt”, “r”)

for employee in employee_file.readlines():

`Print(employee)`

employee_file.close()

Part 26: Writing and appending to files in Python

WE DO NOT REALLY USE THIS ONE

Let's open a file to see what it says.

employee_file = open(“employees.txt”, “r”)

Print(employee_file.read())

employee_file.close()

Say that now we want to add some text onto the file.

**To do this (using in this example the prexisting files of Tom and HR in mode a): **

employee_file = open(“employees.txt”, “a”).

Print(employee_file.write(“Tom - HR”))

employee_file.close()

This adds this information to the original file.

Must be careful; if you append twice, it adds the details to the same line twice.

To add a new line, remember to place: 
(“\nTom – HR”)

BUT! If you change the mode:

employee_file = open(“employees.txt”, “w”)

Print(employee_file.write(“Tom - HR”))

employee_file.close()

**The only bit of information that will be there is Tom – HR. NOTHING ELSE. **

Write (w) can also create a new file. How? Change the extension or name of the file!

employee_file = open(“employees1.txt”, “w”)

Print(employee_file.write(“Tom - HR”))

employee_file.close()

To make the file html:

employee_file = open(“employees1.html”, “w”).

Print(employee_file.write(“<p> This is HTML </p>”))

employee_file.close()

Part 27: Modules in Python

Modules are a Python file we can import into another file in Python.

How do we do this you ask? Go to the top of a new Jupyter notebook file and write:

Import NAME OF FILE

Can then use all the files in that.

print(useful_tools.roll_dice(#))

Hence, importing files from other files saves time from copying and pasting over and over again.

Place to find a mega list of modules = Python Module Index.

These are modules inside of Python that one can already access.

Using modules can seriously save time. There’s a lot of files.

The question is: where are all these modules stored?

Some are stored within (built-in). While others are NOT built in but they are in external libraries.

In addition to looking at these standard modules, there are many other modules that are installed beyond Python. To do so, find a source online!

Part of the fun with computer languages is looking for new formats.

i.e. pip

**Pip is used as a package manager to install different Python modules. **

First: make sure that Pip is installed; go onto your terminal (konsole) and write:

Pip – version

If not, install Pip! Most legitimate Python modules use Pip.

Say that we find Python Docs, which we like. To download, write:

Pip install python-docx

THEN PRESS ENTER.

Tadah!

The new download should now be in site-packages in the external library. In this case, the file is under “docs”.

**To import, write: **

Import docx

And now, you can use it!

To remove, can also use Pip. Go back to the terminal and type:

Pip unistall python.docx

While there are tons of these modules, the quest is now to find which ones are most useful.

Part 28: Classes and Objects in Python

Not all data can be stored as strings, numbers or Boolians. WE can create our own datatypes.

How? Make a new class.

Say that you want to represent a student in Python. Can create a class for a student.

Do so via typing, and then using an initialized function:

class Student:

 `def __init__(self, name, major, GPA, is_on_vacation): `

	`self.name = name`

	`self. major = major`

self. GPA = GPA

	`self. is_on_vacation = is_on_vacation`

This is just a template, however. 
 To then create an example, we create an object on a new page, and write:

From Student (file name) import Student (the class)

Student1 = student(“Tony”, “Arts”, 3.8, False)

print(student1.name OR GPA OR major OR is_on_vacation)

**What's quite cool about this, is that you can create a class to model a real datatype. **

Part 29: Fun example: Building a Multiple Choice Style Quiz

This involves classes, if statements and loops all together.

Here we have our basics:

Question_prompts =

[ “What colour is the sky?\n(a)Green\n(b) Violet\n(c)Red\n(d)Blue\n\n”, “What colour is a banana?\n(a)Grey\n(b) Yellow\n(c)Red\n(d)Blue\n\n”, “What colour is a red car?\n(a)Green\n(b) Yellow\n(c)Red\n(d)Blue\n\n” ]

There are two parts however: The question and the answer.

To store the question and the answer, we need to create a class. On another page, write:

class Question:

`def__init__(self, prompt, answer):`

	`self.prompt = prompt`

	`self.answer = answer`

Then, on the main Python file, write:

From Question import Question

Then, one can write:

`Question =

[ Question(question_prompts[0], “d”),`

`Question(question_prompts[1], “b”),`

`Question(question_prompts[2], “c”),`

]

Def run_test(questions) :

`Score = 0`

`for question in questions:`

answer = input(question.prompt)

if answer == question.answer:

	`score +=1`

print(“You got “ + str(score) + “/” + str(len(questions) + “correct”)

run_test(questions)

Then click enter

Part 30: Class Functions in Python

These are used to adjust our classes using specific designated functions.

Saved on a student file (with info already there):

Class Student:

def __init__(self, name, major, GPA):

	`self.name = name`

	`self. major = major`

self. GPA = GPA

A class function would be:

def on_honor(self):

`if self.GPA >=3.5:`

	`return True`

`else: `

	`return False`

On another file, write:

From student import Student

student1 = Student(“Brian”, “Arts”, 3.4)

student2 = Student(“Julie”, “Science”, 3.9)

print(student1.on_honour())

This gives a result as True or False.

This is just a very basic breakdown of how to use class functions.

Helps the user to think about how they can modify values within an object.

Final Part: Inheritance

Inheritance is where we can define a bunch of attributes/functions inside a class and create another class that can inherit these same attributes. I will make

i.e.

class Swedish_Chef:

def make_chicken(self):

`print(“The chef has made a chicken! HUHUHUHU”)`

def make_salad(self):

`print(“The chef has thrown some salad at you”)`

def make_special_dish(self):

`print(“The chef has made a special dish…Buyer beware…”)`

**On a new file: **

From Chef import Swedish_Chef

myChef = Swedish_Chef()

myChef.make_chicken()

Say that now you want to model a different chef. If a new Chef could do the same as our regular chef and has different (better) dishes.

We could either redo the same steps via copy and paste OR can use inheritance.

To do so, write:

From Chef import Swedish_Chef

Class BetterChef(Chef):

`Def make_newfood(self)” `

	`Print(“The chef makes you a wonderful dish that both reminds you of the flavours of your youth and the gentle aroma of the meals tasted on a Grand Tour of Europe”`

This then allows the following to work just as it did before!

myNewChef = BetterChef()

myNewChef.make_newfood()

NOTE: Because the class is inheriting the values/statements of another class, if you want to override it, this must be done on the file of the new chef. Doing so allows the new data to override the previous statement.

Clone this wiki locally