Skip to content
Advertisement

How to make a for loop iterate a list and ask for input? PYTHON

I would like to make a program that asks how many bills of each type you got, to do this I wanted to use a for loop and a list.

I did this little test:

types_of_bills = [2, 5, 10]

for i in types_of_bills:
    amount_of_bills = int(input("How many {}$ bills have you got?".format(types_of_bills)[i])))

This only prints, not all three choices as I want:

How many 10$ bills have you got?

And when I give any input it gives me this error:

cantidad_de_billetes = int(input("How many {}$ have you got?".format(bills[i])))

ValueError: invalid literal for int() with base 10: ”

Advertisement

Answer

You do not need to use index like – (types_of_bills)[i], you can just use i

types_of_bills = [2, 5, 10]

for i in types_of_bills:
    amount_of_bills = int(input("How many {}$ bills have you got? ".format(i)))

Output –

How many 2$ bills have you got? 1
How many 5$ bills have you got? 2
How many 10$ bills have you got? 3

You will get ValueError: invalid literal for int() with base 10, because of giving input something other than a integer

Also, instead of .format, you can use f-strings because it is much easier to read –

amount_of_bills = int(input(f"How many {i}$ bills have you got? "))

Check this out – Python 3 f-string

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement