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.
Related
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
I've been trying to solve the issue with guessing the number program,
The first number the program has to print Ans which is (Startlow + Starthigh)/2 and then Ans gets updated depends on the input
I can't figure out why my while loop keeps waiting for the input for at least 2 times until it prints the results even if I press l or h (unless I press c) which breaks the loop
Startlow = 0
Starthigh = 100
Ans = (Startlow + Starthigh)/2
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number " + str(int(Ans)))
if input() == "c":
print("Game over,Your secret number was: "+str(int(Ans)))
break
elif input() == "l":
Startlow = Ans
Ans = (Startlow + Starthigh)/2
elif input() == "h":
Starthigh = Ans
Ans = (Startlow + Starthigh)/2
else:
print("Sorry, I did not understand your input.")
any help appreciated :)
You should be asking for input once in the loop, and then comparing that answer to the items you want.
You are instead requesting a (potentially different) answer at each of your conditionals.
The number of questions asked depends on how many conditionals you fall through.
Just do:
x = input()
if x == "c":
#And so on...
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 have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.
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.