I'm writing a very basic payment system on Python, but every time I enter the main() function and input a value it just quits the program. Any ideas?
import sys
def info():
usernames = ["15mermelstein_p","gril","jeff","example"]
passwords = ["test","pass","what","why"]
balances = [22.91,45.76,21.62,7.54]
a = input("What is your username? ").lower()
b = input("What is your password? ")
print(a)
print(b)
success = 0
for index in range(len(usernames)):
if usernames[index] == a and passwords[index] == b:
user_num = index
success = 1
break
if success == 1:
print("Login successful\n")
main()
return (a,b,user_num)
else:
print("Login unsuccessful")
info()
def main():
choice = input("-----Welcome to the new School Payment System-----\n1. Add money to account\n2. Change password\n3. Change your username\n4. Quit the program\n--------------------------------------------------\n")
if choice == "1":
credit = input("How much money would you like to deposit into your account? ")
temp_b = input("Please type in your password once againto confirm thios transaction: ")
if temp_b == info[2]:
balances[num(info[3])] += float(credit)
else:
print("The password you entered was incorrect, please return and try again. ")
elif choice == "2":
check_pass = input("Please input your current password first")
elif choice == "3":
sys.exit(0)
elif choice == "4":
sys.exit(0)
else:
sys.exit(0)
info()
Since you have provided no other information and the code runs fine on my machine, I am going to assume that your error is that you are running the wrong version of python. The code compiles with python-2.x but when you get to any of the inputs, it will not work as desired:
AJs-MacBook-Pro:~ $ python2 k.py
What is your username? "gril"
What is your password? "pass"
gril
pass
Login successful
-----Welcome to the new School Payment System-----
1. Add money to account
2. Change password
3. Change your username
4. Quit the program
--------------------------------------------------
1
AJs-MacBook-Pro:~ $
I ran your code with python3.x and it has some errors.
if temp_b == info[2]:
balances[num(info[3])] += float(credit)
You can subscript a function object. What you really need to do is either pass the correct username password to the main function so that it can be accessed in the main function to add balance and other things and validate the password again.
First of all, your program works fine apart from the below code,
if temp_b == info[2]:
balances[num(info[3])] += float(credit)
You are trying to access info as an array, but info is a function. (may be you have missed to define array for your payment system menu options).
Related
I start to learn python a couple of days ago,Im trying to make some kind of login interface with multiple passwords options but can't figure out the right way to make it loop until I enter the right password ,I tried to use "while" but cant seem to figure out the syntax and placement with it in my code,I want it to repeat the first block of code if "else" is the result so I can try and type the password again,please help?
import random
male = random.choice([True, False])
import random
num = random.choice(["1", "0"])
name = "joe"
user_input= input ("insert Password here ")
if ((user_input == "joey") or (user_input == "loki")):
if male == True: print("hello")
if male == False: print("wellcome")
if name == "joe":
if num == "1":
print("hi world")
if name == "joe":
if num == "0":
print("nice")
if name + num == ("joe" + "0"):
print("thats working")
else:
print ("Wrong Password,Please try again.")
First of all I would like to point out that you only need to import your libraries once. Second if you want your code to repeat you will require a loop, in python there are 2 types of loops - for loop and while loop. For your requirement I would suggest using a while loop as given below. I couldn't really understand what you were trying to accomplish but I have improved your code a bit.
import random
male = random.choice([True, False])
num = random.choice(["1", "0"])
name = "joe"
while True:
user_input= input("insert Password here ")
if (user_input == "joey") or (user_input == "loki"):
if male == True:
print("hello")
elif male == False:
print("wellcome")
else:
break
if name == "joe" and num == "1":
print("hi world")
elif name == "joe" and num == "0":
print("nice")
if name + num == ("joe" + "0"):
print("thats working")
else:
break
else:
print ("Wrong Password,Please try again.")
Another method of having it run repeatedly is to use recursive functions, however since you are just starting out with python I would suggest learning loops before you get into recursive functions.
You can use the following general syntax to validate input:
input_to_validate = input(message_on_input)
while not is_valid(input_to_validate):
print(message_on_error)
input_to_validate = input(message_on_input)
where is_valid() your method for determining if the input is valid or not
Before coding anything please do learn the language properly and do look up proper syntax conventions. The following code is much more readable and conforms more to coding standards:
import random
male = random.choice([True, False])
num = random.choice(["1", "0"])
name = "joe"
def is_valid(password):
return password in ["joey", "loki"]
user_input = input("insert Password here: ")
# this while-loop runs as long as the user_input is not valid
while not is_valid(user_input):
print("Wrong Password, please try again.")
user_input = input("insert Password here: ")
# this part of the code is reached only when user_input is valid
if male:
print("hello")
else:
print("welcome")
if name == "joe":
if num == "1":
print("hi world")
else:
print("nice")
if name + num == "joe0":
print("that's working")
Hopefully my code and question(s) are clear for understanding. If they are not please provide feed back.
I am fairly new to programing/coding so I decided to develop a program using Python that acts like a pizza ordering system. I eventually would like to use this code to develop a website using Django or Flask.
I have just finished the first step of this program where I am asking the user if this will be for delivery of pickup. Depending on what the user chooses the program will ask for specific information.
The area I feel like I am struggling with the most is developing classes and functions. specifically taking a variables from one function and using that variable in another function. I posted a past example of my code and I was advised that Global variables are not good to use in code. So I am trying really hard to refrain from using them.
Here is the code for reference:
import re
running = True
class PizzaOrderingSys():
"""order a customized pizza for take out or delivery """
def delivery_or_pickup(self): # Is the order for devilery or pickup?
print("\nWill this order be for pickup or delivery?")
self.delivery = input("P - pick up / D - delivery : ")
self.delivery = self.delivery.title()
if self.delivery == "D":
while running == True:
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a vaild input")
else:
customerName = customerName.title()
break
while running == True:
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a a contact phone number")
else:
break
while running == True:
house_num = input("\nWhat is your house or unit number: ")
if not re.match("^[0-9 /]*$", house_num):
print("Please use numbers only")
elif len(house_num) == 0:
print("Please enter a valid input ")
else:
break
while running == True:
streetName = input("\nStreet name: ")
if not re.match("^[a-zA-Z ]*$", streetName):
print('Please use letters only.')
elif len(streetName) == 0:
print("Please enter a valid input")
else:
streetName = streetName.title()
break
while running == True:
city = input("\nCity: ")
if not re.match("^[a-zA-Z ]*$", city):
print("Please use letters only")
elif len(city) == 0:
print("Please enter a valid input")
else:
city = city.title()
break
while running == True:
zip_code = input("\nZip Code:")
if not re.match("^[0-9 /]*$", zip_code):
print("Please use numbers only")
elif len(zip_code) == 0 or len(zip_code) > 5:
print("Please enter a valid input")
else:
break
elif self.delivery == "P":
while running == True:
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a valid input")
else:
customerName = customerName.title()
break
while running == True:
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a valid input")
else:
break
else:
print("Please enter P or D ")
delivery_or_pickup()
order = PizzaOrderingSys()
order.delivery_or_pickup()
My question is this: How would I use variables found in one function of my class and use it in another future function??
For example if I wanted to retrieve variables the functions customerName, customerPhoneNumber, house_num, streetName, city, Zip_code found in delivery_or_pick() function and use them in a function called:
def customer_receipt():
What would I need to do to my exiting code or to the def customer_receipt() function to obtain that information?
Any help with my questions or advise on any other area that stick out to you would be be greatly appropriated.
This is my second post on Stackoverflow so I apologize if what i am asking is unclear or the format of my question might is off, I am still learning.
Thank you again.
The idea here is that you can use your class variables to save data between method calls. Methods are functions that belong to a class. For example you could use Python's class initialization and create a dict of orders. Here is a simple example of such system, take a note of the usage of self keyword. self refers to the instance of the class and you can use it to access the variables or methods of the instance:
class PizzaOrderingSys:
def __init__(self):
# Initializing some class variables
self.running = True # Now you can use self.running instead of global running variable
self.orders = {}
def delivery_or_pickup(self):
# Somewhere at the end where you have collected the needed info
order = {
"zip_code": zip_code,
"city": city,
# You can enter all of the needed data similarly
}
order_id = "SomeIdHere" # ID could be anything, it just should be unique
self.orders[order_id] = order
return order_id
def customer_receipt(self, id):
# Now you can access all of the order here with self.orders
order = self.orders.get(id) # Select some specific order with id.
# Using get to avoid the situation
# where no orders or invalid id would raise an exception
if order:
receipt = f"Order {id}:\nCustomer city {order['city']}"
else:
receipt = None
return receipt
pizzasystem = PizzaOrderingSys()
order_id = pizzasystem.delivery_or_pickup()
receipt = pizzasystem.customer_receipt(order_id)
print(receipt)
# >>> Order 1235613:
# Customer city Atlantis
I recommend that you read more about classes, for example, python docs have great material about them.
I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break
def buyingApp():
appDownPick=1
while (appDownPick !=0):
appDownPick = int(input("\nWhich application do you want to download?\nPlease specify the index of the application\nIf you don't want to download, please enter 0.: "))
if (appDownPick == 1):
appDownCon = input("You've chosen to download 'PUBG Mobile'. The price of the application is US$5. Do you want to download this application? (Y/N): ")
if (appDownCon == Y):
if (getBalanceasTotal (ledge)<0): #When balance is not enough, it would not work.
print ("Insufficient funds")
print ("Please restart and try again")
break
elif (getBalanceasTotal(ledge)>0): #When balance is enough to purchase, it would download and saved in the document.
spendBalance (0,5.0,"You have downloaded PUBG Mobile for US$5.")
print ("You have downloaded PUBG Mobile.")
break
elif (appDownCon == N):
break
I am working on this code, which is asking the user to choose whether they are going to download the app or not at the end and should run.
However, when my code is in run, it just keep asking appDownPick and appDownCon, when it is supposed to proceed to purchasing related code.
Which part should I fix in order for this code to run?
+) This is run by the code below
option = 1 #Declare option as 1 so that while loop can work, and until the user puts 0, this, option command will keep looping.
while (option!=0):
option = int(input("Options:\n1. Search by Category\n2. Search by Name (This option requires to type the exact name of the application)\n3. Download the application\nPlease enter 0 to quit App Store."))
if (option == 1):
categorize()
elif (option == 2):
search()
elif (option == 3):
buyingApp()
else:
break
You need use quotes (' or ") in constants strings. So, change:
appDownCon == Y
appDownCon == N
to:
appDownCon == 'Y'
appDownCon == 'N'
Can someone try to help me make with this, please. So once the user guesses 3 times the entire program closes, but once the user gets it wrong it doesn't make them exit the program. Yes I'm aware that I'm asking the same question again but I haven't got my question answered yet so please can someone help.
Here's another one I'm trying out. Any Suggestions on how to do exit the program if the user gets a certain number of attempts by trying to guess the password wrong. I've been trying to use sys.exit and exit()but it hasn't been working for me, so maybe you can try to that , (but remember my teacher wants it so that it on IDLE).
Counter=1
Password=("Test")
Password=input("Enter Password: ")
if Password == "Test":
print("Successful Login")
while Password != "Test":
Password=input("Enter Password: ")
Counter=Counter+1
if Counter == 3:
print("Locked Out: ")
break
counter = 1
password = input("Enter password: ")
while True:
if counter == 3:
print("Locked out")
exit()
elif password == "Test":
print("That is the correct password!")
break
else:
password = input("Wrong password, try again: ")
counter += 1
Move your counter check into the while loop.
Also use getpass for getting password input in python :)
import sys
import getpass
counter = 1
password = getpass.getpass("Enter Password: ")
while password != "Test":
counter = counter + 1
password = getpass.getpass("Incorrect, try again: ")
if counter == 3:
print("Locked Out")
sys.exit(1)
print("Logged on!")
You need to move the condition counter==3 inside the while loop
This can also be done in this way
import sys
password = input("Enter password : ")
for __ in range(2): # loop thrice
if (password=="Test"):
break #user has enterd correct password so break
password = input("Incorrect, try again : ")
else:
print ("Locked out")
sys.exit(1)
#You can put your normal code that is supposed to be
# executed after the correct password is entered
print ("Correct password is entered :)")
#Do whatever you want here
An even better way is to wrap this password-checking thing into a function.
import sys
def checkPassword():
password = input("Enter password : ")
for __ in range(2):
if (password=="Test"):
return True
password = input("Incorrect, try again : ")
else:
print ("Locked out")
return False
if (checkPassword()):
#continue doing you main thing
print ("Correct password entered successfully")