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
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am trying to write a function to get 2 int values from a user until their sum is 21, Simple!!
The aim is to keep prompting the user to pass 2 int values until the condition is met. I am not sure where the code breaks as it stops when either conditions is met, both if true or false.
def check_for_21(n1,n2):
result = 0
while True:
while result != 21:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
except:
if n1+n2 == 21:
print("You got it! ")
else:
break
break
This is what you are looking for you had multiple logical errors! However, the idea was there but wrongly formatted. In this program, it runs continuously until you enter two numbers and their sum is 21
def check_for_21():
while True:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
check_for_21()
Try this. This will meet your requirment.
a = 5
while (a<6):
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 == 21:
print("You got it ")
break
else:
print("You did not get to 21! ")
Take the input, check for result, if you get 21, break the loop.
def check_for_21(n1,n2):
result = 0
while True:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
except:
pass
Below is the test result of the code that worked for me:
I am trying to create an average solver which can take a tuple and average the numbers. I want to use the except hook to give an error message and then continue from the beginning of the while loop. 'continue' does not work.
import sys
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z==1 :
def my_except_hook(exctype, value, traceback):
print('Please only use integers.')
continue
sys.excepthook = my_except_hook
print("Enter your set with commas between numbers.")
x=input()
i=len(x)
print('The number of numbers is:',i)
y=float(float(sum(x))/i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z=input()
print('Thank you for your time.')
As #PatrickHaugh noted, the keyword continue means nothing to my_except_hook. It is only relevant inside a while loop. I know this is what you are trying to do by having continue being called in the flow of a loop, but it's not really in the context of a loop, so it doesn't work.
Also, i is how many numbers you are, yet you set it as the length of the user input. However, this will include commas! If you want the real amount of numbers, set i = len (x.split (",")). This will find out how many numbers are in between the commas.
Never mind, I solved the problem. I just used a try-except clause...
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z == 1:
try:
print("Enter your set with commas between numbers.")
x = input()
i = len(x)
y = float(float(sum(x)) / i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z = input()
except:
print('Please use integers.')
x = []
continue
print('Thank you for your time.')
I have been asked to make a piece of code including a for loop and a while loop. I was asked to:
Get the user to input a number
Output the times table for that number
Starts again every time it finishes
I was able to do the for loop like so:
num= int(input ("Please enter a number."))
for x in range (1,13):
print (num,"x",x,"=",num*x)
But I cannot figure out how to make it repeat, any ideas?
Just put your code inside a while loop.
while True:
num = int(input("Please enter a number: "))
for x in range(1,13):
print("{} x {} = {}".format(num, x, num*x))
I think it would be nice for you to handle errors.
If a user decides to enter a non digit character it will throw an error.
while True:
num = input('please enter a number')
if num ==0:
break
elif not num.isdigit():
print('please enter a digit')
else:
for x in range(1, 13):
mult = int(num)
print('%d x %d = %d' %(mult, x, mult*x))
I don't understand why my following piece of code does not work:
running = True
name = input("Whats your name?: ")
print ("Hi", name, "Which Program Would You Like to Use")
print ("1. Upper to Lower Case converter")
print ("2. Lower to Upper Case converter")
print ("3. Character Count")
x = input("Enter the Number: ")
if x==1:
print ("You have selected the Upper to Lower Case converter")
y = input("Enter the text you would like converted: ")
print (y.lower())
elif x==2:
pass print ("You have selected the Lower to Upper Case converter")
z = input("Enter the text you would like converted: ")
print (z.lower()
running = False
you need here:
x = int(input("Enter the Number: "))
input takes as string
if x==1: you were comparing string with integer
You probably are missing a closing bracket here: print (z.lower()
In this statement if x==1:, you are comparing x, which is a string, with an int, and, as you already might have understood, you cannot do it.
One solution for this problem is to convert x to and int directly when you get the input from the user:
x = int(input("Enter a number: "))
Or comparing the x with a string number:
if x== "1":
# do stuff
It depends of course in what you want to do.
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 ...