I tried running this code and it gave me this error, "TypeError: can only concatenate str (not "NoneType") to str". I need to know what to do.
I tried using '' or "True" instead of "None"
users = {'zacc_eli':{'first_name': 'Zaccheus',
'middle_name': None,
'last_name': 'Elisha',
'age': 19},
'_Djvy_': {'first_name': 'daniel',
'middle_name': 'joshua',
'last_name': 'adebayo',
'age': None}}
for username, details in users.items():
print(username + ':')
full_name = details['first_name'] + ' ' + details['middle_name'] + ' ' + details['last_name']
full_name2 = details['first_name'] + ' ' + details['last_name']
age = details['age']
if details['middle_name'] == None :
print('\tFull Name: ' + full_name2.title())
else:
print('\tFull Name: ' + full_name.title())
if details['age'] != None:
print('\tAge: ' + str(age))
I expect no double space when there is no middle name and no age when there is no age.
This line
full_name = details['first_name'] + ' ' + details['middle_name'] + ' ' + details['last_name']
fails if details['middle_name']
is None
rather than a str
value. At this point, though, you haven't checked if that is the case. You don't do that until 4 lines later.
Python is not lazy (like Haskell); it doesn't wait until you actually use the value of full_name
to evaluate the expression assigned to it.
Instead, check the value before you do anything that requires a str
:
for username, details in users.items():
print(username + ':')
first = details['first_name']
middle = details['middle_name']
last = details['last_name']
if middle is None:
full_name = first + ' ' + last
else:
full_name = first + ' ' + middle + ' ' + last
# Or a one-liner
# full_name = ' '.join([for x in [first, middle, last] if x is not None])
age = details['age']
print('\tFull Name: ' + full_name.title())
if age is not None:
print('\tAge: ' + str(age))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.