Make two while loops one loop - python

I have two while loops that are almost identical apart from a few numbers have changed. I've been looking around but I can't find a solution to my problem. Any help would be appreciated. I want to make the two while loops one loop but I dont know how. I've been looking around for an answer but nothing seems to apply to my problem.
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username1=input("What is your username: ")
password1=input("What is your password: ")
break
else:
print("Invalid input.")
continue
The only thing that has changed is the number 1 has changed to a number 2 (with the exception of row[1])
Again, any help would be appreciated.

From you saying the only difference is 1 becomes 2 I'm guessing you are just trying to run the loop again for a second user, perhaps a dictionary here, then you could just iterate the loop you already have constructed for each user in the dicitonary, you would have to touch up your loops I cannot run them but an idea for format would be something like so
while True:
users = {'User 1': [username1, password1], 'User 2': [username2, password2]}
for k in users:
print('{}'.format(k))
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
users[k][0]=input("What is your username: ")
users[k][1]=input("What is your password: ")
for row in reader:
if row[0]==users[k][0]:
if row[1]==users[k][1]:
print("Welcome " + users[k][0])
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
users[k][0]=input("What is your username: ")
users[k][1]=input("What is your password: ")
break
else:
print("Invalid input.")
continue

Assuming your while loops are within the functions you listed, this is the easiest way I can think of.
from threading import Thread
t1 = Thread(target = firstFunction)
t2 = Thread(target = secondFunction)
t1.start()
t2.start()

Related

My script can't recognise names inside the username file

It can see the file, if i change the name on the path slightly run seizes to function but eithr way it can't read the words in the file despite being able to before while I was writing the program. And now suddenly it doesn't work, the file location is the same and all.
P.S. I have no idea how to specify code on overflow
filen = 'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
usern = open(filen, 'r')
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
def func():
user = input("Enter new Username: ")
passs = input("Enter new Password: ")
passs1 = input("Confirm password: ")
if passs != passs1:
print("Passwords do not match!")
else:
if len(passs) <= 6:
print("Your password is too short, restart:")
elif user in usern:
print("This username already exists")
else:
usern = open(filen, "a")
usern.write(user+", "+passs+"\n")
print("Success!")
while True:
if userr not in usern:
again = input("This username does not exist, would you like to try again? ")
if again == ("No"):
func()
elif again == ("no"):
func()
elif again == ("Yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif again == ("yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif userr in usern:
print("Good, you have entered the zone")
I am not sure I have full understand your means, but as your code, I have some suggestions:
close file if you open it
use f.readline() and str.split() to parse username and passwd and store in array, so you can use in to check, if the file is not to large.

Simple looping if password

while True:
look = input("Key : ")
if look == "ksvbd956dmew1":
But instead of that and having a bunch of elifs can I do like
while True:
look = input("Key : ")
if look == "ksvbd956dmew1", "Otherpassword", "Otherpassword":
Then if the user types one of those passwords it lets them in. I wasn't sure what this was called as I am new to python so I couldn't search it up Hopefully someone could help me here :)
Try this,
passwordList = ("ksvbd956dmew1", "Otherpassword", "Otherpassword")
password = input("Please enter password : ")
while True:
try:
if password in passwordList:
print("Password is Correct")
break
else:
raise Exception
except:
print("Password is wrong")
password = input("Please enter password : ")
while True:
look = input("Key : ")
if look in ("ksvbd956dmew1", "Otherpassword", "Otherpassword"):
...

Function for two users

