Paiza Python Primer 7: Understanding Functions

Python3 is completely free on Paiza, so I summarized it.

Paiza Python3 Primer

01: Let's learn about functions

lesson.py


#Both print and text are functions

#Functions can perform processing using values
#In the case of the following print whose value is called "argument""hello world"
#The result processed in the function is returned as a "return value" and can be assigned to a variable etc.
print("hello world")

#If it is input, the character string of the value input from the keyboard becomes the "return value" and can be assigned to the variable.
text=input()

Function function </ strong>
・ Divide and organize long codes → improve visibility
・ You can name the code
・ You can call the code as many times as you like → You can reuse it
・ You can combine codes

02: Let's make a function

lesson.py



#Create a function
#def=definition
def say_hello():
    print("hello world")
say_hello()

text.txt


hello world

lesson.py


#Create a function
#You can create your own function
#def=definition
def say_hello():
    print("hello world")
say_hello()
say_hello()

text.txt



hello world
hello world

Exercise

  1. Let's call the function

lesson.py


def say_hello():
    print("hello paiza")

#Write a function call below this
say_hello()
hello paiza
  1. Let's create a function

lesson.py



def say_hello():
    #Describe the processing in the function below this
    print("hello python")

say_hello()

03: Let's add arguments and return values

lesson.py



Last review
def say_hello():
    print("hello world")
    
say_hello()


def sum():
    print(10+20)

sum()

#Always 10+Having a function to calculate 20 doesn't help much


#If the function call has an argument, the function definition(x)Passed to a variable
#variable(x)Create a function that changes by changing
def sum(x):
#def sum(variable):
    print( x + 20)

sum(30)

#Function with two arguments
    print(x + y)
sum(3,2)

#Add arguments and return value

def sum(x,y):
    #Return to function definition and set
    return x + y

#In the nu1 variable(return x +y is)To be stored
num1=sum(3,4)
print(num1)
num1=sum(300,400)
print(num1)

Exercise

  1. Let's call the multiplication function

lesson.py


def multiply(x, y):
    return x * y

#Write a function call below this
ans =multiply(3,4)
print(ans)

  1. Let's create a multiplication

lesson.py



#Let's create a multiplication function

def multiply(x, y):
    #Describe the process below this
    return x*y

print(multiply(3, 4))
print(multiply(5, 7))
print(multiply(12, 34))

  1. Let's create a multiplication table

lesson.py



#Let's create a multiplication table

def multiply(x, y):
    return x * y

for step in range(1,10):
    for num in range(1, 10):
        print(multiply(step, num), end="")
        if num < 9:
            print(", ", end="")
    print("")

04: Let's understand the scope

lesson.py




'''
#review

def sum(x,y):
    return x + y

num = sum (3,2)
print(num)

'''

#I used to use variables when calling functions
def sum(x,y):
    return x + y
    
a=10
b=30

num sum(a,b)
print(num)



#It's okay to write weird before the definition
a=10
b=20
def sum(x,y):
    return x + y
    


num sum(a,b)
print(num)

lesson.py


#Even if I decide a lot of variables and make a mistake and it seems to be duplicated, it seems to work normally,
#The effective range of the variable is fixed and it is called "scope".

a=10
b=20

def sum(x,y):
    a=3
    print("hello" + str(a))
    return x + y

num = sum(a,b)

print(num)


hello3
30

#Because the scope is separated inside and outside
#The value is output without any problem
#The outer a variable and the inner a variable are treated as different things

lesson.py



There are local variables and global variables
Local variables ... with scope
Global variables ... can be used anywhere


#message is a global variable
message="paiza"
a=10
b=20

def sum(x,y):
    a=3
    
    #Be careful when changing global variables
    #Global variables are only allowed to be referenced from within the function,
    #Assignments and changes are not allowed as they are
    #Use global message to change
    #global message
    #message +=  "paiza"
    print("hello" + str(a))
    return x + y

