Functions and Variables
Function - Actions or a verbs that allows you to do something in the program
- Each language will have predetermined words to be used to action the program
- functions can be linked together in the same line
Arguments - Input to a function that influences it's behavior
Side Effects - the action of the function
Bugs - mistake in a program
Return Values - passing back info from a function
Variables - representation of a value
Strings - sequence of text, (str)
Parameters - what can be passed to a function
"=" assignment operator, copies the right to the left
Comments - notes to the programmer within the code.
- use comments as psuedocode - used to express your thoughts within the program
- comments are written with a # or a block with 3 """
Parameters - what is given to the function
- positional parameters
- parameters that are run positionally in the code
- named parameters
- rules for a function that can be changed
Arguments can be strung together within a function using the + sign or with a comma
- ex: print ("hello,", name) <- notice spacing here vs below
print ("hello, " + name)
How to use methods
- variable = str.function()
- ex: name = name.strip() - strip is a function of string to remove white space. name is the variable we want to apply it to.
A new feature to use variables within a function is to assign the string as an f string and put the variable in curly brackets {}
- print (f"hello, {name}")
Linked functions
- name = input("What's your name? ").strip().title()
- variable = function.function.function
- functions will read left to right and update the variable as they go
Integers - (int) whole numbers, positive of negative
- int is a function and can be used to convert string numbers to integers
Functions can be nested and viewed just like math problems
- x = int(input("What's x? "))
Float - a number with a decimal point, a real number.
Square brackets [] are generally optional options.
f string is format string
def - define - used to create a function
- def hello(to="world"):
- print("hello,", to)
- name = input("What's your name? ")
- hello(name)
- def is the function called to create a function
- hello is the name of my created function
- (to) is the parameter my function is calling, this is customizable and should be something that reminds you of the use of the function. Say hello to ...
- ="world" - default value if nothing is given
- : is the indicator that code is following, this code is indented with tab or 4 spaces
- name = is using input to retrieve the name from the user
- hello(name) is using the variable name in place of my defined to function
- output is: hello, Stan
Building code to work with defined functions (cleaned up)
def main():
name = input("What's your name? ")
hello(name)
def hello(to="world"):
print("hello,", to)
main()
defining my main code block
defining hello - creating the function
calling the main code
Return - return - used to return a value