R Function - Print When Not Assigned
Assuming that you still want your function to return the 'x+1' value, you could just wrap it in the invisible function:
fun <- function(x) {
print(x+1)
invisible(x+1)
}
> fun(3)
[1] 4
> a = fun(3)
[1] 4
> a
[1] 4
This will only print it out once, while still retaining the 'x+1' value.
print if not assigned
I think the best you can do is to define a special print method for objects returned by the function:
## Have your function prepend "myClass" to the class of the objects it returns
fun <- function(x) {
class(x) <- c("myClass", class(x))
x
}
## Define a print method for "myClass". It will be dispatched to
## by the last step of the command line parse-eval-print cycle.
print.myClass <- function(obj) {
cat("message\n")
NextMethod(obj)
}
> fun(1:10)
message
[1] 1 2 3 4 5 6 7 8 9 10
attr(,"class")
[1] "myClass"
>
> out <- fun(1:10)
>
Printing a variable in C that was not assigned a value
Yes, p
is the address of c
, which is the same as the address of c[0]
. And yes, in your second example, p
would be equal to 5014.
Why does my code print a value that I have not assigned as yet?
Lines in a Python program can be executed in a different order than their placement in the program. What happens when a line is "executed" may differ from what you expect. Given that, let's look at your program as it is executed, leaving out some of the finer points. You can see what I explain by running the program one line at a time in a debugger (a standalone one or one that is included in your IDE such as Spyder or Visual Studio Code).
Before the execution begins, the code is "compiled" into a version that is easier for the computer to handle. Then execution begins with line 1.
Your line 1 is a def
statement. Executing this line does not execute the function. Instead, the code lines for the function are placed into memory, and the name of function (in your case cheese_and_crackers
) is given to that collection of lines. Then the lines inside the function are skipped and execution continues with the line after the function (in your case, line 6). If you run the debugger you will see that execution jumps from line 1 to line 6.
Line 6 is straightforward: some text is printed to standard output.
Line 7 sees the name cheese_and_crackers
with a left parenthesis following, so Python knows to execute (finally) the function that was previously defined in line 1. Python calculates the arguments 20
and 32
, assigns them to the names cheese_count
and box_of_crackers
, notes that those names are for the inside of the function, does some other things I'll skip over, then goes to line 2.
Line 2 sees that it needs the value of name cheese_count
and looks to see if that name exists in the function. It does--it was assigned 20
in line 7--so that value is used.
Lines 3 through 5 are done similarly.
When finishing line 5, Python sees the function is finished. The names that were created for this function execution, namely cheese_count
and box_of_crackers
, are destroyed and their values marked for possible destruction. Then execution resumes after the line that called the function.
Line 8 is straightforward.
Lines 9 and 10 define new variables. The values are calculated, stored in memory, and given the names amount_of_cheese
and amount_of_crackers
. Since these lines are not inside a function, those names are marked as being "global".
Line 11 is like line 7, so the values of the parameters are calculated and stored in the variables cheese_count
and box_of_crackers
.
Lines 2 through 5 are executed (again) but the current values of the names are used.
When done, execution resume to after line 11. Since there is nothing after line 11, the program ends.
Is all that clear? In summary, you are correct that "Python runs code line by line," but not always in top-to-bottom order. In particular, lines 2 and 3 are executed after line 7 then again after lines 9-11.
What happens in C when you print a declared, but unassigned variable?
According to C99 standard, this is undefined behavior. Let's see why:
Section 6.7.8.9 says that
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
This applies to your variable c
, because it has automatic storage duration, and it is not initialized explicitly.
Section J.2 says that
The behavior is undefined in the following circumstances:
...
The value of an object with automatic storage duration is used while it is
indeterminate
This applies to your code as well, because you read c
when you pass it as a parameter to both printf
and putchar
, and the value of c
is still indeterminate, because it has not been assigned.
Print method in R for function that prints summary even when function output is assigned to an object
per @MrFlick's comment, I changed the function to:
fun_example <- function(xvar, yvar){
# Plots
plot1 = ggplot2::ggplot(data.frame(xvar, yvar), ggplot2::aes(x = xvar, y = yvar)) + ggplot2::geom_line()
plot2 = ggplot2::ggplot(data.frame(xvar, yvar), ggplot2::aes(x = xvar, y = yvar)) + ggplot2::geom_line()
plots <- list(plot1, plot2)
# Correlation
Cor <- cor(xvar, yvar)
message("Visually inspect each plot in the plots object to check for linearity.\n")
if(x$Cor > 0.8){
message("A correlation greater than 0.8 was found.")
} else {
message("A correlation less than or equal to 0.8 was found.")
}
result <- list(plots, Cor)
names(result) <- c("plots", "Cor")
class(result) <- "fun_example"
suppressMessages(return(result))
}
Note that this didn't work for me if the messages did not come before the return() function.
Assignment to print function
It doesn't raise an error because in Python 3, print
is a regular function. And function objects are bound to names, so print
is a name (a "variable") that refers to a particular function object.
Since functions are no different than variables, you can reassign them however you please:
def add(a, b):
return a + b
add = "ha-ha, I'm a string"
The parentheses after the =
sign are the kind of parentheses you use in math:
print = (1 + 2) # print == 3
Parentheses immediately after a name represent a function call.
But now print
is broken, and you'll never ever be able to print anything! Not really - there's a copy in __builtins__.print
:
print = __builtins__.print
However, you can mess that up just as easily:
__builtins__.print = 5
In Python 2, however, print
is a statement, not a regular function, so this fails:
Python 2.7.16 (default, Dec 3 2019, 07:02:07)
>>> print = 5
File "<stdin>", line 1
print = 5
^
SyntaxError: invalid syntax
Related Topics
Filter Dataframe Using Global Variable with The Same Name as Column Name
Customise The Infowindow/Tooltip in R -> Plotly
Removing "Nul" Characters (Within R)
R: Remove Repeating Row Entries in Gridextra Table
Change Distance Between X-Axis Ticks in Ggplot2
Change The Color of a Ggplot Geom a Posteriori (After Having Specified Another Color)
Show Source Code for a Function in a Package in R
Converting an Xts Object to a Data.Frame
Cumulative Sums Over Run Lengths. Can This Loop Be Vectorized
Split Data.Frame Row into Multiple Rows Based on Commas
Shiny Sliderinput from Max to Min
How to Make UI Respond to Reactive Values in for Loop
Manually Defining The Colours of a Wireframe
How to Get The R Shiny Downloadhandler Filename to Work
Using Inst/Extdata with Vignette During Package Checking R 2.14.0