Please try it:
{% set total_wth_amount = [0] %}
{% for item in doc.items %}
{% if item.item_name == "Rent" or item.item_name == "Science TextBook" or item.item_name == "WTH item" %}
{% set wth_rate = 5 %}
{% else %}
{% set wth_rate = 0 %}
{% endif %}
{% if wth_rate > 0 %}
{% set wth_amount = item.base_net_amount * (wth_rate / 100) %}
{% if total_wth_amount.append(total_wth_amount.pop() + wth_amount) %}{% endif %}
{% endif %}
{% endfor %}
Total withheld tax amount is:
{{ frappe.format_value(total_wth_amount.pop(), {'fieldtype': 'Currency', 'options': 'TZS'}) }}
Reference: