How do I run while loop that appends a text file? - python

I'm a beginner trying to do a short learning exercise where I repeatedly prompt users for their name and save those names to guest_book.txt, each name in a new line. So far, while loops are always giving me trouble to get them working properly.
In this case, the program ends when I enter the first name, here's the code:
"""Prompt users for their names & store their responses"""
print("Enter 'q' to quit at any time.")
name = ''
while True:
if name.lower() != 'q':
"""Get and store name in guestbook text file"""
name = input("Can you tell me your name?\n")
with open('guest_book.txt', 'w') as guest:
guest.write(name.title().strip(), "\n")
"""Print greeting message with user's name"""
print(f"Well hello there, {name.title()}")
continue
else:
break
It runs perfectly when I omit the with open() block.

In a more pythonic way:
with open('guest_book.txt', 'w') as guest:
while True:
# Prompt users for their names & store their responses
name = input("Can you tell me your name?\n")
if name.lower() == 'q':
break
# Get and store name in guestbook text file
guest.write(f"{name.title().strip()}\n")
# Print greeting message with user's name
print(f"Well hello there, {name.title()}")
Can you tell me your name?
Louis
Well hello there, Louis
Can you tell me your name?
Paul
Well hello there, Paul
Can you tell me your name?
Alex
Well hello there, Alex
Can you tell me your name?
q
>>> %cat guest_book.txt
Louis
Paul
Alex

First try to read an error which was shown by Python.
TypeError: write() takes exactly one argument (2 given)
Next you answer a name after if state. I make some changes with your code and move open to begin of code (and thanks to Corralien for review):
print("Enter 'q' to quit at any time.")
with open('guest_book.txt', 'w') as file:
while True:
name = input("Can you tell me your name?").title().strip()
if name.lower() == 'q':
break
if name:
file.write('{}\n'.format(name))
print('Well hello there, {}'.format(name))

Related

new project :: adv. contactbook , but i am facing some issues

i am a beginner at python , i was working with this project from a long time.
in this project the user should be able to create different account . and the account username and password should be kept in .txt file. then when the user wish they can create a contact book and then write some contact details. the user should also open the contact book whenever they want. but i am getting of error . so could somebody help me.
this is the codes --
name=(user2+".txt")
contact_book=open(name,"a")
contact_book.write("\n")
option=input("hello,do you want to save a new contact:(yes/no) ")
space=(" ")
def openbook():
option=input("do you want to open the contacts (yes/no)")
if option == ("yes"):
openfile=open(name,"r")
print(space)
openfile=openfile.read()
print(openfile)
contact_book.close()
def book():
print("ok")
name=input("what is the name?: ")
print(space)
phone=input("what is the phone number?: ")
print(space)
address=input("what is the address?: ")
contact_book.write("\n")
contact_book.write(name+" "+phone+" "+address)
contact_book.write("\n")
print("ok,done")
print(space)
contact_book.close()
option1=input("do you want to save a new contact:(yes/no)")
while option1==("yes"):
book()
if option1==("no"):
openbook()
x=2
while x==2:
if option==("yes"):
book()
delete=input("do you want to delete the contact book!! (yes/no)")
if delete == ("yes"):
os.remove(name)
if option ==("no"):
openbook()
delete=input("do you want to delete the contact book!! (yes/no)")
if delete == ("yes"):
os.remove(name)
if delete==("no"):
print("ok")
input("")
if delete == ("yes"):
os.remove(name)
x=x-2

Python If Statement question login system easy

