Loop Until Condition Is Met - loops

I am extremely new to coding so please bear with me.
I am trying to create a loop until a condition is met, namely, an email address. This is what I have so far:
first = input("Please enter your first name: ")
surname = input("Please enter your surname: ")
email = input("Please enter your email address: ")
emailconfirm = input("Please confirm email address: ")
if email != emailconfirm:
input ("Emails are different. Please kindly confirm email address: ")
cell = input("Please enter cell number: ")
How do I code to enter a cell/ mobile number without it printing until the emailconfirm == email condition is met?
I know this may be simple to many but it is VERY early days for me. Many thanks for the assistance.
Graeme
Tried tutorials but I just cannot get it right :(

You need to use a while loop and update the value of emailconfirm in each iteration
email = input("Please enter your email address: ")
emailconfirm = input("Please confirm email address: ")
while email != emailconfirm:
emailconfirm = input("Emails are different. Please kindly confirm email address: ")

Related

Loop until correct answer is given

Hi could some one please help. I am very new to Python and need help with something I am creating. I would like to to print six statements and then ask the user to enter their answer. The answer needs to be ie. S2, S10 etc. etc. If not true would like it to loop again until correct input has been given.
Please see below:
print("S0 = Initail Issue ")
print("S2 = Information Issue ")
print("S3 = Internal Review & Comment Issue ")
print("S4 = Suitable for Construction in DPP Stage only ")
print("S10 = Construction Issue")
print("CR = Construction Record (As Built)Issue\n")
Initial = "S0"
Information = "S2"
Review = "S3"
DPP = "S4"
Construction = "S10"
As_built = "CR"
Suitability = (input("Look above on the list of suitability is it?\n ").upper())
Suit = {"Initial", "Information", "Review", "DPP", "Construction", "As_built"}
while True:
Suit = Suitability
if Suit == Suitability:
break
else:
print("is not the correct information! ")
Suitability = (input("Look above on the list of suitability is it?\n ").upper())
print("S0 = Initial Issue ")
print("S2 = Information Issue ")
print("S3 = Internal Review & Comment Issue ")
print("S4 = Suitable for Construction in DPP Stage only ")
print("S10 = Construction Issue")
print("CR = Construction Record (As Built) Issue\n")
Initial = "S0"
Information = "S2"
Review = "S3"
DPP = "S4"
Construction = "S10"
As_built = "CR"
validOptions = [Initial, Information, Review, DPP, Construction, As_built]
while True:
Suitability = (input("Look above on the list of suitability is it?\n ").upper())
if Suitability in validOptions:
break
print("is not the correct information!")
print("You entered", Suitability)
I used if item in container syntax to validate the input by checking to see if the provided input is in a list of valid options.
I also restructured your loop so that you only have to express the input prompt once in your code.

How to find the index of a value in an array and use it to display a value in another array with the same index

I am new to Python and I have been stuck trying out a "simple banking program".
I have got everything right except for this bit:
If the user types S then:
Ask the user for the account number.
Search the array for that account number and find its position in the accountnumbers array.
Display the Name, and balance at the position found during the above search.
Originally it was just supposed to be through accounts 1-5, but now I am having trouble coming up with a way to search the account numbers if they are any number, not just 1 - 5. For example
The user makes his account numbers 34, 445, 340,2354 and 3245. Completely random account numbers with no order.
Here is what I have so far
names = []
accountNumbers = []
balance = []
def displaymenu():
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choiceInput()
def choiceInput():
choice = str(input("Please enter your choice: "))
if (choice == "P"):
populateAccount()
elif (choice == "S"):
accountNumb = int(input("Please enter the account number to search: "))
if (accountNumb > 0) and (accountNumb < 6):
print("Name is: " + str(names[accountNumb - 1]))
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
elif (accountNumb == accountNumbers):
index = names.index(accountNumb)
accountNumb = index
print(names[accountNumb - 1] + " account has the balance of : $" + str(balance[accountNumb -1]))
else:
print("The account number not found!")
elif (choice == "E"):
print("Thank you for using the program.")
print("Bye")
raise SystemExit
else:
print("Invalid choice. Please try again!")
displaymenu()
def populateAccount ():
name = 0
for name in range(5):
Names = str(input("Please enter a name: "))
names.append(Names)
account ()
name = name + 1
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
def balances ():
balances = int(input("Please enter a balance: "))
balance.append(balances)
displaymenu()
I have tried to use indexes and have not been able to find a solution.
Replace the following line of code
if (accountNumb > 0) and (accountNumb < 6):
with
if (accountNumb > 0) and (accountNumb < len(accountNumbers)):
My mistake. I messed up when appending the account number:
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumbers)
balances()
I appended
accountNumbers
not
accountNumber
the code should be
def account ():
accountNumber = int(input("Please enter an account number: "))
accountNumbers.append(accountNumber)
balances()
also the searchArray function I made was:
def searchArray(accountNumbers):
x = int(input("Please enter an account number to search: "))
y = accountNumbers.index(x)
print("Name is: " + str(names[y]))
print(str(names[y]) + " account has a balance of: " + str(balance[y]))
rookie mistake , shouldnt be using such similar object names.

Why it gives me Type error in that code?

