.Empty string comprehension?

Hello everyone , I wrote this code that I understand except one detail in it , here’s the code :

person_infos(first_name, last_name, age=''):
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person
a = person_infos('fna', 'lna', age=34)
print(a)

The variable age in the function definition is an empty string , but we when set age as a number ( age = 4 ) no error happens , when we say if age = True , that means age is not an empty string , or it can be even a number ( age being everything except an empty string ) ? Thanks a lot

1 Like

Python is a dynamic typing language. It means age can be assigned any type at anytime.

age = ""        # string
age = 1         # int
age = 1.0       # float
age = True      # bool

You can preserve a type via casting, e.g. to str(), int(), etc.:

def personal_info(first_name, last_name, age=""):
    person = {"first": first_name, "last": last_name}
    if age:
        person["age"] = str(age)
    return person


personal_info("john", "doe", age=30)
# {"first": "john", "last": "doe", "age": "30"}
2 Likes

Thanks for the reply , when you set age = 30 , why do you enter the if statement, because i’ve learned that for a string , a True value means that this string is not empty , but what about numbers , why age is True ( so that if passes ) when you set age to 30 , I think I missed something

2 Likes

Python’s if uses duck-typing for truth/false values.

Duck-typing: “if it quacks like a duck, it might as well be a duck”.

So Python allows (almost) any value to be treated as close
enough to True or False. Values which “quack like True” are
often said to be truthy:

  • True
  • non-empty strings
  • non-zero numbers
  • non-empty containers (lists, dicts, etc)
  • any object by default

while these are considered to be falsey:

  • False
  • empty strings
  • zero
  • empty containers
  • None

So 30 is considered to be a truthy (true-like) value.

2 Likes

Thank you very much , I understand clearly now.

1 Like