The first thing to do is write "1" and then enter username and password. After that, the max number of account is 1 and you can then use the "2" to login.
First time asking a question so I am sorry if this is like a dumb question or something. My code is as following:
https://imgur.com/a/dAaYf2u - NEW LINK
Code:
print("Type 1 for Create user. Type 2 for login")
Choice = input("Number here: ")
if Choice == ("1"):
print("Welcome to the Create a user interface")
Username = input("Username: ")
Password = input("Password: ")
if Password.count("!") > 0:
print("Not valid - no special characters!")
else:
file = open("account.txt", "w")
file.write(Username)
file.write("\n")
file.write(Password)
file.close()
elif Choice == ("2"):
print("Welcome, please type your Username and Password")
Loginu = input("Write username here: ")
Loginp = input("Write password here: ")
file = open("account.txt", "r")
first_line = file.readline()
if Loginu == first_line:
print("you're logged in")
else:
print("fail")
It's very basic and so on. What I don't understand is why the if Loginu == first_line can't read the first_line variable... It just jumps directly to else:
I hope it helps and I know my code is very basic lol.
My advice:
follow pep8, use meaningful names for variables
split your code into functions
use infinite loop for your "menu"
even better use some package that helps with building such applications (click?) rather then reinvent the wheel
Read your file with with open(...) as f: context manager
It's probably good idea to read whole file and build dictionary instead of depending on the login to be exactly identical with first line
use strip() to remove white characters (like newline)
check that line you are looking at is not empty
if you've opened file without context manager for writting, you need to close it before opening it again for reading
use debugger to check what's exactly result of readline

Issue with referencing a global variable within a function

This is further to an issue I asked about on here yesterday What is the best way to validate user input against the contents of a list?). I got a good suggestion using a function like so:
getuser = input("Please enter your username :")
print("1. render_device")
print("2. audit_device")
askuser = input("Would you like to render_device or audit_device? : ")
def verify_input(sites_set):
get_site_name = input("Please enter the site name you'd like to render :")
if get_site_name in sites_set:
print('Proceed')
return
else:
print('Not in either list, please enter a valid site')
verify_input(sites_set)
if askuser == "1":
sites_2017 = ["bob", "joe", "charlie"]
sites_2018 = ["sarah", "kelly", "christine"]
verify_input(set(sites_2017 + sites_2018))
This works correctly within the function and when it is called. However, the issue is that I need get_site_name as a global variable since its input is referenced later in the script (not in a function). When I make get_site_name global, the function can reference it and works correctly when a valid site is input, but when an invalid site is input it just keeps looping the "Not in either list" error over and over, probably because the raw_input in the get_site_name variable isn't defined locally.
What would be the best way to remedy this?
What about:
def verify_input(sites_set):
while get_site_name not in sites_set:
get_site_name = input("Please enter the site name you'd like to render :")
print('Proceed')
return

How to create a python dictionary that will store the username and password for multiple accounts

The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.
Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).
import pickle
import time
def loaddict():
try:
with open("dictAcc.txt", "rb") as pkf:
return pickle.load(pkf)
except IOError:
with open("dictAcc.txt", "w+") as pkf:
pickle.dump(dict(), pkf)
return dict()
def savedict(dictAcc):
with open("dictAcc.txt", "wb") as pkf:
pickle.dump(dictAcc, pkf)
def userPass():
dictAcc = loaddict() #Load the dict
checkAccount = raw_input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = raw_input("Please Set Your New Username: ")
password = raw_input("Please Set Your New Password: ")
if (userName in dictAcc):
print("Username is taken")
userPass()
else:
dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
savedict(dictAcc) #Save the dict
time.sleep(1.5)
# dataInput() Code ends
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = raw_input("Type in your Username: ")
loginPass = raw_input("Type in your Password: ")
dictAcc = loaddict() #Load the dict
if (tries < 3):
for key in dictAcc:
if (loginUserName == key and loginPass == dictAcc[key]):
print("You have successfully logged in!")
# dataInput() Code ends
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(3)
tries=1 #To restart the tries counter
login()
global tries
tries=1
userPass()
There are different ways to do this. I'll mention two.
As you noticed, all variables created by your program are erased when the program finishes executing.
One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.
However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.
You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.
How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.
Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.
So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.
A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.

Importing a function from a class in another file? [duplicate]