I have a log in system for two users. I had duplicate code for it but I made it a function to make the code more efficient. However, I am not too sure how to make some variables change for each user. Here is the code:
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
Basically, I want to have username and password different for user 1 to user 2 but I have no idea where to start and nothing seems to help. When I input the username and password for user two, it overwrites the input I made for user one and I don't want that happening. Thanks,
Dylan
It seems you are practicing python or a simple question, well I have added the Pseudo code which you can develop yourself because it is simple and if you write this yourself it will help you think in that paradigm inorder to solve this problem.
Whenever you want to do something or implement it, do it in steps or write it down, it helps alot.
Read this btw.
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
#How to Save Username and password
#1. Find Two Empty Rows or one empty row and it's corresponding column in CSV file. (Can be done using running a loop on the csv file)
#2. Store Username password in the corresponding rows and columns above.
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
As per your requirements it seems that dictionary of successfully logged in usernames and passwords could be better for you if you store them
Make your code as belows.
users_logged_in={}
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
# usernames and passwords you have entered stored in dict
users_logged_in[username]=password
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
If you want the order of the usernames logged in to system to be preserved go to OrderedDict from Python collections.
Else you could create list with tuples of usernames and passwords
Create tuple as below in above code
logged_user_details=(username,passowrd)
and let
users_logged_in
be a list of usernames and passwords, Append to it the tuple created above.
users_logged_in.append(logged_user_details).
Now you would have users and passwords in your list as shown below and order of your entry will also be preserved.
[(User1,Password1),(User2,Password2),(User3,Password3)].
It is entirely dependent on your usage purpose of storing username and password whether you go with List or Dict approach.

Cant break out of login system

The login system i have wont break out of the loop. I have shown this to my CS teacher and he told me to change the indentations of the break. It didn't work. I have been looking around but I can't seem to find a reason as of why the loop wont break. Here is the code:
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
The code asks if the user has an account. When I input yes and give valid username and password, it continues with the loop. For context when the user logins in, it says welcome and breaks out of the loop. However this isn't happening, it is instead saying welcome and restarting the loop. The csv for this contains the login details.
Any help as of why the loop wont break will be greatly appreciated.
Dylan
Something like this? I mean you already have a "loggedin" variable, why not use it in the while loop...
loggedin = False
while not loggedin:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1 and row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
You are missing a break.
You break out of the for loop, but never the while loop.
Try this:
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
if loggedin==True:
break
EDIT:
Personally, i would avoid using a while True and instead do something like this:
loggedin = False
while not loggedin:
print("User 1") # Consider moving this outside of the while loop too
login=input("Do you have an account? (yes/no) ")
if login.lower() == "yes":
login1=open("login.csv") # Consider moving this outside of the while loop too
reader = csv.reader(login1) # Consider moving this outside of the while loop too
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1 and row[1]==password1:
print("Welcome " + username1)
loggedin = True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
Note here that the continue is not needed.

How do I make my code loop properly in python?

My goal is to make sure when the user types in numbers in the userName input, then it should not accept it and make them try again.
Same thing with userNumber. When a user types in letters, they should be prompted with another line telling them to try again.
The problem is that when they do type in the correct input, the program will continue looping and listing the numbers indefinitely.
I'm new to coding, and I'm trying to figure out what I'm doing wrong. Thank you in advance!
userName = input('Hello there, civilian! What is your name? ')
while True:
if userName.isalpha() == True:
print('It is nice to meet you, ' + userName + "! ")
else:
print('Choose a valid name!')
userNumber = input('Please pick any number between 3-100. ')
while True:
if userNumber.isnumeric() == True:
for i in range(0,int(userNumber) + 1,2):
print(i)
else:
print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
You never stop the loop. There's two ways to do this: either change the loop condition (while true loops forever), or break out from within.
In this case, it's easier with break:
while True:
# The input() call should be inside the loop:
userName = input('Hello there, civilian! What is your name? ')
if userName.isalpha(): # you don't need `== True`
print('It is nice to meet you, ' + userName + "! ")
break # this stops the loop
else:
print('Choose a valid name!')
The second loop has the same problem, with the same solution and additional corrections.
Alternative way: use a condition in your while loops.
userName = ''
userNumber = ''
while not userName.isalpha():
if userName: print('Choose a valid name!')
userName = input('Hello there, civilian! What is your name? ')
print('It is nice to meet you, ' + userName + "! ")
while not userNumber.isnumeric():
if userNumber: print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
for i in range(0,int(userNumber) + 1,2):
print(i)

Categories

Resources