Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating a for loop into an if statement

This is kind of a double-barreled question, but it's got me puzzled. I currently have the following code:

from __future__ import division
import math

function = int(raw_input("Type function no.: "))


if function == 1:
    a = float(raw_input ("Enter average speed: "))
    b = float(raw_input ("Enter length of path: "))
    answer= float(b)/a
    print "Answer=", float(answer),

elif function == 2:
    mass_kg = int(input("What is your mass in kilograms?" ))
    mass_stone = mass_kg * 2.2 / 14
    print "You weigh", mass_stone, "stone."

else: print "Please enter a function number."

Now, I'd like to have some kind of loop (I'm guessing it's a for loop, but I'm not entirely sure) so that after a function has been completed, it'll return to the top, so the user can enter a new function number and do a different equation. How would I do this? I've been trying to think of ways for the past half hour, but nothing's come up.

Try to ignore any messiness in the code... It needs some cleaning up.

like image 926
dantdj Avatar asked Mar 04 '26 06:03

dantdj


1 Answers

It's better to use a while-loop to control the repetition, rather than a for-loop. This way the users aren't limited to a fixed number of repeats, they can continue as long as they want. In order to quit, users enter a value <= 0.

from __future__ import division
import math

function = int(raw_input("Type function no.: "))

while function > 0:
    if function == 1:
        a = float(raw_input ("Enter average speed: "))
        b = float(raw_input ("Enter length of path: "))
        answer = b/a
        print "Answer=", float(answer),
    elif function == 2:
        mass_kg = int(input("What is your mass in kilograms?" ))
        mass_stone = mass_kg * 2.2 / 14
        print "You weigh", mass_stone, "stone."

    print 'Enter a value <= 0 for function number to quit.'
    function = int(raw_input("Type function no.: "))

You can tweak this (e.g., the termination condition) as needed. For instance you could specify that 0 be the only termination value etc.

An alternative is a loop that runs "forever", and break if a specific function number is provided (in this example 0). Here's a skeleton/sketch of this approach:

    function = int(raw_input("Type function no.: "))

    while True:
       if function == 1:
          ...
       elif function == 2:
          ...
       elif function == 0:
          break      # terminate the loop.

      print 'Enter 0 for function number to quit.'
      function = int(raw_input("Type function no.: "))

Note: A for-loop is most appropriate if you are iterating a known/fixed number of times, for instance over a sequence (like a list), or if you want to limit the repeats in some way. In order to give your users more flexibility a while-loop is a better approach here.

like image 161
Levon Avatar answered Mar 06 '26 20:03

Levon