This question already has answers here:
How do I import other Python files?
(23 answers)
Why is Python running my module when I import it, and how do I stop it?
(12 answers)
Closed 6 months ago.
I'm writing a Python program for fun but got stuck trying to import a function from a class in another file. Here is my code:
#jurassic park mainframe
from random import randint
from sys import exit
from comm_system import Comm_system #the file i want to import from
class Jpark_mainframe(object):
def mainframe_home(self):
print "=====Welcome to the Jurassic Park Mainframe====="
print "==========Security Administration==============="
print "===========Communications Systems==============="
print "===============System Settings=================="
print "===================Quit========================="
prompt = raw_input("What would you like to do? ")
while prompt != "Quit":
if prompt == "Security Administration":
print "Please enter the 5-digit passcode:"
security_passcode = "%d%d%d%d%d" % (2, 0, 1, 2, randint(1, 2))
security_guess = raw_input(": ")
security_guesses = 0
while security_guess != security_passcode and security_guesses < 7:
print "Incorrect. Please enter the security passcode."
security_guesses += 1
security_guess = raw_input(": ")
if security_guess == security_passcode:
print "=========Security Administration======="
print "Area 1 Fences: Off"
print "Area 2 Fences: On"
print "Area 3 Fences: Off"
print "Velociraptor Compound: Off"
print "Lobby Security System: Off"
print "Entrance Facility System: Off"
print "To enable all systems, enter 'On'"
enable_security = raw_input(": ")
if enable_security == "On":
print "Systems Online."
if prompt == "System Settings":
print "You do not have access to system settings."
exit(0)
if prompt == "Communications Systems":
print "===========Communications Systems==========="
print "error: 'comm_link' missing in directories"
exit(0)
return Comm_system.run #this is where I want to return the
#the other file
the_game = jpark_mainframe()
the_game.mainframe_home()
I want to return a function called run() from a class in another file. When I import the file, it first runs the class with run() in it, then proceeds to run the original code. Why does this happen?
Here is the code from comm_system:
#communication systems
from sys import exit
class Comm_system(object):
def run(self):
comm_directory = ["net_link", "tsfa_run", "j_link"]
print "When the system rebooted, some files necessary for"
print "communicating with the mainland got lost in the directory."
print "The files were poorly labeled as a result of sloppy"
print "programming on the staff's part. You must locate the"
print "the file and contact the rescue team before the dinosaurs"
print "surround the visitor's center. You were also notified the"
print "generators were shorting out, and the mainframe will lose"
print "power at any moment. Which directory will you search in?"
print "you don't have much time! Option 1: cd /comm_sys/file"
print "Option 2: cd /comm_sys/dis"
print "Option 3: cd /comm_sys/comm"
dir_choice = raw_input("jpark_edwin$ ")
if dir_choice == "/comm_sys/file" or dir_choice == "/comm_sys/dis":
print "misc.txt"
print "You couldn't locate the file!"
print "The system lost power and your computer shut down on you!"
print "You will not be able to reach the mainland until the system"
print "comes back online, and it will be too late by then."
return 'death'
if dir_choice == "/comm_sys/comm":
comm_directory.append("comm_link")
print comm_directory
print "You found the right file and activated it!"
print "Just in time too, because the computers shut down on you."
print "The phonelines are radios are still online."
print "You and the other survivors quickly call the mainlane"
print "and help is on the way. You all run to the roof and wait"
print "until the helocopter picks you up. You win!"
a_game = Comm_system()
a_game.run()
from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()
# if you want to return run itself to be used later
return theclass.run
Change the end of comm system to:
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
It's those lines being always run that are causing it to be run when imported as well as when executed.
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME
FILENAME is w/o the suffix
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
import myClass
or you can import the entire class and entire functions from the file. For example,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
Now you just use your function however it was meant to be.
Example:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
Hoped this helped, now you can create function packs for download!
--------------------------------This is for Python 2.7-------------------------------------
It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.
For example:
def run():
print "this does nothing"
def chooser():
return "run"
def main():
'''works just like:
run()'''
eval(chooser())()
The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.
You can use the below syntax -
from FolderName.FileName import Classname

Categories