default value python code example

Example 1: python default arguments

def my_function(name, age = 20):
  print(name + " is " + str(age) + " years old"

my_function("Mitro") # Mitro is 20 years old
my_function("Mitro", 26) #Mitro is 26 years old

Example 2: python default input

# Python 3:
age = input('Enter your age: ') or 18

# Older versions:
age = int(raw_input('Enter your age: ') or 18)

Example 3: how to set a default parameter in python

def my_function(num1,num2=0):		#if num2 is not given, it will default it to zero
  return num1 + num2

print(my_function(1,2))				#prints out 3
print(my_function(4))				#prints out 4 since num2 got defaulted to 0

Example 4: python default arguments

def your_function(arg,kwarg='default'):
    return arg + kwarg

Example 5: default values python

class Test:
    def __init__(self, val, num = 0):
        self.val = val
        self.num = num

# you can write this:

t = Test(1)
print(t.num) # prints 0

# OR this

t = Test(1, 2)
print(t.num) # prints 2

Example 6: python default value

d = {'a': 1, 'b': 2}

print(d.get('c', 3)) 	# 3