python functions code example

Example 1: python functions

def myFunction(say): #you can add variables to the function
  print(say)

myFunction("Hello")

age = input("How old are you?")

myFunction("You are {} years old!".format(age))

#this is what you get:

Hello
How old are you?
>>11 #lol my real age actually
You are 11 years old!

Example 2: python functions

# first we have to write 'def'
# then our function name followed by ()
# and a ':' abd defining  block of code

def multiply():     # naming convention could be same as variable for functions
    product = 10.5 * 4
    return product


product = multiply()
print(product)

Example 3: python functions

def chess_piece(piece_name, piece_value, piece_rank):
    """Info about a chess piece."""
    print(f"\nThis chess piece is called the {piece_name}.")
    print(f"It has an approximate value of {piece_value} points.")
    print(f"In other words, this piece is the {piece_rank} valuable piece.")
    
    
chess_piece('pawn', '1', 'least')
chess_piece('knight', '3', 'second to last most')
chess_piece('bishop', '3', 'third to last most')
chess_piece('rook', '5', 'third most')
chess_piece('queen', '9', 'second most')
chess_piece('king', 'infinite', 'most')

Example 4: Python Functions

def my_function():
  print("Hello from a function")

my_function()

Example 5: python functions

def function():
  print('This is a basic function')
  
function()
// Returns 'This is a basic function'

def add(numA, numB):
  print(numA+numB)
  
add(1,2)
// Returns 3

def define(value):
  return value

example = define('Lorem ipsum')
print(example)
// Returns 'Lorem ipsum'

Example 6: python functions

# Python Functions
def a_function(): #def FUNCTIONNAMEHERE(): Function content
  print("Hello World!")
  return 0
def answerValid(prompt, correct_answers, invalid): # Functions can also have parameters, or variables that can be used only in tha function
  while True:
    user = input(prompt)
    if user in correct_answers:
      break 
      return user # Example Function
   	else:
      print(invalid)

a_function() # To call a function; Prints 'Hello World!'
# But if this is done:
function_called = a_function() # function_called would contain a 0, because the function returns 0
answer = answerValid("What is 8 * 8?", [64], "Invalid Option")
print(answer) # Prints 64, because that is the only possible answer

Example 7: python functions

#Functions
def string():
  print('This is a function')
  
  print(string())