User input - Linking the number of units printed to the units

Viewed 24

Im trying to find a tutorial on this aspect of linking the number of units printed to the units themselves. So a user can specify how many outputs are generated in the type of unit they want, either pounds or kgs.

If someone can point me in the right direction, it would be appreciated.

import random

bmi_unit = input("Enter the units: , kg or pounds ")

bmi_sample = input("Enter a number of outputs : ")

while bmi_unit != 'pounds' or bmi_unit != 'kg':

if bmi_unit =='pounds':
    for i in range("what ever the user wants):
        print("bmi_unit" , i+1, '=', random.randint(10, 20),'pounds')
    break

elif bmi_unit == 'kg':
    for i in range(what ever the user wants):
        print("bmi_unit ", i+1, "=" ,round(random.randint(10, 20)/2.205,2),"kg")
    break

else :
    bmi_unit = input("Incorrect input. Reinput the unit kg or pounds")
1 Answers

I've made some edits to your code

import random

while True:
    bmi_unit = input("Enter the units: kg or pounds ")
    if bmi_unit in ["kg", "pounds"]:
        break
    else:
        print("Incorrect input. Reinput the unit kg or pounds ")

while True:
    try:
        bmi_sample = int(input("Enter a number of outputs: "))
        break
    except:  # if the user inputs a string
        print("Please enter a number ")

if bmi_unit == "pounds":
    for i in range(bmi_sample):
        print("bmi_unit", i + 1, "=", random.randint(10, 20), "pounds")

elif bmi_unit == "kg":
    for i in range(bmi_sample):
        print("bmi_unit", i + 1, "=", round(random.randint(10, 20) / 2.205, 2), "kg")

The while loops should only encapsulate the input in order not to repeat extra stuff before we validate it.

The output with kg and 3 is:

Enter the units: , kg or pounds kg
Enter a number of outputs: 3
bmi_unit 1 = 8.62 kg
bmi_unit 2 = 7.26 kg
bmi_unit 3 = 8.62 kg

Is this what you're looking for?

Related