num = sum(a,b)

print(num)
#Global variables can be used in common both inside and outside function definitions
#Even if you assign a value to a variable with the same name in the function definition, it automatically becomes another local variable.
#Does not affect global variables
print(message+ " " + str(a))

Exercise

Finding mistakes

lesson.py


 
 msg = "hello"

def say_hello():
    global msg
    msg += " "
    msg += "paiza"
    print(msg)

say_hello()

05: Let's make an RPG attack scene

lesson.py



#RPG attack scene

import random

def attack(enemy):
    print("The hero"+ enemy + "Attacked")
enemies = ["Slime","monster","Dragon"]

for enemy in enemies:
    #print("The hero"+ enemy + "Attacked")
    attack(enemy)
    
    #The scope of the def enemy variable and the for enemy variable are different.
    

lesson.py



#Make a critical hit according to a random value
import random

def attack(enemy):
    print("The hero"+ enemy + "Attacked")
    hit =random.randint(1,10)
    #Normal damage when 6 or less, critical hits otherwise
    if hit <6:
        print(enemy + "To" +str(hit) + "Damaged")
    else:
        print("critical hit!" + enemy+ "Inflicted 100 damage on!")
enemies = ["Slime","monster","Dragon"]

for enemy in enemies:
    #print("The hero"+ enemy + "Attacked")
    attack(enemy)
    
    #The scope of the def enemy variable and the for enemy variable are different.

Exercise

lesson.py



def attack(person):
    print(person + "Attacked the slime")

def output_ememy_hp(enemy_hp):
    print("Enemy HP remains" + str(enemy_hp) + "is")

enemy_hp = int(input())
team = {"Brave" : 200, "Warrior" : 150, "Wizard" : 100}

for person, power in team.items():
    attack(person)
    #Below, write the code to reduce the enemy's health
    enemy_hp -= power
    output_ememy_hp(enemy_hp)

output

06: Default value of argument

lesson.py



#Default value of argument
#Default value that can be used when the argument is omitted

def introduce(name):
    print("I"+name+"is")
    
introduce("Brave")

'''

output
I am a brave man

lesson.py


#Get arguments only when you have a special role
#Use it and automatically become a "villager" when there are no arguments
#You can do that with the default values

#You can specify the default value of the argument,
#If you call a function with no arguments, its default value is used.

#Pass the villager as an argument
def introduce(name = "Villager"):
    print("I" + name+ "is.")

introduce("Brave")    
introduce()

output
I am a brave man

I am a villager

lesson.py



#If you use the default value, it will be automatically omitted if you omit the argument.
#Initial value can be specified
#However, there is a function that sets the default value as an argument,
#If you want to add a new argument there, be careful about the position

def introduce(name = "Villager",greeting):
    print("I" + name+ "is."+greeting)

introduce("Brave","Hello")    
introduce("Hello")


#Doing the above will result in an error

#The argument for which you want to set the default value must be written after the argument without the default value
#So swap greeting and name

def introduce(greeting,name = "Villager"):
    print("I" + name+ "is."+greeting)

introduce("Brave","Hello")    
introduce("Hello")

I am a Hello. Brave
I am a villager Hello

lesson.py


#Variadic argument
#Receive arguments, but use when you don't know how many arguments
#Fix the content of the greeting as a trial so that multiple people can greet

#Function argument from name*(asterisk)Change to names and use the default value"Villager"Delete"
def introduce(greeting,*names):
    #Repeat the process
    for name in names:
        print("I" + name+ "is."+greeting)

#(Hello → greeting,Hero, villager, soldier →*names)Was put in
introduce("Hello","Brave","Villager","Soldier")

lesson.py


#Variadic argument-dictionary
   #**Change to people
def introduce(**peple):
    #Iterate over name, greeting,inpep;e.imes()change to
    for name,greeting in peple.items():
        print("I" + name+ "is."+greeting)
    print(peple)

#(Hello → greeting,Hero, villager, soldier →*names)Was put in
introduce(hero="Nice to meet you",villager="Hello",soldier ="I look forward to working with you.")

output
I am here Nice to meet you
I'm a villager Hello
I'm a soldier I look forward to working with you.
{'here': 'Nice to meet you', 'villager': 'Hello', 'soldier': 'I look forward to working with you.'}

Exercise

  1. Default value of argument

lesson.py



def say_hello(target = "paiza"):
    print("hello " + target)

#Write a function call below this
say_hello()

  1. RPG battle scene

lesson.py


#enemies*Enemies
def battle(*enemies):
	for enemy in enemies:
		print("The warrior" + enemy + "Fought with")

battle("Slime", "monster", "Dragon")

07: Understand keyword arguments

lesson.py



#Keyword arguments

#Function if the argument is omitted
#"Hello" in greeting variable,"World" is in the target variable
#Output
def say_hello(greeting = "hello",target="world"):
    print(greeting + " " + target)

#hello world
say_hello()

#Hello greeting, state that contains everyone in taeget
say_hello("Hello","everyone")

#If you use the default value for the argument, you can omit the argument when calling
#It is in the greeting variable and the target variable is omitted
#Therefore, it is output as good morning world.
say_hello("good morning")

#There is a "keyword argument" that labels the arguments
#Note that it is not an assignment because it is labeled, it is temporary
say_hello(greeting="Hello",target="everyone")

#You can also change the order of the arguments
say_hello(target="Cat teacher",greeting="Good morning")

#If the "keyword variable" has a default value, its argument can be omitted.
say_hello(target="Cat teacher")
say_hello(greeting="Good morning")

output
hello world
Hello everyone
good morning world
Hello everyone
Good morning cat teacher
hello cat teacher
Good morning world

Exercise

  1. Keyword argument part 1

lesson.py



Expected output value
I am a villager

def introduce(name = "I", role = "Villager"):
    print(name + role + "is")

#Below this, describe the necessary processing
introduce()

  1. Keyword argument part 2

lesson.py



I am a warrior

def introduce(name = "I", role = "Villager"):
    print(name + role + "is")

#Below this, describe the necessary processing
introduce(role="Warrior")

Recommended Posts

Paiza Python Primer 7: Understanding Functions
Paiza Python Primer 8: Understanding Classes
Paiza Python Primer 1 Learn Programming
Paiza Python Primer 4: List Basics
Python functions
Paiza Python Primer 5: Basics of Dictionaries
Paiza Python Primer 3: Learn Loop Processing
#Python basics (functions)
[Beginner] Python functions
Understanding python self
Python Easy-to-use functions
Python basics: functions
Python Beginner's Guide (Functions)
Python basic course (12 functions)
[Python] Memo about functions
# 4 [python] Basics of functions
Python built-in functions ~ Zip ~
Python Tkinter Primer Note
Wrap Python built-in functions
Paiza Python Primer 2: Learn Conditional Branching and Comparison Operators
Curry arbitrary functions with Python ....
Python> lambda> tiny functions / callback functions
Getting Started with Python Functions
Python3 programming functions personal summary
O'Reilly python3 Primer Learning Notes
Complete understanding of numpy.pad functions
Study from Python Hour3: Functions
Overriding library functions in Python
Keyword arguments for Python functions
Python for super beginners Python #functions 1
Python 3 sorted and comparison functions
Full understanding of Python debugging
Python functions learned in chemoinformatics
Python higher-order functions and comprehensions
[python] Manage functions in a list
Python and DB: Understanding DBI cursors
About python dict and sorted functions
Using global variables in python functions
[Python] Understanding the potential_field_planning of Python Robotics
10 functions of "language with battery" python
Dynamically define functions (methods) in Python
[Road to Intermediate] Understanding Python Properties