This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'False':
guess = guess - int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'Correct':
print 'Success!, your number is approximately equal to:', guess
oracle()
What I am trying to do now is get this sequence of if/ elif/ else commands to loop until the user enters 'Correct', i.e. when the number stated by the program is approximately equal to the users number, however if I do not know the users number I cannot think how I could implement and if statement, and my attempts to use 'while' also do not work.
As an alternative to #Mark Byers' approach, you can use while True:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Your code won't work because you haven't assigned anything to n before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.
Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 12 months ago.
I'm new to python and I am trying to figure out how do I enter an error message if the user inputs a number less than zero.
Here is my code to give you a better understanding and I thank you all in advance for any advice.
# Python Program printing a square in star patterns.
length = int(input("Enter the side of the square : "))
for k in range(length):
for s in range(length):
if(k == 0 or k == length - 1 or s == 0 or s == length - 1):
print('*', end = ' ')
else:
print('*', end = ' ')
print()
Here is a simple and straight forward way to use a while loop to achieve this. Simple setting an integer object of check to 0. Then the while loop will evaluate check's value, then take user input, if the user input is greater than 0, let's set out check object to 1, so when we get back to the top of the loop, it will end.
Otherwise, if the if check fails, it will print a quick try again message and execute at the top of the loop again.
check = 0
while check == 0:
length = int(input("Enter the side of the square : "))
if length > 0:
check = 1
else:
print("Please try again.")
You can use this code after the input statement and before for loop.
if length < 0 :
Print("invalid length")
Break
I'm new to python and I'm trying to write a program that will guess the users number.
I'm trying to change the range that's in a while loop, depending on the users answer, but i'm not sure how can I do that.
list = range(100)
half = len(list)//2
def the_guess():
guess = "n"
while guess != "y":
guess = input('is it ' + str(len(list)//2) + '? up(+) or down(-) ?\n')
if guess == 'y':
print('I knew it!!')
break #stops loop?
else:
if guess == '+':
print(list[half:])
# use second part of the range
if guess == '-':
print(list[:half])
# use first part of the range
else:
print("ok, let's try again\n")
the_guess()
The loop works, i'm just not sure how to go about changing the value of the range to something other than 100.
for example:
if the user inputs a "+" I want the range to change to 50 - 100, and will continue to dividing it depending on the users input.
I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
Hello fellow programmers,
I'm quite a Python and overall programming newbie and I don't know how to process user input the bestimmt. A friend of mine suggested while loops and they worked quite well but now I have a serious problem.
The program is about asking the user which one of 3 ways to calculate Pi he wants. After his/her selection, e.g. the way to calculate Pi using a polygon which doubles the number of corners after each iteration, it asks how many digit the user wants to see or how many loops should be calculated etc. I also have added some code that checks what the user has written, e.g. if the user is asked to either type y or n but types b the program reminds him of that and asks again.
This style has led to whiles, inside whiles, inside whiles and now looks more like HTML code than Python and is a little complicated to understand...
Take a look:
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
prgrm_ctrl_main_while_start = 0
while prgrm_ctrl_main_while_start == 0:
print "Please select the type of algorithm you want to calculate Pi."
usr_ctrl_slct_algrthm = raw_input("'p' to use polygons, 'm' to use the Monte-Carlo algorithm or 'c' for the Chudnovsky algorithm: ")
print " "
if usr_ctrl_slct_algrthm == 'p':
#import libraries
import time
from mpmath import *
#starting values
n_corners = mpf(8)
counter = 0
while_loop_check_itertions = 0
while while_loop_check_itertions == 0:
print "Pi will be calculated more precisely the more iterations you select but it'll also take longer!"
loops = int(input("Please select number of iterations (1 - 10.000.000): "))
print " "
if 1 <= loops <= 10000000:
loops = loops - 1
decimals = int(input("Please select the amount of decimals you want to see: "))
print " "
decimals = decimals + 1
starttime = time.clock()
mp.dps = decimals
while counter <= loops:
counter = counter + 1
n_corners = mpf(n_corners) * mpf(2)
circle = mpf(360)
alpha = mpf(circle) / mpf(n_corners)
beta = mpf(alpha) / mpf(2)
radiansBeta = mpf(mp.radians(beta))
opp_leg = mpf(mp.sin(radiansBeta))
edge_lngth = mpf(opp_leg) * mpf(2)
circmfrnce = mpf(n_corners) * mpf(edge_lngth)
pi = mpf(circmfrnce) / mpf(2)
print "Pi: ", mpf(pi)
print "Time to calculate: ", time.clock() - starttime, "seconds"
print " "
prgrm_ctrl_p_algrthm_while_start = 0
while prgrm_ctrl_p_algrthm_while_start == 0:
usr_ctrl_slct_p_algrthm = raw_input("Would you like to try this algorithm again? (y/n): ")
print " "
if usr_ctrl_slct_p_algrthm == 'y':
usr_ctrl_slct_p_algrthm_slction = 0
break
elif usr_ctrl_slct_p_algrthm == 'n':
usr_ctrl_slct_p_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_p_algrthm_slction == 0:
continue
else:
usr_ctrl_slct_diffrt_algrthm_while_start = 0
while usr_ctrl_slct_diffrt_algrthm_while_start == 0:
usr_ctrl_slct_diffrt_algrthm = raw_input("Do you want to use another algorithm? (y/n): ")
print " "
if usr_ctrl_slct_diffrt_algrthm == 'y':
usr_ctrl_slct_diffrt_algrthm_slction = 0
break
elif usr_ctrl_slct_diffrt_algrthm == 'n':
print "See you next time!"
print " "
usr_ctrl_slct_diffrt_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_diffrt_algrthm_slction == 0: #The program gets to this line and in case of the user selecting 'y' should continue in the first while-loop
continue
else: #if the user says 'n' the program should interrupt and stop, in the best case it should close the command line (in my case IDLE)
break #instead of doing all this the code gets executed again in the 2nd while loop not the 1st
"""NOTE: I also know the lines above continue or quit the 2nd while-loop"""
elif loops < 1:
print "Please select at least one iteration!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
else:
print "The maximum amount of iterations is 10 million!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
I have commented the lines that are effected...
I can't solve the problem with the main-while-loop therefore I'm asking you how I can solve this. Is there a better way of handling user input and checking if it's correct? I'm stuck at a point where I wish I had goto because I can't imagine any other solution.
Hopefully you can help me and thank you for reading this long code! I appreciate that! :)
holofox
My first thought is simplify things, please see this "pseudo-code":
while True: #select algorithm type
#code: ask for algorithm
if answer not in "pmc":
#some message
continue #non-valid algorithm selected, ask again
#...
if answer == 'p':
while True: #select iteration range
#code: ask for iteration
if answer_not_in_range:
#some message
continue #non-valid iteration value, ask again
#...
#perform calculation upon valid selections
#...
#calculation ends
#code: ask for try again with other iteration (algorithm stays same)
if answer != "yes":
break #break out of "iteration" loop
#else loop continues asking for new iteration
#code: ask for try again with other algorithm
if answer != "yes":
break #"algorithm" loop ends, program ends
As Robert Rossney says in an answer to another question:
My first instinct would be to refactor the nested loop into a function and use return to break out.