Loop failing to terminate when conditions are met - python

Why is the loop failing to terminate when meeting the required conditions.
I would appreciate an in-depth explanation rather than the code being corrected for me.
def get_name(name_type):
return raw_input("Please enter you're {}name: \n".format(name_type))
def UserName():
result = get_name("Fore"), get_name("Middle"), get_name("Sur")
return " ".join(result)
print("You're UserName is : " + UserName())
while True:
def Base():
return int(raw_input("Please select a base number: \n"))
def Power():
return int(raw_input("Please select a power number: \n"))
def result():
return Base()*Power()
print result()
cont = raw_input("Would you like to quit? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Would you like to quit? yes/no > ")
if cont=="no":
break

Your break statement is nested within the inner while loop, so it is breaking that loop rather than the while True loop. I think moving the conditional statement out of the inner loop and changing the logic to if discont=='yes' (note: renamed var to more accurate description) will give you what you want:
while True:
...
discont = raw_input("Would you like to quit? yes/no > ").lower()
while discont not in ("yes","no"):
discont = raw_input("Would you like to quit? yes/no > ").lower()
if discont=="yes":
break

Now it does:
def get_name(name_type):
return raw_input("Please enter you're {}name: \n".format(name_type))
def UserName():
result = get_name("Fore"), get_name("Middle"), get_name("Sur")
return " ".join(result)
print("You're UserName is : " + UserName())
print
cont = 'no'
while cont != 'yes':
def Base():
return int(raw_input("Please select a base number: \n"))
def Power():
return int(raw_input("Please select a power number: \n"))
def result():
return Base()*Power()
print result()
cont = raw_input("Would you like to quit? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Would you like to quit? yes/no > ")
if cont=="yes":
break

You're inside two while loops. You want to break out of both if the user wants to exit, otherwise only out of the inner one: Move the condition out of the while loop, then it should work:
from sys import exit
...
while True:
def Base():
return int(raw_input("Please select a base number: \n"))
def Power():
return int(raw_input("Please select a power number: \n"))
def result():
return Base()*Power()
print result()
cont = raw_input("Would you like to quit? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Would you like to quit? yes/no > ")
if cont=="yes":
break
The next piece of advice has nothing to do with your question, but I'll give it anyways: There's no need to define the Base, Power, and Result functions in every loop iteration. Just assign the values to variables and print directly:
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
print base*power

Related

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

How to make it my code go back to a specific while loop in python?

I'm new to Python and I am trying to create a simple calculator. Sorry if my code is really messy and unreadable. I tried to get the calculator to do another calculation after the first calculation by trying to make the code jump back to while vi == true loop. I'm hoping it would then ask for the "Enter selection" again and then continue on with the next while loop. How do I do that or is there another way?
vi = True
ag = True
while vi == True: #I want it to loop back to here
op = input("Input selection: ")
if op in ("1", "2", "3", "4"):
vi = False
while vi == False:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
break
#Here would be an If elif statement to carry out the calculation
while ag == True:
again = input("Another calculation? ")
if again in ("yes", "no"):
ag = False
else:
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
exit()
elif again == "yes":
print("okay!")
vi = True #I want this part to loop back
Nice start. To answer your question about whether there's another way to do what you're looking for; yes, there is generally more than one way to skin a cat.
Generally, I don't use while vi==True: in one section, then follow that up with while vi==False: in another since, if I'm not in True then False is implied. If I understand your question, then basically a solution is to nest your loops, or call one loop from within the other. Also, it seems to me like you're on the brink of discovering the not keyword as well as functions.
Code
vi = True
while vi:
print("MENU")
print("1-Division")
print("2-Multiplication")
print("3-Subtraction")
print("4-Addition")
print("Any-Exit")
op = input("Input Selection:")
if op != "1":
vi = False
else:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
print("Placeholder operation")
ag = True
while ag:
again = input("Another calculation? ")
if again not in ("yes", "no"):
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
ag = False
vi = False
elif again == "yes":
print("okay!")
ag = False
Of course, that's a lot of code to read/follow in one chunk. Here's another version that introduces functions to abstract some of the details into smaller chunks.
def calculator():
vi = True
while vi:
op = mainMenu()
if op == "\n" or op == " ":
return None
x, y = getInputs()
print(x + op + y + " = " + str(eval(x + op + y)))
vi = toContinue()
return None
def mainMenu():
toSelect=True
while toSelect:
print()
print("\tMENU")
print("\t/ = Division; * = Multiplication;")
print("\t- = Subtract; + = Addition;")
print("\t**= Power")
print("\tSpace or Enter to Exit")
print()
option = input("Select from MENU: ")
if option in "/+-%** \n":
toSelect = False
return option
def getInputs():
inpt = True
while inpt:
x = input("insert first number: ")
y = input("insert second number: ")
try:
tmp1 = float(x)
tmp2 = float(y)
if type(tmp1) == float and type(tmp2) == float:
inpt = False
except:
print("Both inputs need to be numbers. Try again.")
return x, y
def toContinue():
ag = True
while ag:
again = input("Another calculation?: ").lower()
if again not in ("yes","no"):
print("Please input a 'yes' or a 'no'.")
if again == "yes":
print("Okay!")
return True
elif again == "no":
print("Done, Thank you for using Calculator!")
return False

