How do i make a registration form whic stores useres data in .txt file in python? - forms

I am working on a project which I am spouse to create a Bank system using python. I have done the program and it works perfectly the only problem that I need help with is that how to create a registration form which will store user data for sign up, and read data for login from a txt file.
=
balance = 100
def log_in():
tries = 1
allowed = 5
value = True
while tries < 5:
print('')
pin = input('Please Enter You 4 Digit Pin: ')
if pin == '1234':
print('')
print(" Your Pin have been accepted! ")
print('---------------------------------------------------')
print('')
return True
if not len(pin) > 0:
tries += 1
print('Username cant be blank, you have,',(allowed - tries),'attempts left')
print('')
print('---------------------------------------------------')
print('')
else:
tries += 1
print('Invalid pin, you have',(allowed - tries),'attempts left')
print('')
print('---------------------------------------------------')
print('')
print("To many incorrect tries. Could not log in")
ThankYou()
def menu():
print (" Welcome to the Python Bank System")
print (" ")
print ("Your Transaction Options Are:")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Deposit Money")
print ("2) Withdraw Money")
print ("3) Check Balance")
print ("4) Quit Python Bank System.pyw")
def option1():
print (' Deposit Money' )
print('')
print("Your balance is £ ",balance)
Deposit=float(input("Please enter the deposit amount £ "))
if Deposit>0:
forewardbalance=(balance+Deposit)
print("You've successfully deposited £", Deposit, "into your account.")
print('Your avalible balance is £',forewardbalance)
print('')
print('---------------------------------------------------')
service()
else:
print("No deposit was made")
print('')
print('---------------------------------------------------')
service()
def option2():
print (' Withdraw Money' )
print('')
print("Your balance is £ ",balance)
Withdraw=float(input("Enter the amount you would like to Withdraw £ "))
if Withdraw>0:
forewardbalance=(balance-Withdraw)
print("You've successfully withdrawed £",Withdraw)
print('Your avalible balance is £',forewardbalance)
if Withdraw >= -100:
print("yOU ARE ON OVER YOUR LIMITS !")
else:
print("None withdraw made")
def option3():
print("Your balance is £ ",balance)
service()
def option4():
ThankYou()
def steps():
Option = int(input("Enter your option: "))
print('')
print('---------------------------------------------------')
if Option==1:
option1()
if Option==2:
option2()
if Option==3:
option3()
if Option==4:
option4()
else:
print('Please enter your option 1,2,3 or 4')
steps()
def service():
answer = input('Would you like to go to the menu? ')
answercov = answer.lower()
if answercov == 'yes' or answercov == 'y':
menu()
steps()
else:
ThankYou()
def ThankYou():
print('Thank you for using Python Bank System v 1.0')
quit()
log_in()
menu()
steps()
I expect my program to have a registration form which will store user data for sign up and read data for login from a .txt file.

