Python3 with Loop function / password exit? - python-3.x

I'm new to Python and need a little help. I came across this code on here which I kind of understand and want to expand on it... but I don't know how to get out of the loop!
When you run the code and enter the specified username and password, it runs the defined function logged()... but then loops back to asking for the username again because it run the main() function again!... how can I get past this. When the correct username & password is entered, I would like to be at a point where I can add new code! Does this make sense?
import os
import time
#Must Access this to continue.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()

When all matches, break out of loop and call logged outside the loop. Or else once the logged is over, you return back to the infinite loop again.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
break
else:
print ("Password did not match!")
logged()

Related

Why does my program print "invalid Username or Password" when it's correct

I have tried many different imputs but they all say print "Invalid". I would appreciate if anyone can explain or edit my code so i can understand.
username = []
password = []
def account_creation():
account = input("Would you like to make an Account? Yes or No: ")
if account == "Yes" or "yes":
username = input("Please make a Username: ")
password = input("Please make a Password: ")
else:
return
account_creation()
def login():
account = input("Do you have an Account? Yes or No: ")
if account == "Yes":
login_username = input("Plese enter your username: ")
login_password = input("Plese enter your password: ")
else:
return
if login_username and login_password == username and password:
print("Welcome back")
else:
print("Invalid Username or Password")
login()
you need to first check you username-password check line (as _venky stated):
...
if login_username == username and login_password == password:
...
but you have something more important missing here.
you are trying to change global variables inside a function, thus you need global keyword with related variables in the function body.
def account_creation():
global username,password
account = ... the rest of the code

Python code [Code loops]

Hello am very new to python and ive atempted my first code like this but something seems to be wrong and one of the steps keeps looping. I am very confused on what to do so could someone please help me out.
Thank you!
import os
import time
def main():
while True:
print("Welcome To Amazon")
search = input("Search.... ")
if 'search == registration':
reg()
if 'search == login':
login()
#Must Register to continue
def reg():
while True:
print("Display Name")
reg_user = input()
print("Password")
reg_pass = input()
def registered():
time.sleep(1)
print("Registration Successful!")
main()
#Must Login to continue
def login():
while True:
print("Enter Username: ")
username = input()
print("Enter Password: ")
password = input()
if 'username == reg_user' and 'password == reg_pass':
time.sleep(1)
print("Login Successful!")
logged()
else:
print("Try Again!")
def logged():
time.sleep(1)
print("Welcome To CityRP Gaming")
main()
The while loop loops for as long as the condition is true. You used While True, and True will always be True. This means the loop will continue forever. To break out of a loop you can use 'break'.

Why doesnt the password work when I enter it?

