This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Python - `break` out of all loops [duplicate]
(4 answers)
Closed 8 years ago.
Hello i have this login that i am trying to make and when i get to the command screen if i want to exit out of the program i type "exit", but the problem is i have it in a double while loop and don't know how to break out of both. Here is an example of the code:
a = 0
b = 0
loginatt = 0
while a == 0:
if loginatt == 4:
print "Too many tires!"
break
password = raw_input("Password: ")
if password == "test":
b = 1
while b == 1:
command = raw_input("command: ")
if command == "exit":
break
else:
loginatt += 1
print "error, login failed!"
this part of the code won't break out of the double while loop:
command = raw_input("command: ")
if command == "exit":
break
break will only leave one level of looping. You could try resetting your outer loop variable:
if command == "exit":
a = 1
break
However, it might be better to break your code up a bit:
def access_control(correct_pass="test", attempts=4):
"""Control access to the supplied function func."""
for _ in range(attempts):
password = raw_input("Password: ")
if password == correct_pass:
get_commands()
break
else:
print "Incorrect password."
else:
print "Too many tries."
def get_commands():
"""Take user input until they enter 'exit'."""
while True:
command = raw_input("Command: ")
if command == "exit":
break
You can now call access_control to enter the password; if correct, you will be passed on to get_commands:
>>> access_control()
Password: test
Command: exit
>>>
or
>>> access_control()
Password: foo
Incorrect password.
Password: bar
Incorrect password.
Password: baz
Incorrect password.
Password: python
Incorrect password.
Too many tries.
>>>
There is no keyword to break from more than one loop. You can try the following:
wantToBreak = False
while b == 1:
command = raw_input("command: ")
if command == "exit":
wantToBreak = True
break
if wantToBreak:
break
It utilizes a boolean variable which indicates whether the flow should be interrupted (break more levels).
Generally variable names like a and b aren't very explicit. Also your login functionality is independent of your command functionality, hence why not seperate both?
#! /usr/bin/python2.7
def login(maxTries = 4):
while maxTries:
password = raw_input('Password: ')
if password == 'test':
return True
maxTries -= 1
print 'Too many tries.'
return False
def runCommand():
while True:
command = raw_input('Command: ')
if command == 'exit': break
print 'processing command', command
if login(): runCommand()
Instead of breaking when finding the command exit you can also use an iterator with a sentinel:
def runCommand():
for command in iter(lambda: raw_input('Command: '), 'exit'):
print 'processing command', command
Related
What I'm trying to do is get the position of the users input so if they recall a command it will return the value but it doesn't work for some reason idk why I've tried everything I know please help.
#new file
#new untitled file
args = []
newcommands = []
import time,random,os,sys
commands = ["help","version","python"]
while True:
command = input(">")
if command not in commands:
print("That command does not exist")
if command == "help":
print(commands)
if command == "version":
print("Version = 0.0.1")
if command == "python":
print("Type exit to exit the python interperter")
os.system("python")
if command == "DM ME A COMMAND":
pass
if command == "New":
if len(newcommands) != 5:
name = input("Enter a name: ")
text= input("Enter text for the function: ")
q = newcommands.append(name)
args.append(text)
if q == newcommands.index(0):
print(args.index(0))
if q == newcommands.index(1):
print(args.index(1))
if q == newcommands.index(2):
print(args.index(2))
if q == newcommands.index(3):
print(args.index(3))
if q == newcommands.index(4):
print(args.index(4))
if q == newcommands.index(5):
print(args.index(5))
i dont know what are you trying to do but seems your logic is more than i could understand
because you try to enter New command which is not on the list it means it will never execute the if condition for the "New"
and if that's not all you also try to get command line args which will never given by the user.
so basically please give the description of you question
I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')
I'm trying to make a script where someone can type a username and the script will check if the directory exists, returning true or false as it goes through the list. Currently, the output is always "Not found"/false even though there should definitely be at least one true returned.
def scan():
username = input("Type in the username here: ")
i = 0
searchFor = folderList[i] + username
listLength = len(folderList)
while i < listLength:
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
For reference, this code below which doesn't use a loop works fine, as if I type in the username and the correct index for the element of the directory that exists, it returns true, otherwise if I choose another index it's false as it should, so it's not an issue with the elements or folder permissions.
def test():
username = input("Type in the username here: ")
i = int(input("Type list index number here: "))
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print("Folder found: " + searchFor)
else:
print("Not found!")
Would appreciate any help!
I'm writing an answer because the existing answers fail to address the problem, and I think they confuse things more than anything.
You currently have searchFor outside of the loop. As a result, it will be given a value once before the loop is entered, then its value is never changed. If you want its value to change, you must manually reassign it:
while i < listLength:
searchFor = folderList[i] + username
Although, really, a for loop should be used here instead (but not as #Sai suggests):
for folder in folderList:
searchFor = folder + username
You never use i for anything other than indexing folderList, so you should just iterate the folderList directly instead. Iterating a range is generally regarded as a code smell if you're just using the number to index a list.
This code will help you
def scan():
username = input("Type in the username here: ")
is_exists = False
for i in range(0,len(folderList)):
searchFor = folderList[i] + username
if os.path.isdir(searchFor):
is_exists = True
break
if is_exists:
print("Search is found")
else:
print("Not Found")
def scan():
username = input("Type in the username here: ")
i = 0
listLength = len(folderList)
while i < listLength:
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm trying to figure out how to make Python go back to the top of the code. In SmallBasic, you do
start:
textwindow.writeline("Poo")
goto start
But I can't figure out how you do that in Python :/ Any ideas anyone?
The code I'm trying to loop is this
#Alan's Toolkit for conversions
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
start()
So basically, when the user finishes their conversion, I want it to loop back to the top. I still can't put your loop examples into practise with this, as each time I use the def function to loop, it says that "op" is not defined.
Use an infinite loop:
while True:
print('Hello world!')
This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
If you were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
for example.
Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.
1. Loops
An example of how you could do exactly what your SmallBasic example does is as follows:
while True :
print "Poo"
It's that simple.
2. Recursion
def the_func() :
print "Poo"
the_func()
the_func()
Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!
Edited to Answer Question More Specifically
#Alan's Toolkit for conversions
invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")
while invalid_input: # this will loop until invalid_input is set to be False
start()
You can easily do it with loops, there are two types of loops
For Loops:
for i in range(0,5):
print 'Hello World'
While Loops:
count = 1
while count <= 5:
print 'Hello World'
count += 1
Each of these loops print "Hello World" five times
Python has control flow statements instead of goto statements. One implementation of control flow is Python's while loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.
Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.
while True:
# do stuff here
pass
The line # do stuff here is just a comment. It doesn't execute anything. pass is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."
Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.
You could do something like this:
while True:
cmd = raw_input('Do you want to quit? Enter \'q\'!')
if cmd == 'q':
break
cmd will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd stores just the letter 'q', the code will forcefully break out of its enclosing loop. The break statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.
write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.
https://wiki.python.org/moin/ForLoop
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
def start():
Offset = 5
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Please be sensible try just the lower case')
def getMessage():
print('Enter your message wanted to :')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (Offset))
key = int(input())
if (key >= 1 and key <= Offset):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
I'm very very new to programming and for a school project (50% of my final grade) I had to create a Python program that did roughly this.
I've had some help from my older brother and my teacher but mainly did it myself with some flow charts etc, so please forgive me if I haven't followed conventional rules and things of this nature, or if my code is messy. I will finalise it, just needed bait of help/support from the pro's.
This is my code and I have an issue with it. Once I have pressed 'y' and then 'y' again on the displayMenu() why doesn't it run oldUser()
Also, if any of you have any suggestion on what could make my code better, or I could improve it would be very helpful and I will take it on board.
import os # allows me to use functions defined elsewhere. os module allows for multi platforming.
import sys
words = []
users = {}
status = ""
def teacher_enter_words():
done = False
print 'Hello, please can you enter a word and definition pair.'
while not done:
word = raw_input('\nEnter a word: ')
deff = raw_input('Enter the definition: ')
# append a tuple to the list so it can't be edited.
words.append((word, deff))
add_word = raw_input('Add another word? (y/n): ')
if add_word.lower() == 'n':
done = True
def student_take_test():
student_score = 0
for pair in words:
print 'Definition:', pair[1]
inp = raw_input('Enter word: ')
student_score += check_error(pair[0], inp)
print 'Correct spelling:', pair[0], '\n'
print 'Your score:', student_score
def check_error(correct, inputt):
len_c = len(correct)
len_i = len(inputt)
# threshold is how many incorrect letters do we allow before a
# minor error becomes a major error.
# 1 - allow 1 incorrect letter for a minor error ( >= 2 becomes major error)
threshold = 1
# immediately check if the words are the same length
num_letters_incorrect = abs(len_c - len_i) # abs() method returns value of x - positive dist between x and zero
if num_letters_incorrect == 0:
for i in xrange(0, len(correct)):
if correct[i] != inputt[i]:
num_letters_incorrect += 1
if num_letters_incorrect <= threshold:
if num_letters_incorrect == 0:
return 2 # no incorrect letter.
else:
return 1 # minor error.
else:
return 0 # major error.
def displayMenu():
status = raw_input('Are you a registered user? y/n?: ')
if status == raw_input == 'y':
oldUser()
elif status == 'n':
newUser()
def newUser():
createLogin = raw_input('Create login name: ')
if createLogin in users:
print '\nLogin name already exist!\n'
else:
createPassw = raw_input('Create password: ')
users[createLogin] = createPassw
print '\nUser created!\n'
def oldUser():
login = raw_input('Enter login name: ')
passw = raw_input('Enter password: ')
if login in users and users[login] == passw:
print '\nLogin successful!\n'
else:
print "\nUser doesn't exist or wrong password!\n"
if __name__ == '__main__':
running = True
while running:
os.system('cls' if os.name == 'nt' else 'clear') # multi-platform, executing a shell command
reg = raw_input('Do you want to start the program? y/n?').lower()
if reg == 'y' or reg == 'yes':
displayMenu()
else: sys.exit(0)
inp = raw_input('Are you a Teacher or a Student? (t/s): ').lower()
if inp == 't' or inp == 'teacher':
teacher_enter_words()
else:
student_take_test()
running = False
raw_input is a function. status == raw_input == 'y' will never be true: that is comparing status with the function, and with 'y'.
I suspect that's simply a typo, and you just meant if status == 'y':