So I looked a bit on it, and tried to do it with a .txt file.
So, in the same folder as the .py file, create the data.txt file like this one:
1234 1000.0
5642 500
3256 50.0
6543 25
2356 47.5
1235 495
1234 600000
The PIN and the balance are separated by a tabulation.
Then in the code, first step is to use global variable to pass on both the PIN number, the balance, and the path to the data file. Then, the data file is open, and the balance and pin are placed into 2 lists.
If you want to work with a dataframe, for instance panda, a dictionnary structure would be more relevant.
# Create the global variable balance and pin that will be used by the function
global balance
global pin
# Path to the data.txt file, here in the same folder as the bank.py file.
global data_path
data_path = 'data.txt'
data = open("{}".format(data_path), "r")
# Create a list of the pin, and balance in the data file.
pin_list = list()
balance_list = list()
for line in data.readlines():
try:
val = line.strip('\t').strip('\n').split()
pin_list.append(val[0])
balance_list.append(val[1])
except:
pass
# Close the data file
data.close()
""" Output
pin_list = ['1234', '5642', '3256', '6543', '2356', '1235', '1234']
balance_list = ['1000', '500', '-20', '25', '47.5', '495', '600000']
"""
Then, every function modifying the balance need to change the global variable value. For instance:
def log_in():
global balance
global pin
tries = 1
allowed = 5
while tries < 5:
pin = input('\nPlease Enter You 4 Digit Pin: ')
if pin in pin_list:
print('\n Your Pin have been accepted! ')
print('---------------------------------------------------\n')
balance = float(balance_list[pin_list.index(pin)])
menu()
else:
tries += 1
print('Wrong PIN, you have {} attempts left.\n'.format(allowed - tries))
print('---------------------------------------------------\n')
print('To many incorrect tries. Could not log in.')
ThankYou()
Or:
def option1():
global balance
print (' Deposit Money\n')
print('Your balance is £ {}'.format(balance))
deposit = float(input('Please enter the deposit amount £ '))
if deposit > 0:
balance = balance + deposit
print("You've successfully deposited £ {} into your account.".format(deposit))
print('Your avalible balance is £ {}\n'.format(balance))
print('---------------------------------------------------')
service()
else:
print('No deposit was made. \n')
print('---------------------------------------------------')
service()
Others sources of improvement:
Instead of print ('') to skip a line, simply add '\n' to the printed string.
Use 'blabla {}...'.format(value to put in {}) to place values, or str, or whatever in the middle of a str. It's good to use it since you will be able to place multiple values in the same string. Illustration in the saving data part bellow.
Finally, the new balance must be save in the .txt file. This will be done in the Thank you function:
def ThankYou():
global balance
global pin
global data_path
balance_list[pin_list.index(pin)] = balance
data = open("{}".format(data_path), "w")
for i in range(len(pin_list)):
line = '{}\t{}\n'.format(str(pin_list[i]), str(balance_list[i]))
data.write(line)
data.close()
print('Thank you for using Python Bank System v 1.0')
quit()
I hope you get the idea, and can manage on your own the code modifications, you should have every key to do it.
Good luck !

Related

Why is my program not scanning and outputting the text file properly?

I'm currently having trouble with my text file. When I run my program, it is supposed to print the students on academic warning, but when I run it, it only prints the header and does not scan the text file. Is this a problem with my Netbeans or with my program?
Here is the program assignment in more detail:
Write a program that will read in a file of student academic credit data and create a list of students on academic
warning. The list of students on warning will be written to a file. Each line of the input file will contain the
student name (a single String with no spaces), the number of semester hours earned (an integer), the total
quality points earned (a double). The following shows part of a typical data file:
Smith 27 83.7
Jones 21 28.35
Walker 96 182.4
Doe 60 150
The program should compute the GPA (grade point or quality point average) for each student (the total quality
points divided by the number of semester hours) then write the student information to the output file if that
student should be put on academic warning. A student will be on warning if he/she has a GPA less than 1.5 for
students with fewer than 30 semester hours credit, 1.75 for students with fewer than 60 semester hours credit,
and 2.0 for all other students. The file Warning.java contains a skeleton of the program. Do the following:
Set up a Scanner object scan from the input file and a PrintWriter outFile to the output file inside the try
clause (see the comments in the program). Note that you’ll have to create the PrintWriter from a FileWriter,
but you can still do it in a single statement.
Inside the while loop add code to read and parse the input—get the name, the number of credit hours, and
the number of quality points. Compute the GPA, determine if the student is on academic warning, and if so
write the name, credit hours, and GPA (separated by spaces) to the output file.
After the loop close the PrintWriter.
Think about the exceptions that could be thrown by this program:
• A FileNotFoundException if the input file does not exist
• A NumberFormatException if it can’t parse an int or double when it tries to - this indicates an error in
the input file format
• An IOException if something else goes wrong with the input or output stream
Add a catch for each of these situations, and in each case give as specific a message as you can. The program
will terminate if any of these exceptions is thrown, but at least you can supply the user with useful information.
Test the program. Test data is in the file students.dat. Be sure to test each of the exceptions as well.
Code:
package Chapter11LabProgram;
import java.util.*;
import java.io.*;
public class Warning
{
// --------------------------------------------------------------------
// Reads student data (name, semester hours, quality points) from a
// text file, computes the GPA, then writes data to another file
// if the student is placed on academic warning.
// --------------------------------------------------------------------
public static void main(String[] args) {
int creditHrs; // number of semester hours earned
double qualityPts; // number of quality points earned
double gpa; // grade point (quality point) average
String line, name, inputName = "/Users/Downloads/students.dat.txt";
String outputName = "/Users/Downloads/students.dat.txt";
try {
// Set up scanner to input file
PrintWriter outFile = new PrintWriter(new FileWriter(outputName));
Scanner scan = new Scanner(new File(inputName));
// Set up the output file stream
// Print a header to the output file
outFile.println();
outFile.println("Students on Academic Warning");
outFile.println();
// Process the input file, one token at a time
while (scan.hasNext()) {
line = scan.nextLine();
creditHrs = Integer.parseInt(line.split("\\s+")[1]);
qualityPts = Double.parseDouble(line.split("\\s+")[2]);
gpa = qualityPts / creditHrs;
//outFile.print(line);
if (gpa < 1.5 && creditHrs < 30)
{
outFile.write(line + "\r\n");
}
else if (gpa < 1.75 && creditHrs < 60)
{
outFile.write(line + "\r\n");
}
else if (gpa < 2)
{
outFile.write(line + "\r\n");
}
//outFile.println ();
// Get the credit hours and quality points and
// determine if the student is on warning. If so,
// write the student data to the output file.
}
//outFile.println ("test");
outFile.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + inputName + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
} catch (NumberFormatException e) {
System.out.println("Format error in input file: " + e);
}
}
}
My text file:
Smith 27 83.7
Jones 21 28.35
Walker 96 182.4
Doe 60 150
Wood 100 400
Street 33 57.4
Taylor 83 190
Davis 110 198
Smart 75 2 92.5
Bird 84 168
Summers 52 83.2
Any help would be appreciated! Thank you!