Why he gives me (Type error) in that statment
" address = cur.fetchone()[2] last = cur.fetchone()[4] no = cur.fetchone()[5] , while it accept "name = cur.fetchone()[1]" in the code : "
import sqlite3
conn = sqlite3.connect('myproject.sqlite')
cur = conn.cursor()
print "Welcome Mr/Hefnawy"
cur.execute('SELECT phone FROM participants')
b = cur.fetchone()[0]
while True:
a = raw_input("Enter Phone number here : ")
if a == b :
cur.execute('SELECT name,address,last_order,no_of_orders FROM participants WHERE phone = ?',(b, ))
name = cur.fetchone()[1]
address = cur.fetchone()[2]
last = cur.fetchone()[4]
no = cur.fetchone()[5]
print "The Costumer is already exist in Paricipants "
print "To edit the costumer data press (1)", "\n" , "to delet the costumer press (2)", "\n" , "add new order to the costumer press (3) "
c = raw_input("Enter your choice here : ")
if c == "1":
print "What do you want to edit ? , to edit name press 1 , to edit address press 2 , to edit phone press 3"
d = raw_input("Enter your choice here : ")
if d == "1" :
e = raw_input("New costumer name please ")
cur.execute('UPDATE participants SET name = ? WHERE phone = ?' , (e , a))
print "Costumer name has been updated to :", e
print ""
conn.commit()
else:
print "The costumer is not exist"
print b
print a , type(a)
When you are fetching something from a cursor say for example
t = cur.fetchone()
you can access the data from t using
print t[0],t[1],t[2] but In your case you are using multiple cur.fetchone() which allows you to use name = cur.fetchone()[1] that ends the data in the cursor. The second line address = cur.fetchone()[2] and the lines that follow it do not have a sql query executed for them to fetch, hence giving you the error. If you want to access the whole row just assign it to a variable and use the variable to get the data.

I can't seem to understand loops

Yes I'm new to this and I'm having a very hard time learning. This has me very confused. I have tried for hours to create a loop where if the value of a variable is not what it should be, it will continue asking for raw_input until it is what it should be and the program moves to the next function, as well as display something like "Try again" It's probably simple but I can't figure it out. I'm talking about the code after first_action = raw_input(">> ")
def start():
print """You awaken in a strange lanscape, You are on a steep hillside
surrounded by trees, and you can see large mountains in the distance."""
print "....."
print "....."
print "You struggle to regain your senses, and you realize you don't know who you are, or how you got here."
print "You have the following items: %s" % i
print "It's dark, perhaps you should sleep until the sun rises."
print "What do you do?"
def cryptic_message(read):
print read, "A paper with a message written in a strange language."
def day_1():
print "_-_-_Dream_-_-_"
print "It is relativity. It is a concept you know as time."
print """This time, what is it? You ask "me" and I do not know. Ask yourself."""
print """It is illusion. Oh look, "time" to wake up!"""
print "....."
print "....."
print "You awaken, dazed and tired"
print "What do you do?"
def knife(cut, stab):
print "What do you want to do with the knife?"
knife = raw_input(">> ")
def photo(view):
print "A faded photo of a man on a park bench"
i = ['clothing','small knife','strange photo','cryptic message']
start()
first_action = raw_input(">> ")
first_action == False
while first_action is False:
if first_action == "sleep":
print "You lay on the grass for a hardly restful sleep."
first_action == True
day_1()
elif first_action == "do nothing":
print "Try again"
first_action == False
else: "Try again"
You want something like this:
inp = ''
desired = 'hello'
while inp != desired:
inp = raw_input('Enter a greeting: ')
This will continue to ask for input until inp is desired:
>>> inp = ''
>>> desired = 'hello'
>>> while inp != desired:
... inp = raw_input('Enter a greeting: ')
...
Enter a greeting: bye
Enter a greeting: no
Enter a greeting: what's up
Enter a greeting: hello
>>>
In your code:
first_action = raw_input(">> ")
while first_action != "False::
print "Try again"
first_action = raw_input(">> ")
print "You lay on the grass for a hardly restful sleep."
day_1()

Text file over written and not appended

So far I have this program doing what i want. However when running through it will overwrite the last employee record instead of just adding to the file. I'm new to prgramming and have been staring at this for hours and i can't get it yet. Just need a little nudge in the right direction.
# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
fullName = fullName
age = age
salary = salary
def displayEmployee():
print("\n")
print("Name: " + fullName)
print("Age: " + age)
print("Salary: " + salary)
print("\n")
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input("Pick an option: ")
if choice == "1":
fullName = input ("Enter Full Name: ")
if fullName == "":
blankName = input ("Please enter a name or quit: ")
if blankName == "quit":
print ("Goodbye!")
print ("Hope to see you again.")
Continue = False
break
age = input ("Enter Age: ")
salary = input ("Enter Salary: ")
EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
EmployeeRecords.write("Full Name: " + fullName + '\n')
EmployeeRecords.write("Age: " + age + '\n')
EmployeeRecords.write("Salary: " + salary + '\n')
EmployeeRecords.close()
elif choice == "2":
EmployeeRecords = open ('EmployeeRecords.txt', 'r')
data = EmployeeRecords.read()
print ("\n")
print (data)
EmployeeRecords.close
elif choice == "3":
answer = input ("Are you sure you want to quit? " "yes/no: ")
if answer == "yes" or "y":
print ("Bye!")
Continue = False
else:
Continue
else:
print ("Please choose a valid option")
print ("\n")
You are opening the file to be rewritten each time, based on the control string passed to open. Change open ('EmployeeRecords.txt, 'w')to open ('EmployeeRecords.txt', 'a+'). and the records will be appended to the end of the file.
Append mode should work.
EmployeeRecords = open('EmployeeRecords.txt', 'a')

Resources