Python
https://www.codecademy.com/courses/python-for-programmers/articles/python-style-guide
Style Guide
Python wants you to write functions and variables in lower_case_with_underscores
It wants you to indent: with 4 spaces per indentation
Inline comments are written # like this
Command line
To run a script in command line you just run:
Program Structure
Hello World
Why does this script to print hello world look like this? Why not just
Why does it look this way?
Putting it in a main() function defines the start of the program.
Putting it in a main() function allows this scipt to be imported and ran inside other scripts.
if __name__ == '__main__': is done to work out if the python file being run (the module) is the main program or not.
When the python file being run is the main program (as opposed to being run from inside another script), then name will equal main.
When the python file is being run from within another file, the name will equal that other files name
So far this seems similar enough to R. The main difference is that indents matter now. Also that your function is defined with a different syntax. No {}s to be seen here.
Input and Output
There is an inbuilt function called input.
The above line will give a space to let you input text
This will let you save the input
The most simple way to output would be to use print
The above one has f at the start to show this is a formatted string literal.
Python calls it's files modules.
Variables
Python uses = rather than <- to define variables
In python you can specify what class you want to store a variable as, by doing something like
Above will store 12 as a string rather than as a number
Data Types
As well as strings, Python also has
int() # To store integers
float() # To store numbers with decimal points
bool() # To store boolean values of TRUE or FALSE
str() # To store strings. Python can use both ' and "
Operators
Arithmetic
To act on numeric variables you can use
+ # to add
- # to subtract
* # to multiply
/ # to divide
** # to raise to the power of (I think R would use ^)
// # a floor division, where you get just the integer (x // y = how many whole y's fit in x)
% # modulo, the leftover of a floor division (how much of x is leftover once all the whole y's are removed)
Assignment
These operators assign or edit a variable
= # set a variable
+= # add to an existing variable
-= # Subtract from existing variable
*= # multiply existing variable
/= # divide existing variable
Comparison
These are testing comparing operators that return either true or false. They seem the same as R
== # Is x = to y?
!= # is x not equal to y?
> # Greater than
>= # Greater than or equal to
< # Less than
<+ # Less than or equal to
Logical
These operators are used to string a few conditions together They also return true or false
x > 1 and y < 2 # Will give TRUE if x is greater than one and y is less than 2
x > 1 or y < 2 # Will give TRUE if either x is greater than one or y is less than 2
not(x > 1 and y < 2) # Will give FALSE if x is greater than one and y is less than 2, it reverses the statement
The equivalent in R would be &,|, and !() I think.
Conditional Statements
if
The format for an if statement is:
So no {} to be seen. But remember the colon and the indent
else
Here note the how you need to indent, and put a colon after else
else if, elif
if result = result_wanted:
print('Success!')
elif: result > result_wanted:
print('Even better!')
else:
print("That's a shame")
Loops
for
A for loop goes over a list or a range
you can nest for loops within nested lists
range()
while
A while loop keeps going whilst the while condition is true
Controlling Loops
Inside a loop you can put:
pass # This skips an item in a list
break # This kills the loop
continue # This seems similar to pass, in that it skips an item. It's different in that it goes onto the next item. (i'm not too sure why that's different tho)
Error Handling
try and except
This allows you to put some code after try, your first code you want to run. And if the code in run fails, you will run the except code
finally
In try and except, if you put a finally, this will run after either of them
try:
print(value)
except:
print('Sorry, you forgot to define value!)
finally:
print('Hope it worked!')
Functions
You create a function like this:
def function_name(function_arguments): # State you are making a function with def,
# Name it in function_name
# Pass the arguments to it inside brackets
function_variable = function_arguments
return function_variable # return is the keyword to exit the function and return what you've stated
You call a function just like in R
In python the arguments in a function are called parameters
So above example, function_arguments is a parameter, so I should have called it function_parameters !
Recursive Functions
Recursion is where a function can call itself
def recursive_function(num):
if num == 1:
return 1
else:
print(num)
return recursive_function(num-1)
A recursive function has a base case (the if bit), and it has the recursive step, the else bit, which calls it's own function!
So what this factorial() is doing, is I think kind of like a while loop. It's got what it will do if it meets the base step criteria. If not it trys again, but minusing 1 from the previous bit
Lambda Functions
You don't have to give a function a name. You can use a lambda function, where you use lambda rather than def
So it still has a name really, but is considered anonymous, cos you haven't used def. The advantage here is that it's a one-liner. Which doesn't seem like much of an advantage The other advantage is you can combine it with other built in functions.
Classes and Objects
This is for object orientated programming. In R you normally use function orientated programming (I think)
Classes
A class is a data type that is used as a blueprint or definition for subsequent objects
Object
An object is an example of a class. It contains everything from the class it comes from.
C
List
A list can exist as:
You can nest lists within lists: