Integrating a for loop into an if statement - python

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.

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.

You simply need to wrap your entire script inside a loop, for example:
from __future__ import division
import math
for _ in range(10):
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."
This will run your if statement 10 times in a row.

I'd try this:
while True:
function = ...
if function == 0:
break
elif ...

Related

including a loop for the function so it can ask the user to re enter a number if the number is incorrect

I need to modify my program so it includes a prime read with a loop. the document is saying for my getNumber function it should ask the user only to input a number between 2 and 30, the getScores function should ask the user to input a number between 0 and 100. it they don't get a number between that it should tell them re enter a number. I don't get any errors when running the program but not sure what I am missing in order to make sure its running properly to include the re enter a number part. here is the code:
# main
def main():
endProgram = 'no'
print
while endProgram == 'no':
totalScores = 0
averageScores = 0
number = 0
number = getNumber(number)
totalScores = getScores(totalScores, number)
averageScores = getAverage(totalScores, averageScores, number)
printAverage(averageScores)
endProgram = input('Do you want to end the program? yes or no ')
while not (endProgram != 'yes' or endProgram != 'no'):
print('Enter yes or no ')
endProgram = input('Do you want to end the program? (yes or no )')
# this function will determine how many students took the test
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
# this function will get the total scores
def getScores(totalScores, number):
for counter in range(0, number):
score = int(input('Enter their score: '))
return totalScores
while score < 0 or score > 100:
print('Please enter a number between 0 and 100')
score = int(input('Enter their score: '))
return score
# this function will calculate the average
def getAverage(totalScores, averageScores, number):
averageScores = totalScores / number
return averageScores
# this function will display the average
def printAverage(averageScores):
print ('The average test score is: ', averageScores)
# calls main
main()
First suggestion is to change this:
number = int(input('How many students took the test: '))
reason is that, as it is written, this takes the user input and implicitly assumes that it can be cast to an int. What happens if the user enters "hello, world!" as input? It is necessary to take the user input first as a string, and check if it would be valid to convert it:
number = input("enter a number:")
if number.isdecimal():
number = int(number)
Next, the function as a whole has some structural problems:
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
number is passed in as an argument to getNumber. Then the name number is reassigned to the result of reading the user input, and returned... Make sure you understand what the return statement does: once the control flow reaches a return statement, that function terminates, and it sends that value back to the caller. So your while loop never runs.
Maybe this would work better:
def getNumber():
while number := input("enter a number"):
if number.isdecimal() and int(number) in range(0, 31):
return int(number)
print('Please enter a number between 2 and 30')

Why does the following code not follow the specified order?

I want it to say welcome, ask for the user input (a,b,c), validate the user input and if the validation returns that the input is reasonable then carry out the quadratic formula on a,b,c. I suspect the problem is in the while-loop. The program just welcomes, asks for input then says welcome again and so on.
from math import sqrt
def quadratic_formula(a,b,c):
a=float(a) #The quadratic formula
b=float(b)
c=float(c)
x1_numerator = -1*b + sqrt((b**2)-4*(a*c))
x2_numerator = -1*b - sqrt((b**2)-4*(a*c))
denominator = 2*a
x1_solution = x1_numerator/denominator
x2_solution = x2_numerator/denominator
print("x= "+str(x1_solution)+" , x= "+str(x2_solution))
def number_check(a,b,c,check): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check == False
else:
check == True
check = False
while check == False:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
number_check(a,b,c,check)
else:
quadratic_formula(a,b,c)
You are correct in your suspicion. You have a problem in your while loop. does not work the way your code assumes.
Instead you need to write something like:
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check = False
else:
check = True
return check
check = False
print("Welcome to the Quadratic Equation Calculator!")
while check == False:
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
check = number_check(a,b,c)
quadratic_formula(a,b,c)
Note, that in addition to changing the while loop you also need to update number_check as input parameters are not updated in calling scope. Instead the function has to explicitly return the updated value.
Try using return, not attempting to modify a global variable.
There's a way to use global variables (see global statement), but it's not necessary for this code.
The check variable itself isn't really necessary, though
def number_check(a,b,c):
a=float(a)
b=float(b)
c=float(c)
return (b**2)-4*a*c >= 0 # return the check
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if not number_check(a,b,c):
print("The values you have entered result in a complex solution. Please check your input.")
else:
break # getting out of the loop
There are two problems with the way you're using the check variable in the number_check function.
First, you're not assigning new values to it, because you're using == (which tests equality) rather than =.
But also, since it's a parameter variable, it's local to the function. So assigning it inside the function does not modify the global variable that you test in the while loop. Rather than use a global variable, you can simply test the result of number_check directly, and use break when you want to end the loop.
If you make this change, you need to move the call to quadratic_formula out of the else: clause, because that's only executed when the while condition fails, not when we end the loop with break.
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
return False
else:
return True
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if number_check(a,b,c):
break
quadratic_formula(a,b,c)

How to recall a function until invalid input?