How do I make Simpy simulation to depict a markovian M/M/1 process?

output printing the len of arrival and service timesI am trying to implement an M/M/1 markovian process with exponential inter arrival and exponential service times using simpy. The code runs fine but I dont quite get the expected results. Also the number of list items in arrival times is lesser than the number of list items in service time after the code is run.
# make a markovian queue
# make a server as a resource
# make customers at random times
# record the customer arrival time
# customer gets the resource
# record when the customer got the resource
# serve the customers for a random time using resource
# save this random time as service time
# customer yields the resource and next is served
import statistics
import simpy
import random
arrival_time = []
service_time = []
mean_service = 2.0
mean_arrival = 1.0
num_servers = 1
class Markovian(object):
def __init__(self, env, num_servers):
self.env = env
self.servers = simpy.Resource(env, num_servers)
#self.action = env.process(self.run())
def server(self,packet ):
#timeout after random service time
t = random.expovariate(1.0/mean_service)
#service_time.append(t)
yield self.env.timeout(t)
def getting_service(env, packet, markovian):
# new packet arrives in the system
arrival_time = env.now
with markovian.servers.request() as req:
yield req
yield env.process(markovian.server(packet))
service_time.append(env.now - arrival_time)
def run_markovian(env,num_servers):
markovian = Markovian(env,num_servers)
packet = 0
#generate new packets
while True:
t = random.expovariate(1.0/mean_arrival)
arrival_time.append(t)
yield env.timeout(t)
packet +=1
env.process(Markovian.getting_service(env,packet,markovian))
def get_average_service_time(service_time):
average_service_time = statistics.mean(service_time)
return average_service_time
def main():
random.seed(42)
env= simpy.Environment()
env.process(Markovian.run_markovian(env,num_servers))
env.run(until = 50)
print(Markovian.get_average_service_time(service_time))
print (arrival_time)
print (service_time)
if __name__ == "__main__":
main()
Hello there were basically one bug in your code and two queuing theory misconceptions:
Bug 1) the definition of the servers were inside the class, this makes the model behaves as a M/M/inf not M/M/1
Answer: I put the definition of your resources out the the class, and pass the servers not the num_servers from now on.
Misconception 1: with the times as you defined:
mean_service = 2.0
mean_arrival = 1.0
The system will generate much more packets and it is able to serve. That's why the size of the lists were so different.
Answer:
mean_service = 1.0
mean_arrival = 2.0
Misconception 2:
What you call service time in your code is actually system time.
I also put some prints in your code so we could see that is doing. Fell free to comment them. And there is no need for the library Statistics, so I commented it too.
I hope this answer is useful to you.
# make a markovian queue
# make a server as a resource
# make customers at random times
# record the customer arrival time
# customer gets the resource
# record when the customer got the resource
# serve the customers for a random time using resource
# save this random time as service time
# customer yields the resource and next is served
#import statistics
import simpy
import random
arrivals_time = []
service_time = []
waiting_time = []
mean_service = 1.0
mean_arrival = 2.0
num_servers = 1
class Markovian(object):
def __init__(self, env, servers):
self.env = env
#self.action = env.process(self.run())
#def server(self,packet ):
#timeout after random service time
# t = random.expovariate(1.0/mean_service)
#service_time.append(t)
# yield self.env.timeout(t)
def getting_service(env, packet, servers):
# new packet arrives in the system
begin_wait = env.now
req = servers.request()
yield req
begin_service = env.now
waiting_time.append(begin_service - begin_wait)
print('%.1f Begin Service of packet %d' % (begin_service, packet))
yield env.timeout(random.expovariate(1.0/mean_service))
service_time.append(env.now - begin_service)
yield servers.release(req)
print('%.1f End Service of packet %d' % (env.now, packet))
def run_markovian(env,servers):
markovian = Markovian(env,servers)
packet = 0
#generate new packets
while True:
t = random.expovariate(1.0/mean_arrival)
yield env.timeout(t)
arrivals_time.append(t)
packet +=1
print('%.1f Arrival of packet %d' % (env.now, packet))
env.process(Markovian.getting_service(env,packet,servers))
def get_average_service_time(service_time):
average_service_time = statistics.mean(service_time)
return average_service_time
def main():
random.seed(42)
env= simpy.Environment()
servers = simpy.Resource(env, num_servers)
env.process(Markovian.run_markovian(env,servers))
env.run(until = 50)
print(Markovian.get_average_service_time(service_time))
print ("Time between consecutive arrivals \n", arrivals_time)
print("Size: ", len(arrivals_time))
print ("Service Times \n", service_time)
print("Size: ", len(service_time))
print ("Waiting Times \n", service_time)
print (waiting_time)
print("Size: ",len(waiting_time))
if __name__ == "__main__":
main()

