Trying to use a while statement to return to an opening prompt.
I apologize for my garbage code.
I've tried assigning a True/False value to the while loop but the program just terminates when any input is given.
choice = eval(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
while choice:
if choice == 1:
degreesF = eval(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesC, 'degrees Celcius')
elif choice == 2:
distanceFeet = eval(input('Enter the distance in feet: '))
distanceMeters = distanceFeet/3.28
print(distanceMeters, 'm')
elif choice == 3:
Pounds = eval(input('Pounds: '))
Kilograms = Pounds*0.45359237038
print(Kilograms, 'kg')
elif choice == 4:
Ounces = eval(input('Ounces: '))
Liters = Ounces*0.0295735
print(Liters, 'L')
Currently, the program returns me to whatever I set the input as. For example, if I input 1, I can convert temperature but I am only able to convert temperature.
Putting below line inside a while True may result in what you expected:
choice = eval(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
If I am not wrong, you need something like below:
while True:
choice = eval(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
if choice == 1:
degreesF = eval(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesC, 'degrees Celcius')
elif choice == 2:
distanceFeet = eval(input('Enter the distance in feet: '))
distanceMeters = distanceFeet/3.28
print(distanceMeters, 'm')
elif choice == 3:
Pounds = eval(input('Pounds: '))
Kilograms = Pounds*0.45359237038
print(Kilograms, 'kg')
elif choice == 4:
Ounces = eval(input('Ounces: '))
Liters = Ounces*0.0295735
print(Liters, 'L')
You like to include the input in the while-loop:
while True:
choice = int(input('What would you like to convert? \n Farenheit to Celcius (1) \n Feet to Meters (2) \n Pounds to Kilograms (3) \n Ounces to Liters (4) \n : '))
if choice == 1:
degreesF = float(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesC, 'degrees Celcius')
elif choice == 2:
distanceFeet = float(input('Enter the distance in feet: '))
distanceMeters = distanceFeet/3.28
print(distanceMeters, 'm')
elif choice == 3:
Pounds = float(input('Pounds: '))
Kilograms = Pounds*0.45359237038
print(Kilograms, 'kg')
elif choice == 4:
Ounces = float(input('Ounces: '))
Liters = Ounces*0.0295735
print(Liters, 'L')
else:
break
You have to put the eval line inside your while loop for it to run multiple times.
untested (pseudo) code:
while true:
your input line
your other code
this will run forever so I suggest doing somethig like this
while true:
your input line
if input == 0:
break
your other code
this will stop the while loop when you type 0
You need to do a couple of things, and for now you should make them explicit:
Your program should run forever, or until it is told to quit.
Your prompt for a menu selection should loop until it gets a valid answer.
Your inputs for numeric values should loop until they get valid answers.
General Form of the Solution
How can you do these things? In general, by starting with bad initial data, and looping until you see good data:
some_value = bad_data()
while some_value is bad:
some_value = input("Enter some value: ")
A good "default" value for bad_data() is the special value None. You can write:
some_value = None
On the other hand, your is bad test might want a different kind of bad data, such as a string. You might consider using '' as your bad data value:
some_value = ''
Finally, if your is bad test wants an integer value, maybe consider using a number you know is bad, or a number out of range (like a negative value):
some_value = 100
# or
some_value = -1
For your specific problems:
1. How do I run forever?
You can run forever using a while loop that never exits. A while loop will run as long as the condition is true. Is there a value that is always true in Python? Yes! Its name is True:
while True:
# runs forever
2. How do I loop until my menu selection is valid?
Using the general form, above, for an integer selection. Your menu asks the user to enter a number. You can check for a valid value either using str.isdigit() or using try:/except:. In python, the exception is the better choice:
choice = -1 # Known bad value
while choice not in {1, 2, 3, 4}: # {a,b,c} is a set
instr = input('Choose 1..4')
try:
choice = int(instr)
except:
choice = -1
3. How can I loop until I get a valid numeric value?
For floating point numbers, like temperatures, you don't want to try to spell out an explicit set of allowed answers, or a range of numbers. Instead, use None (you could use Nan, but it's more characters for the same result).
temp = None
while temp is None:
instr = input('Enter a temp: ')
try:
temp = float(instr)
except:
temp = None
Be aware that 'nan' is a valid float. So you might want to check for that and disallow it.
How do I combine all these things?
You put them together in blocks:
while True: # run forever
# Menu choice:
choice = -1 # Known bad value
while choice not in {1, 2, 3, 4}: # {a,b,c} is a set
instr = input('Choose 1..4')
try:
choice = int(instr)
except:
choice = -1
if choice == 1:
# Now read temps
temp = None
while temp is None:
instr = input('Enter a temp: ')
try:
temp = float(instr)
except:
temp = None
Related
I am trying to find scores from only 7 judges and to have the numbers between 1-10 only, what is the problem with my code I am an newbie trying to self teach myself:)
So what I'm asking is how to limt the input to have to be 7 inputs per name and to limt the user input to 1-10 for numbers.
import statistics#Importing mean
def check_continue(): #defining check_continue (checking if the user wants to enter more name/athletes
response = input('Would you like to enter a another athletes? [y/n] ') #Asking the user if they want another name added to the list
if response == 'n': #if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
print('Please select a correct answer [y/n]') #making sure the awsener is valid
return check_continue() #calling check continue
while(True):
name = input('Please enter a athletes name: ') #asking for an athletes name
if name == (""):
print ("try again")
continue
else:
try:
print("Enter the judges scores with space inbetween each score") #asking for scores
avg = [float(i) for i in input().split( )] #spliting the scores so the user only needs to put a space for each score
except ValueError:
continue
print("Please enter scores only in numbers")
scores = '' .join(avg)
print("please only enter number")
if scores ==("") or scores <=0 or scores >=10:
print("Please enter a score between 1-10")
continue
else:
print("_______________________________________________________________________________")
print("Athlete's name ",name) #Printing athletes name
print("Scores ", avg) #printing athletes scores
avg.remove(max(avg)) #removing the highest score
avg.remove(min(avg)) #removing the lowest score
avgg = statistics.mean(avg) #getting the avg for the final score
print("Final Result: " +
str(round(avgg, 2))) #printing and rounding the fianl socre
if not check_continue():
break
else:
continue
After reading input scores from judges, make sure that len(input.split()) == 7 to match first criteria.
Once you have the list of scores, just have a check that for each score, 1 <= int(score) <= 10.
If necessary, I can provide a working code too.
import statistics # Importing mean
def check_continue(): # defining check_continue (checking if the user wants to enter more name/athletes
# Asking the user if they want another name added to the list
response = input('Would you like to enter a another athletes? [y/n] ')
if response == 'n': # if n, ends the loop
return False
elif response == 'y': # if y, continues the loop
return True
else:
# making sure the awsener is valid
print('Please select a correct answer [y/n]')
return check_continue() # calling check continue
while(True):
# asking for an athletes name
name = input('Please enter a athletes name: ')
if name == (""):
print("try again")
continue
else:
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
if len(scores) != 7:
print("try again")
continue
print("_______________________________________________________________________________")
print("Athlete's name ", name) # Printing athletes name
print("Scores ", scores) # printing athletes scores
scores.remove(max(scores)) # removing the highest score
scores.remove(min(scores)) # removing the lowest score
# getting the avg for the final score
avg = statistics.mean(scores)
print("Final Result: " + str(round(avg, 2))) # printing and rounding the final score
if not check_continue():
break
This one should work. Let me know if there are any issues.
scores = [float(i) for i in input('Enter the judges scores with space inbetween each score').split() if 1 <= float(i) <= 10]
This line of code only saves values between 1 and 10, thus already checking for those values. Then the number of elements is checked to be 7.
PS: Would also want to point out that in your code, nothing ever executes after the except ValueError: continue. The continue basically skips to the next iteration without running any of the next lines of code.
My two cents. All checks of input you can warp before printing results with if all(): function for length of input scores list and range of nums between 1 and 10 (see code below).
For mean calc you don't need to delete value from list. You can make sorting and then slicing of list.
check_continue() can be simplify. Check entering for y or n value and return True or False by cases in dict. Otherwise loop.
import statistics
def check_continue():
response = input('Would you like to enter a another athletes? [y/n] ').lower() # Format Y and N to y and n
if response in ['y', 'n']: # Check if response is y or n
return {'y': True, 'n': False}[response]
check_continue()
while True:
name = input('Please enter a athletes name: ') #asking for an athletes name
if name: # Check if name not empty
while True: # make a loop with break at only 7 scores enter
scores_input = input("Enter the judges scores with space inbetween each score (only 7 scores)").split(' ')
try:
scores = [float(s) for s in scores_input] # sort list for extract part for avgg calc
except ValueError:
print("Please enter scores only in numbers")
continue
if all([len(scores) == 7, max(scores) <= 10.0, min(scores) >= 1]):
print("_______________________________________________________________________________")
print(f"Athlete's name {name}") #Printing athletes name
print(f"Scores {scores}") #printing athletes scores
avgg = statistics.mean(sorted(scores)[1:-1]) #getting the avg for the final score
print(f'Final result - {avgg :.2f}')
break
else:
print("Please enter 7 numbers for scores between 1-10")
if not check_continue():
break
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.
I'm updating a crack the code game I made in Python so that you can play a single-player game against the computer. For some reason, the interpreter either doesn't use the data stripped from the input used to determine player count or skips the if statement that uses the stripped data from the input. Either way, after you input the player number it goes straight to the guessing code with an empty list of correct code characters.
My code for the player count determining and code creation is:
plyrs = 0
correctanswer = []
print('Welcome!')
plyrs = str(input('How many players are there? (minimum 1, maximum 2) '))
if plyrs == 2:
print("I'm gonna ask you for some alphanumerical (number or letter characters to make a code for the other player to guess.")
input('Press enter when you are ready to enter in the code!') #Like all of my games, it has a wait.
i = 0
while i < 4:
correctanswer.append(input('What would you like digit ' + str(i + 1) + " to be? "))
i = i + 1
print("Ok, you've got your code!")
i = 0
while i < 19: #Generates seperator to prevent cheating
print('')
i = i + 0.1
print("Now, it's the other player's turn to guess!")
elif plyrs == 1:
import random
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
i = 0
while i < 4:
correctanswer.append(characters[randint(0,36)])
i = i + 1
print('Time for you to guess!')
print('')
No other skipping if statement questions apply to this so please help.
plyrs is a string, and you're comparing it to an int. "2" == 2 will always be false. Same with plyrs == 1, this will be false throughout.
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
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 ...