I'm new to python, and I was wondering how I could recall a function until the user gives invalid input.
Here's a sample of code:
start = input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")
def main_function(start):
while start.lower() != "exit":
if start.lower() in "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")
if start.lower() in "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")
if start.lower() in "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")
else:
print("Program halted normally.")
quit()
main_function(start)
What I am trying to get it to do is to reprompt 'start' if the user inputs a proper input, and then get it to run through the function again. I have tried putting 'start' within the function above and below the 'else' statement, but it never accepts the new input.
I would do it like this, define the start input in a method and call it inside the loop, when it's equal to "exit" than break the loop.
Also use elif, this way if the first condition statement is True than you won't check the others, unless that what you want of course.
def get_start_input():
return input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")
def main_function():
while True:
start = get_start_input()
if start.lower() == "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")
elif start.lower() == "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")
elif start.lower() == "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")
elif start.lower() == "exit":
print("Program halted normally.")
break
main_function()
EDIT:
As dawg wrote in comment, it's preferred to use here == instead of in because you can have several matches and ambiguous meanings.

How do i have my python program restart to a certain line?

print ("Enter the object you are tyring to find.")
print ("1 = Radius")
print ("2 = Arch Length")
print ("3 = Degree")
print ("4 = Area")
x = int(input("(1,2,3,4):"))
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
if x == 2:
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
I am making a basic math program but i want it to repeat infinitely. This is not the complete code but i want to do the same thing for the rest of the "if" statements. i want it to end after each function is completed and repeat back to the first line. thanks!
Put a
while True:
at the spot you want to restart from; indent all following lines four spaces each.
At every point in which you want to restart from just after the while, add the statement:
continue
properly indented also, of course.
If you also want to offer the user a chance to end the program cleanly (e.g with yet another choice besides the 4 you're now offering), then at that spot have a conditional statement (again properly indented):
if whateverexitcondition:
break
You will need to add a way to let the user quit and break the loop but a while True will loop as long as you want.
while True:
# let user decide if they want to continue or quit
x = input("Pick a number from (1,2,3,4) or enter 'q' to quit:")
if x == "q":
print("Goodbye")
break
x = int(x)
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
elif x == 2: # use elif, x cannot be 1 and 2
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
elif x == 3:
.....
elif x == 4:
.....
If you are going to use a loop you can also verify that the user inputs only valid input using a try/except:
while True:
try:
x = int(input("(1,2,3,4):"))
except ValueError:
print("not a number")
continue

Print 20 random numbers in range, check if odd or even

I've been killing myself with this assignment for the past week and I'm still baffled. I have to create a program that gets the user to input 2 numbers, arranges them in order of size, prints 20 random numbers within the range and also determines whether or not they are odd or even. Here's what I've got so far:
#Main function
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
def sortnums(first, second):
if first > second:
return second, first
else:
return first, second
MIN, MAX = sortnums(first, second)
for x in range(20):
random = random.randrange(MIN, MAX)
if random%2 == 0:
print ("The random number", random ,"is even.")
elif random%2 != 0:
print ("The random number", random ,"is odd.")
return random
main()
I'm not just lazily asking for a solution, I've genuinely exhausted my efforts on this one and even contacted my lab tutor for additional advice but I'm still clueless as to why it's not working.
Thanks.
On this line:
random = random.randrange(MIN, MAX)
You've shadowed the random module with a number. You should pick a different variable name, like random_number so subsequent calls to random.randrange don't error:
for x in range(20):
random_number= random.randrange(MIN, MAX)
if random_number % 2 == 0:
print ("The random number", random_number, "is even.")
elif random_number % 2 != 0:
print ("The random number", random_number, "is odd.")
return random_number
A few problems with your code. But you are pretty close. I think you may just have issues with understanding how your program is executed. The "main()" function call at the bottom is the first code execution point. The user prompts are collecting the user data just fine, but then you just define two functions and never actually call them. Additionally, you use the word "random" as a variable name but this is also being used as the namespace for the random library. Below is a fixed up version...
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
MIN, MAX = sortnums(first, second)
for x in range(20):
randNum = random.randrange(MIN, MAX)
if randNum%2 == 0:
print ("The random number", randNum ,"is even.")
elif randNum%2 != 0:
print ("The random number", randNum ,"is odd.")
def sortnums(first, second):
if first > second:
return second, first
else:
return first, second
main()
Your biggest oversight is probably shadowing the random you imported with the first random number you select. After this, you program would fail the second time through the loop when it tries to look up the randrange attribute on an int.
There's already a nice builtin way to sort numbers
def sortnums(first, second):
return sorted([first, second])
More simply, using tuple unpacking
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
for x in range(20):
num = random.randrange(*sorted([first, second]))
if num%2 == 0:
print ("The random number", num ,"is even.")
else:
print ("The random number", num ,"is odd.")
return
main()
You can remove repetition from the print functions like this
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
for x in range(20):
num = random.randrange(*sorted([first, second]))
print("The random number", num ,"is", "odd." if num%2 else "even.")
return
main()
I would take the def sortnums outside of the main function:
import random
def sortnums(first, second):
if first > second:
return second, first
else:
return first, second
Then the MIN, MAX assignment seems to have wrong indentation...
and you re-assign random (the module) with a value. Change it to something
like r or number.
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
MIN, MAX = sortnums(first, second)
for x in range(20):
r = random.randrange(MIN, MAX)
if r%2 == 0:
print ("The random number", r ,"is even.")
elif r%2 != 0:
print ("The random number", r ,"is odd.")
return r
main()
Try:
import random
min_input = int(input("Enter first integer: "))
max_input = int(input("Enter second integer: "))
if max_input<min_input:
min_input, max_input=max_input, min_input
for i in range(20):
rnd=random.randrange(min_input, max_input)
print 'The random number {} is {}.'.format(rnd, ('even', 'odd')[rnd%2])

Categories

Resources