how to check if the user exist in database list - python-3.x

After so many hours I still can't figure out how to check if the name and password user input exist in my data. For example, when I ask Please input customer name: and they input Sam than I ask again Please input customer password: and the input is janos i want customer_menu() function to be called. thanks
customers_list = []
class BankSystem(object):
def __init__(self):
self.customers_list = []
self.load_bank_data()
def load_bank_data(self):
customer_1 = Customer("Sam", "janos", ["14", "Wilcot Street", "Bath", "B5 5RT"])
account_no = 1234
account_1 = Account(5000.00, account_no)
customer_1.open_account(account_1)
self.customers_list.append(customer_1)
def customer_login(self, name, password):
if name in customers_list and password in customers_list:
self.name = name
self.password = password
self.customer_menu()
else:
print("sorry %s, it doesn't look like you are a customer"%name)
exit()
def main_menu(self):
print ("1) Customer login")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_main_option(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
name = input ("\nPlease input customer name: ")
password = input ("\nPlease input customer password: ")
msg = self.customer_login(name, password)
print(msg)
person.py
class Person(object):
def __init__(self, name, password, address = [None, None, None, None]):
self.name = name
self.password = password
self.address = address
def get_address(self):
return self.address
def update_name(self, name):
self.name = name
def get_name(self):
return self.name
def print_details(self):
print("Name %s:" %self.name)
print("Address: %s" %self.address[0])
print(" %s" %self.address[1])
print(" %s" %self.address[2])
print(" %s" %self.address[3])
print(" ")
def check_password(self, password):
if self.password == password:
return True
return False
def profile_settings_menu(self):
#print the options you have
print (" ")
print ("Your Profile Settings Options Are:")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Update name")
print ("2) Print details")
print ("3) Back")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_profile_options(self):
loop = 1
while loop == 1:
choice = self.profile_settings_menu()
if choice == 1:
name=input("\n Please enter new name\n: ")
self.update_name(name)
elif choice == 2:
self.print_details()
elif choice == 3:
loop = 0
customer.py
from person import Person
class Customer(Person):
def __init__(self, name, password, address = [None, None, None, None]):
super().__init__(name, password, address)
def open_account(self, account):
self.account = account
def get_account(self):
return self.account
def print_details(self):
super().print_details()
bal = self.account.get_balance()
print('Account balance: %.2f' %bal)
print(" ")

for customer in customers_list:
if customer.name == name:
if customer.password == password:
...

Related

Is it possible to change the output so that "Arlene" and "Klusman" don't have an extra set of parenthesis around them?

I'm writing code for an assignment where I can't change the main. The way I have it written, it prints like in the screenshot below:
Here is my code:
import csv
class Customer:
def __init__(self, cust_id, name, lastName, companyName, address, city, state, cust_zip):
self.cust_id = cust_id
self.first_name = name
self.last_name = lastName
self.company_name = companyName
self.address = address
self.city = city
self.state = state
self.zip = cust_zip
def getFullName(self):
return(self.first_name, self.last_name)
def getFullAddress(self):
return(self.getFullName(), self.company_name, self.address, self.city, self.state, self.zip)
def get_customers():
myList = []
counter = 0
with open("customers.csv", "r") as csv_file:
reader = csv.reader(csv_file, delimiter = ",")
for row in reader:
if counter!=0:
customer1 = Customer(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7])
myList.append(customer1)
counter+=1
return myList
def find_customer_by_id(customers, cust_id):
for i in range(len(customers)):
if cust_id == customers[i].cust_id:
return customers[i]
return None
def main():
#main is fully implemented with no modification expected
print("Customer Viewer")
print()
customers = get_customers()
while True:
cust_id = input("Enter customer ID: ").strip()
print()
customer = find_customer_by_id(customers, cust_id)
if customer == None:
print("No customer with that ID.")
print()
else:
print(customer.getFullAddress())
print()
again = input("Continue? (y/n): ").lower()
print()
if again != "y":
break
print("Bye!")
if __name__ == "__main__":
main()
Why are there parenthesis and, can you get rid of them?
I tried to different approaches but nothing changed the output in the intended way

Is there any command for calling a function in other function?

Here is my python code. I want to print the 1st function result in the 2nd function's print command in the bolded position. How can I do that?
def Position(self):
if self.is_sitting == True:
print ("sit down")
else:
print("stand up")
def introduce_person(self):
print("The person name is "+ self.name,"." +
"\nThe person's personality is "+
self.personality,".")
print("The person's position is " ,**self.Position()**)
Try this:
class person:
def __init__(self, *args):
self.name, self.personality, self.is_sitting = args
def Position(self):
if self.is_sitting == True:
return "sit down"
else:
return "stand up"
def introduce_person(self):
print("The person name is "+ self.name,"." + "\nThe person's. personality is "+ self.personality,".")
print("The person's position is " , self.Position())
obj=person('ali', 'ambitious', False)
obj.introduce_person()

Write a Python program to generate tickets for online bus booking, based on the class diagram given below