import sys
import string
import time
password = "1234"
guess = " "
count = 0
def bank():
print("TKS Bank")
print("Enter your pin below to access your TKS Bank account")
print()
def password():
global password
global guess
global count
while count != 3 and guess != password:
guess = input("Please enter your 4 digit pin: ")
count += 1
if guess == password:
menu()
elif count == 3:
print("Number of tries maxed.")
countdown()
count = 0
else:
print("Your pin is denied, Try again")
def menu():
print("Your pin has been approved")
print("_" * 80)
print("Welcome to the TKS Bank")
print("_" * 80)
print("1. Type 1 to check your account balance")
print("2. Type 2 to to deposit a chosen amount")
print("3. Type 3 to withdraw a chosen amount")
print("4. Type 4 to check your simple interest")
print("5. Type 5 to exit the menu")
print("_" * 80)
def balance():
balance = (random.randint(1,1000))
print("$", balance)
#'sys' imports the system library from the python library
def quit():
os.exit(0)
def countdown():
print("You have been locked out for 3 minutes. Please come back later
and try again")
time.sleep(3)
bank()
password()
When I have the countdown function the password does not work and just continually loops. Does anyone have a fix?
To expand with the countdown function when I input the correct password it says that it is incorrect and goes to the countdown after three tries. I really don't know what the solution is so anyone help would be appreciated.
Inside your def password(): function, there's an ambiguous name usage between password the variable and password the function.

Running python on server, executing commands from computer

I made a login system with python. It works perfectly, but i want to run script on server or web. For example: Steam. Steam wants username and password to log in. So i wanted to do the same for my script. How can i do that?
My Code:
import os
import string
import time
version = "1.0 Alfa"
def login():
print ("----------------------------------------")
print (" Login ")
print ("----------------------------------------")
k_name = input("Enter username: ")
if os.path.exists(k_name + ".txt") == False:
print ("Username not found.")
create()
else:
k_pass = input("Enter password: ")
with open(k_name + ".txt", "r") as f:
if k_pass == f.read():
print("Welcome %s!"%k_name)
f.close()
input()
else:
print("Password is wrong!")
create()
def create():
print("You using login system %s" % version)
print( "----------------------------------------")
print("| Lobby |")
print( "----------------------------------------")
starting = input("To create user type R, to login type L").upper()
if starting == "R":
name = input("Enter username: ")
password = input("Enter password: ")
password2 = input("Enter password again: ")
if password == password2:
newfile = open(name + ".txt", "w")
newfile.write(password)
newfile.close()
print("User created. Redirecting you to login.")
time.sleep(2)
login()
elif password != password2:
print("Passwords doesn't match.")
input()
create()
elif starting == "L":
login()
else:
print("\nWrong button\n")
create()
create()
Here is the script which you can run : python test.py user pass
it will save data if file not found and perform login
#!/usr/bin/env python
import sys, getopt
import os
import time
version = "1.0 Alfa"
def login(username=None, password=None):
print ("----------------------------------------")
print (" Login ")
print ("----------------------------------------")
if username:
k_name = username
else:
k_name = input("Enter username: ")
if os.path.exists(k_name + ".txt") == False:
print ("Username not found.")
create(username, password, "R")
else:
if password:
k_pass = password
else:
k_pass = input("Enter password: ")
with open(k_name + ".txt", "r") as f:
if k_pass == f.read():
if not username:
print("Welcome %s!"%k_name)
f.close()
input()
else:
print("Password is wrong!")
create()
def create(username=None, password=None, mode="L"):
print("You using login system %s" % version)
print( "----------------------------------------")
print("| Lobby |")
print( "----------------------------------------")
if mode:
starting = mode
else:
starting = input("To create user type R, to login type L").upper()
if starting == "R":
if username:
name = username
else:
name = input("Enter username: ")
if password:
password2 = password
else:
password = input("Enter password: ")
password2 = input("Enter password again: ")
if password == password2:
newfile = open(name + ".txt", "w")
newfile.write(password)
newfile.close()
print("User created. Redirecting you to login.")
time.sleep(2)
login(username, password)
elif password != password2:
print("Passwords doesn't match.")
input()
create()
elif starting == "L":
login(username, password)
else:
print("\nWrong button\n")
create()
def main(argv):
print sys.argv
if len(sys.argv) < 3:
print 'test.py <username> <password>'
sys.exit()
username = sys.argv[1]
password = sys.argv[2]
print 'username is ', username
print 'password is ', password
create(username, password)
if __name__ == "__main__":
main(sys.argv[1:])

Error writing text into a .txt file in python

I am making a program that will
1. Create a text file
2. Allow a password to be stored
3. Allow a password to be changed
4. Add an additional password
5. Delete a specific password
The problem is in def delete():. I put in three passwords on three seperate lines: first, second, third. When I choose to delete password "second", it reprints the list from before, and then prints the new list at the end of the last password.
Here is my code:
import time
def create():
file = open("password.txt", "w")
passwordOfChoice = input("The password you want to store is: ")
file.write(passwordOfChoice)
print ("Your password is: ", passwordOfChoice)
file.close()
time.sleep(2)
def view():
file = open("password.txt","r")
print ("Your password is: ",
"\n", file.read())
file.close()
time.sleep(2)
def change():
file = open("password.txt", "w")
newPassword = input("Please enter the updated password: ")
file.write(newPassword)
print ("Your new password is: ", newPassword)
file.close()
time.sleep(2)
def add():
file = open("password.txt", "a")
extraPassword = input("The password you want to add to storage is: ")
file.write("\n")
file.write(extraPassword)
print ("The password you just stored is: ", extraPassword)
file.close()
time.sleep(2)
def delete():
phrase = input("Enter a password you wish to remove: ")
f = open("password.txt", "r+")
lines = f.readlines()
for line in lines:
if line != phrase+"\n":
f.write(line)
f.close()
print("Are you trying to: ",
"\n1. Create a password?",
"\n2. View a password?",
"\n3. Change a previous password?",
"\n4. Add a password?",
"\n5. Delete a password?",
"\n6. Exit?\n")
function = input()
print("")
if (function == '1'):
create()
elif (function == '2'):
view()
elif (function == '3'):
change()
elif (function == '4'):
add()
elif (function == '5'):
delete()
elif (function == '6'):
print("Understood.", "\nProgram shutting down.")
time.sleep(1)
else:
print("Your answer was not valid.")
print("Program shutting down...")
time.sleep(1)
To show what I meant above, here is my output:
Your password is:
first
second
thirdfirst
third
Can someone please tell me how to fix my def delete(): function so that it will not rewrite the original data? Thanks a ton!
The problem lies with the 'r+' mode. When you use 'r+' you can read and write, sure, but it's up to you to control where in the file you write.
What's happening is you read the file, and the cursor is stuck at the end, so when you write it back, Python dutifully puts your new lines on the end of the file.
See the docs about file methods; you're looking for something like seek.

Resources