loop fails to terminate once conditions are met

I am trying to get my function to end the loop once it hit the return clause but it fails to do so.
Explanations rather than direct code editing would be appreciated.
def Menu():
UserMenu = True
print ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
while UserMenu not in ("U", "E", "Q"):
print("\n Error: Choice must be U, E or Q")
return UserMenu
# Function designed to retrieve first name only from fullname entry.
def get_first_name(name):
first=[""]
i = 0
while i < len(name) and name[i] !=" ":
first += name[i]
i += 1
return name[:i]
# Function designed to retrieve first initial of last name or first initial of first name if only one name input.
def get_last_initial(name):
j = len(name) - 1
while j >= 0 and name[j] !=" ":
j-=1
return name[j+1]
# Function that generates username based upon user input.
def get_username():
name = raw_input("Please enter your Full Name: ")
username = get_first_name(name) + get_last_initial(name)
return username.lower()
# Function to generate exponential numbers based upon usser input.
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*",
power = power -1
return "=%d" % exponential
print Menu()
while UserMenu != "Q":
if UserMenu is "U":
UserMenu = raw_input("Please enter your Full Name: ")
print "your username is %s" % get_username()
else:
print print_exponential()
print Menu()
This is the whole program, hope it helps!
You need to update the value of UserMenu inside the loop, or else entering the loop will inherently be an infinite loop:
def Menu():
UserMenu = raw_input("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""")
while UserMenu not in ("U", "E", "Q"):
UserMenu = raw_input("\n Error: Please input only U, E or Q:")
return UserMenu
...
all your other functions
...
user_choice = Menu()
while user_choice != "Q":
if user_choice == "U":
print "your username is %s" % get_username()
else:
print_exponential()
user_choice = Menu()
By getting new input in the loop, it will be able to meet the criteria that controls the loop. The loop you wrote will just print then check UserMenu again without changing it, so the loop will never exit.
Managed to sort out my problem using the following code.
def Menu():
result = raw_input ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""").upper()
while result not in ("U", "E", "Q"):
print("\n Error: Please input only U, E or Q:")
result = raw_input ("""
U.Create a Username
E.Run Exponential Calculator
Q.Exit/Quit
""").upper()
return result
# Function designed to retrieve first name only from fullname entry.
def get_first_name(full_name):
i = 0
while i < len(full_name) and full_name[i] !=" ":
i += 1
return full_name[:i]
# Function designed to retrieve first initial of last name or first initial of first name if only one name input.
def get_last_initial(full_name):
j = len(full_name) - 1
while j >= 0 and full_name[j] !=" ":
j-=1
return full_name[j+1]
# Function that generates username based upon user input.
def get_username():
username = get_first_name(full_name) + get_last_initial(full_name)
return username.lower()
# Function to generate exponential numbers based upon user input.
def print_exponential():
base = int(raw_input("Please select a base number: \n"))
power = int(raw_input("Please select a power number: \n"))
exponential = 1
while power>0:
exponential = exponential * base
print base
if power >1:
print "*",
power = power -1
return "=%d" % exponential
choice = Menu()
while choice != "Q":
if choice == "U":
full_name = raw_input("Please enter your Full Name:")
print "your username is %s" % get_username()
else:
print print_exponential()
choice = Menu()

Continue isnt working properly

I do need help in solving my code.
Below python code 'continue' is not working properly
dicemp = {'12345':''}
while(1):
choice = int(input("Please enter your choice\n"))
if (choice == 1):
empno = input("Enter employee number: ")
for i in dicemp.keys():
if i == empno:
print("employee already exists in the database")
continue
print("Hello")
Output:
Please enter your choice
1
Enter employee number: 12345
employee already exists in the database
Hello
So for the above code if I give same employee no. 12345 it is going into if block and printing the message"employee already exists in the database" after this it should continue from start but in this case it is also printing "hello".
Your continue is moving the for loop on to its next iteration, which would have happened anyway. If you need to continue the outer loop, you can do something like this:
while True:
choice = int(input("Please enter your choice\n"))
if choice == 1:
empno = input("Enter employee number: ")
found = False
for i in dicemp:
if i == empno:
print("employee already exists in the database")
found = True
break
if found:
continue
print("Hello")
Now the continue is outside the for loop, so it will continue the outer loop.
You could simplify this to:
while True:
choice = int(input("Please enter your choice\n"))
if choice==1:
empno = input("Enter employee number: ")
if empno in dicemp:
print("employee already exists in the database")
continue
print("Hello")
and get rid of the inner loop entirely.

python calculator program with expected indented block error

I have created a python calculator, I need to get it to restart, I have added the loop:
#This line defines the end of the program so it restarts.
def sys():
#These lines will define each operation.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def Multiply(x, y):
return x * y
def Divide(x, y):
return x/y
#This asks the user what operation they would like to use
print("Please select operation ")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
#This tells the user to enter the number of the operation they would like
operation = input("Enter operation(1/2/3/4):")
#This asks the user to input the two numbers they would like the calculator to calculate
num1 = int(input("Please enter first number: "))
num2 = int(input("Please enter second number: "))
#This is the part of the program that will calculate the calculations
if operation == '1':
print(num1, "+", num2, "=", add(num1,num2))
elif operation == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif operation == '3':
print(num1,"*",num2,"=", subtract(num1,num2))
elif operation == '4':
print(num1,"/",num2,"=", subtract(num1,num2))
else:
print("Invalid input")
inp = input("Enter clear to play again or exit to exit")
if inp == "clear":
sys()
else:
print("thanks for playing")
sys.exit()
It keeps saying expected an indented block and shows, that it wants the indent in front of:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def Multiply(x, y):
return x * y
def Divide(x, y):
return x/y
but when I add them in, it keeps saying, that the operation is not defined. I also feel like the loop will not work either.
It looks like you are trying to recursively re-run the code, in which case you probably want e.g.
import sys # so you can use sys.exit()
def add(x, y): # no need for these function definitions to be in the loop
...
...
def main(): # conventional name - sys shadows the module you just imported
print("Please select operation ")
print("1. Add")
...
inp = input("Enter clear to play again or exit to exit")
if inp == "clear":
main()
else:
print("Thanks for playing")
sys.exit() # or just 'return'
if __name__ == "__main__": # if run directly, rather than imported
main()
You can define functions within other functions (although there's no need here), but remember you need another level of indentation:
def outer(n):
def inner(x):
return x ** 2
return 2 * inner(n)
Note that using recursion means you will eventually hit the system recursion depth limit; iteration is probably wiser:
def main():
while True:
...
inp = input("Enter clear to play again or exit to exit")
if inp != "clear":
print("Thanks for playing")
break
You may be interested in this solution to your problem. It makes use of the operator module, which provides named functions for all the standard Python operators. It also uses a list to translate the operation number to a function and a symbol for printing.
from operator import add, sub, mul, div
operations = [
(add, '+'),
(sub, '-'),
(mul, 'x'),
(div, '/'),
]
while True:
print('1. Add')
print('2. Subtract')
print('3. Multiply')
print('4. Divide')
op = int(raw_input('Enter operation (1/2/3/4): '))
if 0 < op <= len(operations):
func, sym = operations[op-1]
num1 = float(raw_input('Please enter first number: '))
num2 = float(raw_input('Please enter second number: '))
print('{} {} {} = {}'.format(num1, sym, num2, func(num1, num2)))
else:
print('Invalid operation')
continue
while True:
inp = raw_input('Enter clear to play again or exit to exit: ')
if inp == 'exit':
print('Thanks for playing')
exit()
elif inp == 'clear':
break
output
1. Add
2. Subtract
3. Multiply
4. Divide
Enter operation (1/2/3/4): 3
Please enter first number: 8
Please enter second number: 9
8.0 x 9.0 = 72.0
Enter clear to play again or exit to exit: exit
Thanks for playing
If you have an empty function, put in the phrase pass as in:
def some_func():
pass
And that error will no longer occur.

Categories