Importing two text files to compare as lists sequentially

Student trying to compare two .txt files of string "answers" from a multiple choice test a,c,d,b, etc. I've found some information on different parts of the problems I'm having and found a possible way to get the comparisons I want, but the guide was meant for in script strings and not pulling a list from a file.
For the import of the two files and comparing them, I'm basing my code on my textbook and this video here: Video example
I've got the code up and running, but for some reason I'm only getting 0.0% match when I want to a 100.0% match, at least for the two text files I'm using with identical answer lists.
import difflib
answer_sheet = "TestAnswerList.txt"
student_sheet = "StudentAnswerList.txt"
ans_list = open(answer_sheet).readlines()
stu_list = open(student_sheet).readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=ans_list, b=stu_list)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match")
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# not the crux of my issue, but will accept advice all the same
answer_sheet.close
student_sheet.close
If I add in the close statement at the end for both of the text files, then I receive this error:
Traceback (most recent call last): File
"c:/Users/jaret/Documents/Ashford U/CPT 200/Python Code/Wk 5 Int Assg
- Tester code.py", line 18, in
answer_sheet.close AttributeError: 'str' object has no attribute 'close'
I had to re-look at how my files were being opened and realized that the syntax was for Python 2 not 3. I chose to go w/ basic open and later close to reduce any potential errors on my novice part.
import difflib
f1 = open('TestAnswerList.txt')
tst_ans = f1.readlines()
f2 = open('StudentAnswerList.txt')
stu_ans = f2.readlines()
sequence = difflib.SequenceMatcher(isjunk=None, a=stu_ans, b=tst_ans)
check_list = sequence.ratio()*100
check_list = round(check_list,1)
print(str(check_list) + "% match") # Percentage correct
if check_list == 100:
print('This grade is Plus Ultra!')
elif check_list >= 75:
print('Good job, you pass!')
else:
print('Please study harder for your next test.')
# Visual Answer match-up
print('Test Answers: ', tst_ans)
print('Student Answers:', stu_ans)
f1.close()
f2.close()

How can I take my captured information from a network/port scan and write that to a file?