Initialize static variable counter to 0
validate_source_destination(): Validate source and destination. source must always be Delhi and destination can be either Mumbai, Chennai, Pune or Kolkata. If both are valid, return true. Else return false
generate_ticket():Validate source and destination. If valid, generate ticket id and assign it to attribute ticket_id. Ticket id should be generated with the first letter of source followed by first letter of destination and an auto-generated value starting from 01 (Ex: DM01, DP02,.. ,DK10,DC11). Else, set ticket_id as None.
Note: Perform case insensitive string comparison
For testing:
Create objects of Ticket class
Invoke generate_ticket() method on Ticket object
Display ticket id, passenger name, source, destination
In case of error/invalid data, display appropriate error message
class Ticket:
counter=0
def __init__(self,passenger_name,source,destination):
self.__passenger_name=passenger_name
self.__source=source
self.__destination=destination
self.Counter=Ticket.counter
Ticket.counter+=1
def validate_source_destination(self):
if (self.__source=="Delhi" and (self.__destination=="Pune" or self.__destination=="Mumbai" or self.__destination=="Chennai" or self.__destination=="Kolkata")):
return True
else:
return False
def generate_ticket(self ):
if True:
__ticket_id=self.__source[0]+self.__destination[0]+"0"+str(self.Counter)
print( "Ticket id will be:",__ticket_id)
else:
return False
def get_ticket_id(self):
return self.ticket_id
def get_passenger_name(self):
return self.__passenger_name
def get_source(self):
if self.__source=="Delhi":
return self.__source
else:
print("you have written invalid soure option")
return None
def get_destination(self):
if self.__destination=="Pune":
return self.__destination
elif self.__destination=="Mumbai":
return self.__destination
elif self.__destination=="Chennai":
return self.__destination
elif self.__destination=="Kolkata":
return self.__destination
else:
return None
when generate_ticket() method will give false condition I don't want to print ticket_id but in my code after the false statement the ticket id does print output.
class Ticket:
counter=0
def init(self, passenger_name, source, destination):
self.__passenger_name=passenger_name
self.__source=source.lower()
self.__destination=destination.lower()
self.__ticket_id=None
Ticket.counter+=1
def get_passenger_name(self):
return self.__passenger_name
def get_source(self):
return self.__source
def get_destination(self):
return self.__destination
def get_ticket_id(self):
return self.__ticket_id
def validate_source_destination(self):
if self.__source== "delhi" and (self.__destination=="mumbai" or self.__destination=="chennai" or self.__destination=="pune" or self.__destination=="kolkata"):
return True
else:
return False
def generate_ticket(self):
if self.validate_source_destination() == True:
srcchar=self.__source[0].upper()
destchar=self.__destination[0].upper()
if(Ticket.counter<10):
self.__ticket_id=srcchar+destchar+"0"+str(Ticket.counter)
else:
self.__ticket_id=srcchar+destchar+str(Ticket.counter)
else:
self.__ticket_id=None
return self.__ticket_id
try this thing:
class Ticket:
def __init__(self, passenger_name, source, destination):
self.counter = 0
self.__passenger_name = passenger_name
self.__source = source
self.__destination = destination
self.Counter = self.counter
self.counter += 1
def validate_source_destination(self):
all_destinations = ["Pune", "Mumbai", "Chennai", "Kolkata"]
if self.__source == "Delhi" and self.__destination in all_destinations:
return True
else:
return False
def generate_ticket(self):
if self.validate_source_destination() == True:
self.ticket_id=self.__source[0]+self.__destination[0]+"0"+str(self.Counter)
print("Ticket id will be: " + self.ticket_id)
else:
return False
def get_ticket_id(self):
return self.ticket_id
def get_passenger_name(self):
return self.__passenger_name
def get_source(self):
if self.__source == "Delhi":
return self.__source
else:
print("You have written invalid soure option")
return None
def get_destination(self):
all_destinations = ["Pune", "Mumbai", "Chennai", "Kolkata"]
if self.__destination in all_destinations:
return self.__destination
else:
return None

Calling global variable causes error when using it for pickling in python 3

I'm trying to save and load files by player name, but it errors when I try to call PlayerIG.name for the path. I've declared global PlayerIG higher up.
Basically I use the PlayerIG to load and then overwrite the values as the name remains the same anyway. The player doesn't have to know and I couldn't find an easier way to do this
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.base_attack = 10
self.gold = 10
self.pots = 1
self.weap = ["Rusty Sword"]
self.curweap = self.weap
#property
def attack(self):
attack = self.base_attack
if self.curweap == "Rusty Sword":
attack += 5
if self.curweap == "Great Sword":
attack += 12
return attack
def attack_damage(self, attack):
damage = random.randint(attack / 2, attack)
return damage
def start():
os.system('clear')
print ("Hello, what is your name?")
options = input("--> ")
global PlayerIG
PlayerIG = Player(options)
name = "Your name is: " + PlayerIG.name
send_status(name)
main()
def main():
os.system('clear')
menutext = "Welcome to text RPG!\n 1.) Start\n 2.) Load\n 3.) Exit\n"
print (menutext)
options = input("-> ")
if options == "1":
Menu()
elif options == "2":
if os.path.exists(PlayerIG.name == True:
os.system('clear')
with open(PlayerIG.name, 'rb') as f:
PlayerIG = pickle.load(f)
loaded = "You loaded your save"
print (loaded)
send_status(loaded)
time.sleep(2)
Menu()
else:
noload = "You have no save file for this game."
print (noload)
time.sleep(2)
main()
elif options == "3":
sys.exit()
else:
main()

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:])

Resources