A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code.
The #
character is used to start a comment and it continues until the end of the line.
# Comment on a single lineuser = "JDoe" # Comment after code
Python supports different types of arithmetic operations that can be performed on literal numbers, variables, or some combination. The primary arithmetic operators are:
+
for addition-
for subtraction*
for multiplication/
for division%
for modulus (returns the remainder)**
for exponentiation# Arithmetic operationsresult = 10 + 30result = 40 - 10result = 50 * 5result = 16 / 4result = 25 % 2result = 5 ** 3
+=
The plus-equals operator +=
provides a convenient way to add a value to an existing variable and assign the new value back to the same variable. In the case where the variable and the value are strings, this operator performs string concatenation instead of addition.
The operation is performed in-place, meaning that any other variable which points to the variable being updated will also be updated.
# Plus-Equal Operatorcounter = 0counter += 10# This is equivalent tocounter = 0counter = counter + 10# The operator will also perform string concatenationmessage = "Part 1 of message "message += "Part 2 of message"
A variable is used to store data that will be used by the program. This data can be a number, a string, a Boolean, a list or some other data type. Every variable has a name which can consist of letters, numbers, and the underscore character _
.
The equal sign =
is used to assign a value to a variable. After the initial assignment is made, the value of a variable can be updated to new values as needed.
# These are all valid variable names and assignmentuser_name = "codey"user_id = 100verified = False# A variable's value can be changed after assignmentpoints = 100points = 120
%
A modulo calculation returns the remainder of a division between the first and second number. For example:
4 % 2
would result in the value 0, because 4 is evenly divisible by 2 leaving no remainder.7 % 3
would return 1, because 7 is not evenly divisible by 3, leaving a remainder of 1.# Modulo operationszero = 8 % 4nonzero = 12 % 5
An integer is a number that can be written without a fractional part (no decimal). An integer can be a positive number, a negative number or the number 0 so long as there is no decimal portion.
The number 0
represents an integer value but the same number written as 0.0
would represent a floating point number.
# Example integer numberschairs = 4tables = 1broken_chairs = -2sofas = 0# Non-integer numberslights = 2.5left_overs = 0.0
Python supports the joining (concatenation) of strings together using the +
operator. The +
operator is also used for mathematical addition operations. If the parameters passed to the +
operator are strings, then concatenation will be performed. If the parameter passed to +
have different types, then Python will report an error condition. Multiple variables or literal strings can be joined together using the +
operator.
# String concatenationfirst = "Hello "second = "World"result = first + secondlong_result = first + second + "!"
The Python interpreter will report errors present in your code. For most error cases, the interpreter will display the line of code where the error was detected and place a caret character ^
under the portion of the code where the error was detected.
if False ISNOTEQUAL True:^SyntaxError: invalid syntax
A ZeroDivisionError is reported by the Python interpreter when it detects a division operation is being performed and the denominator (bottom number) is 0. In mathematics, dividing a number by zero has no defined value, so Python treats this as an error condition and will report a ZeroDivisionError and display the line of code where the division occurred. This can also happen if a variable is used as the denominator and its value has been set to or changed to 0.
numerator = 100denominator = 0bad_results = numerator / denominatorZeroDivisionError: division by zero
A string is a sequence of characters (letters, numbers, whitespace or punctuation) enclosed by quotation marks. It can be enclosed using either the double quotation mark "
or the single quotation mark '
.
If a string has to be broken into multiple lines, the backslash character \
can be used to indicate that the string continues on the next line.
user = "User Full Name"game = 'Monopoly'longer = "This string is broken up \over multiple lines"
A SyntaxError
is reported by the Python interpreter when some portion of the code is incorrect. This can include misspelled keywords, missing or too many brackets or parentheses, incorrect operators, missing or too many quotation marks, or other conditions.
age = 7 + 5 = 4File "<stdin>", line 1SyntaxError: can't assign to operator
A NameError is reported by the Python interpreter when it detects a variable that is unknown. This can occur when a variable is used before it has been assigned a value or if a variable name is spelled differently than the point at which it was defined. The Python interpreter will display the line of code where the NameError was detected and indicate which name it found that was not defined.
misspelled_variable_nameNameError: name 'misspelled_variable_name' is not defined
Python variables can be assigned different types of data. One supported data type is the floating point number. A floating point number is a value that contains a decimal portion. It can be used to represent numbers that have fractional quantities. For example, a = 3/5
can not be represented as an integer, so the variable a
is assigned a floating point value of 0.6
.
# Floating point numberspi = 3.14159meal_cost = 12.99tip_percent = 0.20
print()
FunctionThe print()
function is used to output text, numbers, or other printable information to the console.
It takes one or more arguments and will output each of the arguments to the console separated by a space. If no arguments are provided, the print()
function will output a blank line.
print("Hello World!")print(100)pi = 3.14159print(pi)
In C#, a method can take inputs via parameters. Parameters are variables that can be used within the method body. When a method is called, the actual values passed to the method are called arguments.
// IntroduceSelf takes two parameters, name and agestatic void IntroduceSelf(string name, int age){// name and age are used within the method bodyConsole.WriteLine($"Hi, my name is {name}, and I am {age} years old.");}static void Main(string[] args){// "Astrid" and 28 are passed as arguments to the method call// and correlate to the name and age parameters respectivelyIntroduceSelf("Astrid", 28);// Prints "Hi, my name is Astrid, and I am 28 years old."}
In C#, the return
statement can be used to return a value from a method back to the method’s caller.
When return
is invoked, the current method terminates and control is returned to where the method was originally called. The value that is returned by the method must match the method’s return type, which is specified in the method declaration.
static int ReturnAValue(int x){// We return the result of computing x * 10 back to the caller.// Notice how we are returning an int, which matches the method's return type.return x * 10;}static void Main(){// We can use the returned value any way we want, such as storing it in a variable.int num = ReturnAValue(5);// Prints 50 to the console.Console.WriteLine(num);}
In C#, a method is a reusable set of instructions that performs a specific task. Methods can be passed one or more values as inputs and can output one or more values at the end of their execution.
A method is called by using the method name followed by a set of parentheses ()
. Any argument values should be included between the parentheses, separated by commas.
// Console.WriteLine is a method, which we called using parentheses// its string argument, "Hello World!" in this case, gets printed to the console// and the argument is passed between the parenthesesConsole.WriteLine("Hello World!");
Main()
methodIn C#, the Main()
method is the application’s entry point. When the application is run, execution begins at the start of the Main()
method.
The dplyr package provides functions that perform data manipulation operations oriented to explore and manipulate datasets. At the most basic level, the package functions refers to data manipulation “verbs” such as select, filter, mutate, arrange, summarize among others that allow to chain multiple steps in a few lines of code. The dplyr package is suitable to work with a single dataset as well as to achieve complex results in large datasets.
The read_csv()
and write_csv()
functions belong to the tidyverse package and perform smart reading and writing operations of files in R. The read_csv()
function reads a file and converts it to a better format of a data frame called a tibble. The first argument of the read_csv()
is the file to be read. Tibbles in R can be exported to csv files using the write_csv()
function. The first argument of write_csv()
is the tibble to be exported.
The filter() function can subset rows of a data frame based on logical operations of certain columns. The condition of the filter should be explicity passed as a parameter of the function with the following syntax: name of the column, operator(<,==,>,!=) and value. On the other hand is possible to chain conditions within a column or on different columns using logical operators such as boolean operators(&,|,!).
A data frame is an R object that store data in two dimensions represented by columns and rows. The columns are the different variables of the dataframe and the rows are the observations of each variable. Each row of the dataframe represent a unique set of observations. This object is a useful data structure to store data with different types in columns and perform analysis around them.
The select() function of dplyr allows users to select all columns of the data frame except for the specified columns. To exclude columns, add the -
operator before the name of the column or columns when passing them as an arguments to select(). This will return a new data frame with all columns except ones preceded by a -
operator. For example: select(-genre, -spotify_monthly_listeners, -year_founded)
.
The rename()
function of dplyr package can be used to change the column names of a data frame. It has a simple syntax where it is necessary to pass the new name followed by the =
operator and the old name of the column. On the other hand to rename multiple columns based on logical criteria, the rename()
function has variants such as rename_if()
, rename_at()
and rename_all()
.
The filter()
function of the dplyr package allows users to select a subset of rows in a data frame that match with certain conditions that are passed as arguments. The first argument of the function is the data frame and the following arguments are the conditional expressions that serve as the filter()
criteria. For example: filter(artists, genre == 'Rock', spotify_monthly_listeners > 20000000)
.
Data frames in R can be inspected using head()
and summary()
. The head()
function accepts an integer argument which determines the number of rows of the data frame that you can see. The default value of the head()
function is 6. The summary()
returns summary statistics such as min, max, mean, and three quartiles.
The arrange()
function of the dplyr package orders the rows of a data frame based on the values of a column or a set of columns that are passed as parameters. The resulting order of the data frame can be in ascending or descending order. By default arrange()
orders the dataframe in ascending order, but it is possible to change this and order the data frame in descending order using the desc()
parameter over the column.
The mutate()
function from dplyr package adds new columns to an existing data frame based on a transformation of an existing column, while maintaining all the other columns. The function receives the data frame as the first parameter, and subsequently specify the new column name followed by the =
operator and a transformation function. After the first variable parameter, further parameters can be added to mutate more variables at the same time.
mutate(heights, cm = inches * 0.39)
CSV (Comma-separated values) files represent plain text in the form of a spreadsheet that use comma to separate individual values. This type of file is easy to manage and compatible with many different platforms. This file can be imported to a database or to an Integrated Development Environment (IDE) to work with its content.
The pipe %>%
can be used to input a value or an object into the first argument of a function. Instead of passing the argument into the function seperately, it is possible to write the value or object and then use the pipe to convert it as the function argument in the same line. This can be used with the functions select() and filter() that contain a data frame as the first argument.
In the example, the weather data frame is piped into the select function that would select the first two columns of the weather data frame.
weather %>% select(1:2)