I wrote an IP and port scanning program and I want to take the captured data and output it to a text file. I've been trying to figure it out for a while and haven't had any luck applying what I can find in searches. At the end, I commented out how I thought it should work to write the information to a file.
Any help or suggestions would be greatly appreciated, I'm still somewhat new to Python and trying to learn.
#!/usr/bin/env python
import ipaddress
import sys, time
import os
import subprocess
import socket
from datetime import datetime
FNULL = open(os.devnull, 'w')
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print ('Welcome to the IP/Port Scanner and Logger')
address = input('Enter starting IP address: ')
split1 = first,second,third,fourth = str(address).split('.')
start = int(fourth)
host = first+'.'+second+'.'+third+'.'+str(start)
end_address = input('Enter the ending IP address: ')
split2 = first,second,third,fourth = str(end_address).split('.')
end = int(fourth)
network = first+'.'+second+'.'+third+'.'
min_port = input("Enter starting port range: ")
max_port = input("Enter ending port range: ")
remoteserver = host
remoteserverIP = socket.gethostbyname(remoteserver)
def port_scan():
print ('Port scanning function initialized:')
try:
for port in range(int(min_port),int(max_port)):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteserverIP, port))
if result == 0:
print ('Port ' + str(port) + ': Open')
sock.close()
except KeyboardInterrupt:
print ("You halted the process")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Couldn't connect to server")
sys.exit()
return port
def check_up():
for ip_address in range(int(start), int(end)):
try:
subprocess.check_call(['ping', '-c', '2',
network + str(ip_address)],
stdout=FNULL,stderr=FNULL)
except (OSError, subprocess.CalledProcessError):
print ("{}{}".format(network,ip_address), "is down")
except KeyboardInterrupt:
print ("You halted the process")
sys.exit()
else:
print ("{}{}".format(network,ip_address), "is up")
return ip_address
check_up()
time1 = datetime.now()
time2 = datetime.now()
scantime = time2-time1
print ('Scan completed in: ', scantime)
while True:
print ('Would you like to write information to file?')
answer = input()
if answer in ['yes', 'y', 'yeah']:
print ('Alright, writing to file')
print ('Program will exit upon scan completion.')
break
elif answer in ['no', 'n']:
print ('Okay, exiting now..')
sys.exit()
break
else:
print ('Please enter a yes or no value')
###Output File
##with open('ipscan.txt', 'w+') as ip:
## print (ip_address, port)
##
##sys.exit()

How to save names in a Qbasic file?

I am trying to create a program in Qbasic wherein a person can enter their name and label themselves as admin or unwanted user. How do I save these preferences in my program?
If you have inputed the username with something like,
INPUT "Type your username: ", uName$
To save it to a file, simply use these commands:
OPEN "User.dat" FOR OUTPUT AS #1
PRINT #1, uName$
CLOSE #1
Here's a complete program:
DEFINT A-Z
'Error handler for the first time we run the program. The data file won't exist, so we create it.
ON ERROR GOTO FileNotExist
'Create a type and an Array of users that would include Username and the Status (adminstrator vs. Unwanted user)
TYPE user
Uname AS STRING * 16
Status AS STRING * 1
END TYPE
DIM Users(1 TO 100) AS user
'Gets all the users stored in the file. i is a variable which represents the number of users before adding a new user
i = 0
OPEN "User.txt" FOR INPUT AS #1
WHILE NOT EOF(1)
i = i + 1
INPUT #1, Users(i).Uname
INPUT #1, Users(i).Status
WEND
CLOSE #1
TryAgain:
'Gets info for the new user
CLS
INPUT "User name: ", Users(i + 1).Uname
PRINT "Admin (a), Unwanted user (u), or Regular user (r) ?"
Users(i + 1).Status = LCASE$(INPUT$(1))
'Ensure there are no blank lines in the file
IF Users(i + 1).Uname = "" OR Users(i + 1).Status = "" THEN GOTO TryAgain
'Outputs user data to the file "User.txt"
OPEN "User.txt" FOR OUTPUT AS #1
FOR j = 1 TO i + 1
PRINT #1, Users(j).Uname
PRINT #1, Users(j).Status
NEXT j
CLOSE #1
'Just for a closer: Prints all the current users.
CLS
FOR j = 1 TO i + 1
PRINT Users(j).Uname,
IF Users(j).Status = "a" THEN PRINT "Amdinistrator" ELSE IF Users(j).Status = "u" THEN PRINT "Unwanted User" ELSE IF Users(j).Status = "r" THEN PRINT "Regular user" ELSE PRINT Users(j).Status
NEXT j
END
'*** ERROR HANDLER: ***
FileNotExist:
OPEN "User.txt" FOR OUTPUT AS #1
CLOSE
RESUME
To save a name into a file, you will need to use the WRITE statement.
Eg:
OPEN "Name.txt" FOR OUTPUT AS #1
INPUT"Enter a name";a$
WRITE #1,a$
CLOSE #1
END