Changes

Jump to navigation Jump to search

Workshop: Introduction to programming (with Python)

8,210 bytes added, 19:00, 7 November 2019
update workshop checklist to conform to standard pedagogy.
{{Workshop header}}
 
===Python===
Some Beginner Questions:
 
*What do you know about Python?
*Do you have any previous experience with Python or other programming languages?
 
 
Python Basics:
 
*Python is a flexible, high-level, procedural scripting language.
*It offers support for object-oriented programming and integrating libraries.
*It's super widely adopted!
 
<br />
 
==Welcome to Introduction to Programming!==
===Setting up your work station===
#'''Download Python -''' You can download it [https://www.python.org/downloads/ here]
#'''Check that your installation was successful -''' We will do this by checking the version of python we just downloaded. We can do this by opening up our command prompt and simply typing "python --version". If you did everything right you should see a message that looks something like this: "Python 3.7.3"
#'''Let's test our distribution''' - Let's get our first introduction into Python programming by making a hello world file.
==Basic Hello World Program==
A hello world program is the most basic program you can write to test that your distribution is working smoothly. [[File:Hello world example.png|thumb|The print statement will simply print out "Hello world!" to the console when ran.]]A hello world program is the most basic program you can write to test that your distribution is working smoothly.
#'''Open a text editor''' - This is where we will be writing all of our code. There are many different editors you can use, so feel free to choose the one you are most comfortable with. The only requirement is that the text editor should be able to product plain text files. Windows users already have Notepad installed. Mac users have TextEdit (other text editors include TextWrangler, Atom, and much more).
#'''Write your code''' - To make this program as simple straightforward as possible we will simply write a print statement. After writing your print statement save the file to your Desktop (or whatever other directory you want) as "hello'''.py'''". All python files need to have the extension .py#'''Execute the code''' - Now is the fun part, running the code! Open up the command prompt (Terminal for Mac Users, Powershell for Windows). Navigate to the directory where you saved the file (ex: cd Desktop). Now execute your python code by typing "python [filename]"[[File:Hello World Executed.png|thumb|Execute the code!]]<br />
==Interactive Python==
According to [[wikibooks:Python_Programming/Interactive_mode|wikipedia]], "Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole". Essentially what this means is Interactive Python is good for quick testing and debugging in the command line. Enter it simply by typing "python" and then hit enter.
==Variables==
Now that we understand the basic workflow of python (create code in text editor → execute in command prompt), we can start discussing the different functions and capabilities of Python. We can start this discussion with variables. You can think of variables as the objects that store information for our program. A variable has two basic parts; '''A name''' (which we will use to refer to the variable) and '''A value''' (the info we care about). Besides those two parts, variables can hold different types of information.
== =='''Types Of Variables '''====Now that we understand the basic workflow #Strings - A sequence of characters (ex: "Python is fun!")#Integers - Whole numbers (ex: 3, 10, 999)#Floats - Numbers w/ a decimal (ex: 1.0, 3.14, 7.77)#Boolean - True or False#Lists - A sequential list of python other variables (create code in text editor → execute in command promptfloats, integers, strings, more lists, or a mix)(ex: ['cat', 'dog', 999, 3.14, we variable1]) ===='''Defining Variables'''====One of the great features of Python is that the built in compiler can start discussing the different functions intelligently figure out what type of variable your specified variables should be and capabilities takes care of this distinction '''automatically'''. This means defining variables is easier in Pythonthan some other languages you may be familiar with. We define a variable by writing its name, followed by an equal sign, followed by the value of the variable (ex: pi=3.14, name="Dylan", eq="3+4"). We can start also define variables without setting the values immediately. To do this discussion we need to tell the compiler what type of variable we need (since it can't figure it out automatically) (ex: int pi, str myName)  Important Note: The standard naming convention of variables follows: The first word is always all lowercase then the proceeding words begin with variablesan uppercase letter (ex: myVariable, reallyAwesomeInteger). You don't need to follow this convention, but it is worth knowing.  <br />===='''Updating Variables'''====To update a variable (change it's value later on in the code) we simply need to redefine it's value. You can think do this by: variableName = [new value] <br /> ===='''Casting Variables'''====When we get into more complex implementations our variable type will become very important. Ask yourself 'what is the difference between these two codes?' #float sum = 1.5 + 3#int sum = 1.5 + 3 Answer: 1.5 + 3 = 4.5 but 4.5 is a float value. So for code #1 the answer is 4.5, but the "sum" variable in code #2 is an integer so the answer will be rounded down to 4. It because of variables cases like these that sometimes we implement a technique known as casting. Casting simply means converting the objects that store type of information for our programa variable holds. With casting we can turn an int to a float, float to an int, str to an int, etc. We cast by writing the variable type we want ("float", "int", "str", etc.) followed by the variable/value we want to cast enclosed by parenthesis.  Examples: *float(3) → 3.0*int(2.9999) → 2*int("1964") → 1964  '''Lists''' In Python a list is indicated by square brackets and commas. A Define a list like any other variable has two basic parts; , except enclose all the list elements in square brackets and separate them by commas. '''For example: myList = [var1,var2,var3].'''A The elements of a given list can be recalled by typing the nameof the list followed with the index of the item enclosed in square brackets. '''For example: myListLists[0] ⟶ var1.''' Lists can be modified during runtime with methods such as these: *myList'''.append('''x''')''' - Adds a new element (which we will use to refer x) to the variableend of the list*myList'''.remove('''x''')''' - Removes the first item with the specified value (x)*myList'''.index('''x''') and '''A - Returns the index of the first element with the specified value(x)*myList''' .insert('''x''')''' - Adds an element at the info we care aboutspecified position (x)*myList'''. Besides those two parts, variables can hold different types of informationclear()''' - Removes all the elements from the list (We will discuss what methods are in a later section.)
<br />
==Basic Operators=='''Types Of VariablesArithmetic Operators:'''
# Strings *Addition ('''+''') - A sequence of characters Adds values*Subtraction (ex: "Python is fun!"'''-''')- Substracts values# Integers *Division ('''/''') - Whole numbers Divides values*Modulus (ex: 3, 10, 999'''%''')- Divides values and returns the remainder# Floats - Numbers w/ a decimal *Multiplication (ex: 1.0, 3.14, 7.77'''*''')- Multiplies values# Lists - An sequential list of other variables *Exponent (floats, integers, strings, more lists, or a mix'''**''') - Performs an exponent*Equal (ex: ['cat', 'dog=''', 999, 3.14, variable1])- Sets a variable equal to a value
'''Defining VariablesComparison Operators:'''
One of the great features of Python is that the built in compiler can intelligently figure out what type of variable your specified variables should be and takes care of this distinction *Is equal? ('''automatically=='''. This means defining ) - Checks if two variables is easier in Python than some other languages you may be familiar with. We define a variable by writing its name, followed by have an equivalent value*Is not equal sign, followed by the value of the variable (ex: pi'''!=3.14''') - Checks if two variables have different values*('''>''', name'''<''') - Greater than and lesser than*('''>="Dylan"''', eq'''<="3+4"'''). We can also define - Greater than or equal to and lesser than and equal to*'''IS''' - Checks if two variables without setting are the values immediately. To do this we need to tell exact same (share the compiler what type of variable we need (since it can't figure it out automatically) (ex: int pi, str myNamesame memory location)
Important Note'''Logical Operators: The standard naming convention of variables follows: The first word is always all lowercase then the proceeding words begin with an uppercase letter (ex: myVariable, reallyAwesomeInteger). You don't need to follow this convention, but it is worth knowing. ''
*'''AND''' or '''&''' - If both the statements are true then condition becomes true
*'''OR''' or '''|''' - If any of the statements are true then condition becomes true
*'''NOT''' - Used to reverse the logical state
*'''IN''' - Checks if an element exists inside of a sequence (or list)
Updating Variables<br />==Methods==The next major thing to learn about Python is methods. Methods are functions that act upon objects and variables in your code. You can use methods to obtain information about variables/objects or update their values. And the syntax of a method goes as follows:[[File:Example of Append.png|thumb|An example of a very common method, append, which adds elements to the end of a list. ]][name of object/variable]'''.'''[method]'''('''value''')'''
You can learn about all the different methods for your variables and objects by exploring the documentation of python (or which ever library you are using).
Casting Variables
Here are some methods you can use on different variables in Python:
== '''The first step''' is to download Python*String - ==If you haven’t yet got pythoncapitalize(), lower(), upper(), the latest official installation packages can be found here:find()http://python.org/download*Int/Float - abs(), long(), pow(), round()Python 3 is preferable*List - append(), count(), pop(), sort(), being the newest version out!reverse()
'''The second step''' is to understand the different things we can do with it!<br />
Ok, so python ==If Statements==[[File:If statement example.png|thumb|300x300px|Example if statement]]The if statement is this thing called a programming languagethe next key concept to learn. It takes text that you’ve written (usually referred If statements allow our programs to as make decisions at run time. This means we can run certain code)if a requirement is fulfilled, turns it into instructions for your computerand if we want, and runs those instructions. We’ll be learning how to write run different code to do cool and useful stuffif the requirement is not met. No longer will you be bound to use others’ programs to do things with your computer - you More simply we can make your own!say, "If this, then that".
We Each 'requirement' is a statement that must evaluate to true or false. These statements can take many different forms and rely on the basic operators we learned earlier. So we can use Python as ask if a calculatorvariable is greater than, very advanced calculatorless than, build softwaresequal to, games, and analyze data!etc. a value (if (variable==0)). We can write equations (if (a**2 + b**2 == c**2)) or even use logical operators (if ((player1 OR player2) NOT IN list)).
We will start with It is important to remember the most simple concept- variable!syntax of these statements. Each statement should be enclosed in parentheses and followed by a colon. The code block that you want to run should occupy the line directly below the statement and be indented.
We name a variable and stick Okay, now we know how to it a number, a word, a list etcrun code if our statement is true. Now how do we do tell the program what to do if the statement is false? What if we have multiple criteria to check? This way we is where else and elif statements come into play. Multiple elif statements can call it in be placed directly under the futureif statement.example for They allow you to write additional statements that will be evaluated only if the if statement isn't fulfilled. The else statement goes at the end of your if statement (and elif statements if you have them). Simply put, the else statement will run a variable is a=6code block only if the elif and if statements aren't fulfilled.<br />
If we want to print the variable we can do - print(a)and we will get 6.<br />
==Loops==One of the most important concepts in procedural programming is the loop. Like the name suggests, a loop simply iterates through some selected lines of code a certain amount of times. In addition we can use python as Python there are a calculator-just type 6+6 and run it and few different types of loops you will get 12.can choose from, they are:
#'''While Loop''' - Like the name suggests, a while loop repeats a block of code while a certain expression is true. This kind of loop is useful when we don't know how many times a loop will actually execute at runtime. The While Loop is composed of two parts; the loop statement and the code block to repeat (indented). The syntax looks like this:[[File:While Loop Example.png|thumb|An example of a while loop]]<code>while (statement):</code>'''''*code to repeat*'''''<br />The while loop will loop over the code block until the statement in parentheses equates to false. The statement can be an algebraic equation or variable. (ex: (n+1)/4 == 1) <br />[[File:Example For loop.png|thumb|2 examples of for loops that yield the same result. ]]
#'''For Loop''' - This loop will run once for each element in a list. This kind of loop is useful when iterating over loops and arrays or when we know exactly how many times the code block should run. There are two main ways to use the for loop.
##To iterate over a list - Will run the code block once for each element in a list. You can reference the element data during each iteration by putting an element name after "for". Example of this syntax can be seen below: '''for''' element '''in''' list''':''' '''''*code to repeat*''''' <br />
##To iterate a certain number of times - Use Python's range function to repeat the code block a certain number of times. The syntax for range is: range (start, stop[, step]). Just like in the other type of for loop, you can reference each element of the range function but naming it. The syntax for this for loop goes: '''for ('''element '''in range('''start, stop[, step]''')):''' '''''*code to repeat*''''' <br />
#'''Nested Loops''' - Loops can be nested inside of each other! For each iteration of the outer loop, the entire contents of the loop will be ran to completion (including other nested loops).
#'''Breaks and Continues''' - "Break" and "continue" are statements which can be placed inside of a loop to modify the loop for special cases. Break is used to break out of (or exit) a loop. Continue is used to stop the current iteration of the loop and start again from the beginning.
Types of inputs are integers, floats, string, and list (those are the basic ones that we will use)-
integer is a whole number-> int(), 6, 7[[File:Break Flowchart.jpg|frameless]][[File:Continue Flow Chart.jpg|frameless]]
float is not a whole number-<br /> 6.25, 7.3333
string is ==Magic Conch Demo==[[File:Magic Conch Logic Flowchart.png|thumb|Flowchart logic of the Magic Conch Demo]]Together we will build your first real program, a word or a phrase[https://www.youtube.com/watch?v=H-IUE0idp7k magic conch shell] demo (Magic 8- Ball). This project will combine all of the written part of something-> 'My name is', '6', (information we use the tags to help Python recognize it)just learned.
list is a list The picture to the right outlines the basic logic of integers, floats or strings-> [1,2,3,4,5], ['1','2','3','4','5']our program.
The link to the example code is [https://pastebin.com/Tm5HLTzV here].
Now that we are a bit more familiar lets see how we can use ==Other Educational Resources for Python to solve Problems!!!==
We will go to project Euler*The Official Python Documentation - https://projecteulerdocs.python.net or httporg/3/*Tutorials - https://rosalindthepythonguru.infocom*Challenging Math/problemsComputational Problems - https:/locations/projecteuler.net
The first one is more <br />==Workshop checklist=====Learning Objectives===By the end of solving math problems with Python (or any other software) and the latter is solving real life Bioinformatics problems!!this Workshop, you should:
lets do together #be able to explain the first problem purpose of Project Euler!programming languages.#understand the difference between a script and the interactive shell.#know the basic functionality of programming languages: sequencing, selecting, and iterating.#have a basic understanding of computational thinking.
===Measurable Outcomes===
By the end of this Workshop, you should be able to:
Another great source you can #run Python scripts on your system#use in order to learn the basics interactive shell on your system.#utilize the basic parts of Python is-httpsa program://thepythonguruvariables, objects, and functions.com. This website provides pictures #code and explanations on the different structures we have in Python. You can also find there some more advanced programing tutorialstest a program which accomplishes a small task.

Navigation menu