Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count Y/N answers in Python?

I’ve been trying to make a form using y/n as answers for each of the questions. I’ve been wondering if I could do the same thing like this, but for y/n questions instead of true/false statements.

Here’s the code I’ve been working on.

print('Are You Ready for Omicron?')
print('Here\'s a test to make sure you\'re ready')
print('Note: please answer in y or n')
print('')
faceMask = input('Do you have a face mask? ')
faceShield = input('Do you have a face shield? ')
alcohol = input('Do you have alcohol in hand? ')

booleanList = [faceMask, faceShield, alcohol]
yCount = sum(booleanList)
print(yCount)

Based on the code, I was expecting to count the y answers but ended up with an error like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):
  File [REDACTED], line 14, in <module>
    yCount = sum(booleanList)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Any simple yet good ideas on how to do this?

>Solution :

If you want to work with the example you cited, you could do this:

print('Are You Ready for Omicron?')
print('Here\'s a test to make sure you\'re ready')
print('Note: please answer in y or n')
print('')
faceMask = input('Do you have a face mask? ')
if faceMask == "y":
    faceMask = True
else:
    faceMask = False
faceShield = input('Do you have a face shield? ')
if faceShield == "y":
    faceShield = True
else:
    faceShield = False
alcohol = input('Do you have alcohol in hand? ')
if alcohol == "y":
    alcohol = True
else:
    alcohol = False
booleanList = [faceMask, faceShield, alcohol]
yCount = sum(booleanList)
print(yCount)

This is not a recommended solution but I wanted to remind you to use if/else

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading