Loop Dual-Conditional Input Validation (Python) - python

I'm trying to write a python script that achieves the following:
First, prompt a user to enter the username or press enter to exit.
Prompt a user to enter quantity.
Next, use regular expression to make sure that the username consists of 5 to 10 alphabetical characters.
Use regular expression to make sure that quantity consists of only numerical values and the quantity entered is between 0 and 100
If both the username and quantity are valid, then print the username and quantity. Otherwise print an error message.
Finally, prompt the user for username again or press enter to exit.
import re, sys
username = ""
username = input('Enter Username (Press ENTER to exit): ')
while username != "":
quantity = input('Enter Quantity: ')
if re.match("[a-zA-Z]{5,10}$", username) and re.match("[0-9]{1,2}$", quantity) and type(quantity) is int and quantity > 0:
print('Username: ', username, "\n" 'Quantity: ', quantity)
else:
print('Error: Enter a username consisting of 5-10 alphabetical letters and a valid integer between 1 and 100')
username = input('Enter Username (Press ENTER to exit): ')
How would I achieve these requirements? When I run my program I always print the error message and can't properly print the username and quantity.
Thank you for taking the time and I appreciate any help I can get.

If you are having trouble understanding a complex condition, test each component individually. In your case, type(quantity)will not be int it will be str, which also means that quantity > 0 would raise a TypeError (you are not getting there because the typetest shortcircuits the condition).
A slightly better condition would be:
if re.match("[a-zA-Z]{5,10}$", username) and re.match("[0-9]{1,2}$", quantity) and int(quantity) > 0
This is hardly pythonic, but it will get the job done.

Related

How To Slove Error For The Login Code In Python Using CSV File?

This is my code for Verifying User ID and password from a csv file.
CODE
import pandas as pd
login():
df=pd.read_csv("IDPASS.csv")
for i in range(len(df)):
x=input("Enter User Name=")
y=input("ENter The Password=")
if (df.iloc[i]["ID"])==x:
if str(df.iloc[i]["PASS"])==y:
print("Succesfully Logined")
break
else:
print("Invalid Password")
print("Try Again!!")
else:
print("Invalid Username")
print("Try Again!!")
login()
Output1:
Enter User Name=JEET1073
ENter The Password=str1234
Succesfully Logined
Here I have entered correct id password and the code is executed perfectly!!
Output2:
Enter User Name=dw
ENter The Password=wd
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Enter User Name=JEET1073
ENter The Password=str1234
Invalid Username
Try Again!!
Here at first i have entered wrong id and password and then i was trying to enter the correct id and password but it was showing invalid username. any solutions will be appreciated,also i want a solution in which if a user enters wrong id password the code should run again asking id and password till the user id and password entered is not correct.Thanks in advance.
After the clarification, this should be the functionality you are seeking.
First import pandas and read the csv:
import pandas as pd
df = pd.read_csv("IDPASS.csv")
We will now read the values stored in the csv and store them as a list. A list of users and a list of passwords. A good practice would be to do this outside of any loops.
csv_id_list = df['ID'].to_list()
csv_pass_list = df['PASS'].to_list()
If you don't know how long your loop will have to go on for (we don't know how many times the user will try the password) use a while loop. Initialize the initial state of the correct login variable.
correct_login = False
Now where the magic happens. We will start a while loop. While correct_login is false, we will keep asking the user for their username and password. IF the input by the user matches a list element, get the index for that list element, then start another IF statement. . This will break the while loop. ELSE they get an invalid password message, IF the input matches the list element at the correct index, print correct_msg and correct_login = True. Break while loop. ELSE correct_login is still false, user must try again.
This means that the user must input the correct username and the password it corresponds to, they cannot input the password of another user and log in.
while not correct_login:
x = input("Enter User Name=")
y = input("Enter The Password=")
correct_msg = 'Successfully logged in.'
incorrect_msg = 'Invalid Password.' + '\n' + 'Try Again.'
if x in csv_id_list:
x_index = csv_id_list.index(x)
if y == csv_pass_list[x_index]:
print(correct_msg)
correct_login = True
else:
correct_login = False
print(incorrect_msg)
else:
correct_login = False
print(incorrect_msg)

Python - Issue with for loop (lists)

I have the following code which prompts the user for a username, then checks if that username exists in a json file, if so the script should prompt the user 3 times maximum to enter another username, otherwise just accept the entered username and continue.
The issue comes when I try to reinitiate the for loop j = test1["users"][0] so that in the second attempt, this script checks the json file from the beginning not from the point it was.
When the script comes back to the for loop after the else statement, it just simply ignores the whole loop and continue to the next section of the code without any error...
The for loop is looping in a dictionary which is in a list:
#prompt for username
x["User Name"] = input("Please type your user name: ")
i = 0
#for loop to check if the entered username already exists
for j in test1["users"]:
while j["User Name"] != x["User Name"] and i < 3:
break
else:
print("username already exists, try again")
x["User Name"] = input("Please type a new user name: ")
i += 1
j = test1["users"][0]
#prompts the user for additional information if username pass `succesfully`
x["First Name"] = input("Please type your first name: ")
x["Last Name"] = input("Please type your last name: ")
x["Age"] = input("Please type your age: ")
A sample of test1["users]:
{
"users": [
{
"First Name": "jhon",
"Age:": "30",
"Last Name": "kerry",
"User Name": "jhon",
"Height": "170",
"Weight": "70"
},
For this case you dont want to use break but continue .
Here is a good tutorial where you can find more detailed explainations: https://docs.python.org/3/tutorial/controlflow.html?highlight=break
Guys thanks for your support, just wanted to say I solved the issue. Basically the challenge was:
I have a list of users in a json format or in a dictionary, in the end it doesn't matter.
I prompt the user to enter basic information and then I will append the information to the json file if the user name doesn't already exists there.
If the username already exists, the user has 3 additional attempts to enter another username.
The script must check again in the whole file if the new typed user exists or not in order to continue.
The issue was in the last point, because I needed to loop again in a for statement that could be in the middle of its job, which could result in duplicated records if the username existed in previous records.
My first attempt was to try to restart the for loop with this statement j = test1["users"][0] so that the loop started over, but that one didn't work. In the end the solution I came up with is using an additional loop that forces the for loop to be restarted. If you play with a while and a boolean variable the issue will get solved!! :)
That's the final code:
x["User Name"] = input("Please type your user name: ")
#initializing variables that restart for loop and restrict username input to 3
i = True
n = 0
#additional while loop to restart for loop
while i and n <= 3:
i = False
if n == 3:
print("Thank you")
exit()
#looping a list in a diciontary
for j in test1["users"]:
while j["User Name"] != x["User Name"]:
break
#telling the user the username already exists and prompting for new username
else:
print("existing user")
x["User Name"] = input("Type new user name")
n += 1
i = True
break
x["First Name"] = input("Please type your first name: ")
x["Last Name"] = input("Please type your last name: ")
Thanks everyone!!

How to insert data into specific row without hardcode

The aim of this code is to achieve the following:
-Enter username
-Check if exists on DB
-If not create new user
-Add currency & balance to new user row
The issue is with my insert statement. I'm not sure how to use the WHERE condition while inserting data using defined variables. Help would be welcomed!
Error Message: TypeError: function takes at most 2 arguments (4 given)
def add_user():strong text
print("enter new username")
UserLogin = str(input())
c.execute("SELECT username FROM FinanceDBTable")
enter code here
for row in c.fetchall():
print()
#Convers tuple to string without spaces
UserNameDB = ''.join(row)
if UserNameDB == UserLogin:
print('This username already exisits. please try again')
add_user()
else:
print("Please enter your balanace\n")
userbalance = input()
print("Please enter currency\n")
userCurrency = input()
c.execute("INSERT INTO FinanceDBTable (balance, currency) VALUES (?,?)",
(userbalance, userCurrency), "WHERE (username) VALUES (?)", (UserLogin))
conn.commit()
One way would be to do this, also does not use recursion which is seen as unpythonic and also will eventually throw errors. Plus made it a bit more pythonic.
I'm not sure if you can use WHERE in INSERT statements, you can in UPDATE maybe that where you're getting that idea from, but by also giving the username value with the other will work for what you are trying to achieve i think.
def add_user():
while True:
username = input("Username: ")
c.execute("SELECT username FROM FinanceDBTable WHERE username = ?", (username,))
results = c.fetchall()
if len(results) < 1:
# Add user as there is not user with that username.
user_balance = int(input("Please enter your balance: "))
user_currency = input("Please enter currency: ")
c.execute("INSERT INTO FinanceDBTable(username, balance, currency) VALUES (?,?,?)", (username, user_balance, user_currency))
conn.commit()
break
else:
# User already exists
print('This username already exists, please try again.')

Python GCSE homework help - password

For my homework I need to make a user registration system in python. I need to make a password section.
What I am meant to do?.
Here is my code, I can't work out whats wrong:
password = input("Please enter your password: ")
passwordl = len(password)
while passwordl <= 8:
print("password must be more than 8 characters - please try agian")
password = input("Please enter your password: ")
passworda = password.isalpha()
passwordi = password.isdigit()
while passworda != True or passwordi != True:
print("password needs to contain digits and characters - please re-enter")
password = input("Please enter your password: ")
The code is in a function btw.
Thanks
The functions isalpha() and isdigit() return true if all the members in the string are alphanumeric and digits, respectively.
What you need to do instead is to check if any characters in the string have the right properties, for example like this:
passworda = any([x.isalpha() for x in password])
passwordi = any([x.isdigit() for x in password])
Additionally, you need to redo all the checks (both length and character set checks) each time when the password is entered anew.
Instead of following
Password = input("Please enter your password")
In the last while loop with the checks over again you would be better just calling the password function as it's more efficient.

Can't Assign to Literal in Python

I'm receiving an error in python that says I, "Can't assign to literal". I was hoping that somebody could help me understand why this is coming up. Here's my code:
# Chapter 3 Challenge part 3
# use the code below and the following
# directions to see if you can solve the problem
# Your Co-Worker has been asked to write a
# 1st time "Log-in" program in which a user has to
# sign in with their user name. If they enter
# the correct id name they need to be asked
# to create their password.
# They were required to make sure the user did
# not leave the username entry blank and must have the
# correct user name or the progam should re-ask
# them to sign in... They cannot figure out what
# to do, so they have called on you to help...
# Here is what they have so far...
# They started their program like this....
# and included some of their documentation.
# Get username, check to see if not empty,
# then verify that username is correct.
# using username "jalesch" as test user.
name = False
while not name:
name = raw_input("Enter your user name: ")
print "Welcome," , name , "you must create a password."
password = False
while not password:
password = raw_input("""Enter a password.
Password must be at least 6 characters in length,
and must include one of these symbols (!, $, ?, &): """)
while len(password) < 6:
for "!" in password or "$" in password or "?" in password or "&" in password:
password = raw_input("""Enter a password.
Password must be at least 6 characters in length,
and must include one of these symbols (!, $, ?, &): """)
print "This has met the requirements."
check = raw_input("Please re-enter your password:")
while check != password:
print "You have entered the wrong password"
check = raw_input("Please re-enter your password:")
print "Welcome to the program!"
# prompt user to create a password that meets the
# following requirements:
# - Must be at least 6 characters in length
# - Must include at least one of these 4 symbols
# - ! $ ? &
# Once the user has entered their password, the program
# must check to see if it meets the requirements.
# If the requirements are not met, it should reask them
# to put in a password that meets the requirements
# until they get it correct.
# Test password is: $program!
# If it meets the requirements then prompt the user
# to re enter the password, and check that the
# first and second entry matches.
# If the 1st and 2nd match. display "Welcome to the program"
# If the 1st and 2nd don't match, re-prompt for the password
# until they get a correct match.
I also believe that the code is malfunctioning when I try to find the special characters, because it is skipping one of the while loops. Any help is appreciated, thanks.
on this line:
for "!" in password or "$" in password or "?" in password or "&" in password:
You probably meant to use if:
if "!" in password or "$" in password or "?" in password or "&" in password:
for x in y iterates over y, assigning each member to x sequentially, running the following indented code in a loop for each member of y. You can't assign a value to "!" because that's a literal character, not a variable.
def get_name(prompt):
while True:
name = raw_input(prompt).strip()
if name:
return name
def get_password(prompt):
while True:
name = raw_input(prompt).strip()
if len(name) >= 6 and (set(name) & set("!$?&")):
return name
name = get_name("Enter your user name: ")
print("Welcome, {}, you must create a password.".format(name))
while True:
print("Now enter a password. It must be at least 6 characters in length, and must include a symbols (!, $, ?, &).")
pass1 = get_password("Enter a password: ")
pass2 = get_password("Please re-enter your password: ")
if pass1 == pass2:
print("Welcome to the program")
break
else:
print("No match! Please try again")

Categories

Resources