Answers for "set default value function python"

5

set default python

newDict = {1:"One",
           2:"Two",
           3:"Three"}
x=newDict.setdefault(4,"Four")
print(newDict[4])
#returns Four

newDict2 = {1:"One",
           2:"Two",
           3:"Three",
           "Hello":"World"}
y=newDict.setdefault("Hello","Yellow")
print(newDict2["Hello"])
#returns World

dict1 = {1:"One",2:"Two"}
x=dict1.setdefault(3,"Three")
x=dict1.setdefault(2,"Duo")
print(dict1)
#prints {1: 'One', 2: 'Two', 3: 'Three'}

#Therefore if value doesn't exist it is given default value, else value of key is returned.
Posted by: Guest on September-18-2020
4

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
Posted by: Guest on October-25-2020
2

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
Posted by: Guest on August-03-2020

Code answers related to "set default value function python"

Python Answers by Framework

Browse Popular Code Answers by Language