so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
Related
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
if choice == 1:
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
confirm = input("Do you want to save your contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
with open('contact_list.txt','w') as file:
file.write(str(contact))
print("Your contact-book is saved!")
else:
print("Your contact book was not saved.")
# else:
elif choice == 7:
confirm = input("Do you want to update your saved contact-book Yes or No?")
if confirm == 'Yes' or confirm == 'yes':
f = open("Saved_Contact_List.txt" , "a")
f.write("Name = " + str(name))
f.write(" Number = " + str(phone))
f.close()
#with open('contact_list.txt','a') as file:
# file.write(str(contact))
print("Your contact-book has been updated!")
else:
print("Your contact book was not updated.")
else:
break
I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.
You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.
To write a dictionary, take a look at json.dump():
with open("Saved_Contact_List.txt", "w") as f:
json.dump(contact, f)
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 need to add to a .csv file based on user input. Other portions of the code add to the file but I can't figure out how to have it add user input. I'm new to python and coding in general.
I have other portions of the code that can merge or draw the data from a .csv database and write it to the separate file, but can't figure how to get it to take multiple user inputs to write or append to the outgoing file.
def manualentry():
stock = input("Enter Stock #: ") #Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") #Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) #Prints the line of user data
input4 = input("Append to inventory list? Y/N") #Asks user to append the data to the output file.
if input4 == "Y" or input4 == "y":
with open('INV.csv','a', newline='') as outfile: #Pull up a seperate csv to write to, an output for collected data
w = csv.writer(outfile) #Need to write the user input to the .csv file.
w.writerow([stock, VIN, make, model, year, l8v]) #<-This is the portion that seems to fall apart.
print("INVENTORY UPDATED")
starter() #Restarts whole program from begining.
if input4 == "N" or input4 == "n":
print("SKIPPING. RESTARTING....")
starter() #Reset
else:
print("Invalid entry restarting program.")
starter() #Reset
starter() #R E S E T !
Just need the user inputs to be applied to the .csv and saved there. Earlier portions of the code function perfectly except this to add to the .csv file. It's to fill in missing data that would otherwise not be listed in a separate database.
Some improvement in the code.
You can use a looping condition like while or for instead of recursion
You can open your csv file at the start of the code instead of doing it everytime
You can come up with a word say stop to stop the loop, close the file and exit
You can use str.lower() == 'y' to cover for both y and Y, upper and lower case
The code will then look like
import csv
def manualentry():
#Open csv file at start
outfile = open('INV.csv', 'a', newline='')
w = csv.writer(outfile) # Need to write the user input to the .csv file.
#Everything wrapped in a while True loop, you can change to any loop accordingly
while True:
stock = input("Enter Stock #: ") # Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") # Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) # Prints the line of user data
input4 = input("Append to inventory list? Y/N") # Asks user to append the data to the output file.
if input4.lower() == "y":
w.writerow([stock, VIN, make, model, year, l8v]) # <-This is the portion that seems to fall apart.
print("INVENTORY UPDATED")
if input4.lower() == "n":
print("SKIPPING. RESTARTING....")
#If you see stop, stop writing, close the file and exit
if input4.lower() == 'stop':
print('Not writing anymore! Stopping')
outfile.close()
exit()
else:
print("Invalid entry restarting program.")
#Call manualentry
manualentry()
You can simply use user input controlled while loop to recursively get user input and then you can exit depending on the user choice
user_input = 'Y'
while user_input.lower() == 'y':
# Run your code here
user_input = input('Do you want to add one more entry: Enter [Y/N]')
Try this
import csv
def boo():
stock = input("Enter Stock #: ") # Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") # Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) # Prints the line of user data
input4 = input(
"Append to inventory list? Y/N || anything else to exit") # Asks user to append the data to the output file.
if input4 == "Y" or input4 == "y":
with open('INV.csv', 'a',
newline='') as outfile: # Pull up a separate csv to write to, an output for collected data
w = csv.writer(outfile)
w.writerow([stock, VIN, make, model, year,
l8v]) # Need to write the previously pulled up line to new csv
print("INVENTORY UPDATED")
user_input = input('Do you want to add one more entry: Enter [Y/N]')
if user_input.lower() == 'y':
boo()
else:
exit()
boo()
I have a problem in which users can input spaces or nothing and still pass through the program, how do I go about preventing this? I am still a beginner at python.
def orderFunction(): # The function which allows the customer to choose delivery or pickup
global deliveryPickup
deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
if deliveryPickup == "d":
global customerName
while True:
try:
customerName = (input("Please input your name"))
if customerName == (""):
print("Please input a valid name")
else:
break
global customerAddress
while True:
try:
customerAddress = (input("Please input your name"))
if customerAddress == (""):
print("Please input a valid Address")
else:
break
global customerPhnum
while True:
try:
customerPhnum = int(input("Please input your phone number"))
except ValueError:
print("Please input a valid phone number")
else:
break
print("There will also be a $3 delivery surcharge")
elif deliveryPickup == "p":
customerName = (input("Please input your name"))
if customerName == (""):
print("Please input a valid name")
orderFunction()
else:
print("Please ensure that you have chosen d for Delivery or p for Pickup")
orderFunction()
orderFunction()
Here is my attempt at doing this but I get all kinds of unindent and indent errors at the moment and I think my while loops are probably wrong.
Essentially if I input a space or hit enter into one of the customer inputs (customerName for instance) it gets stored. This needs to prevented and I have tried to fix it by using while loops which obviously haven't worked.
Hopefully someone has a solution to this problem
Many Thanks.
.strip() removes all tabs or spaces before and after a string.
Meaning all spaces == empty string. All tabs == empty string. So all you have to check if the length of that string != 0 or the string is not empty. Just use an infinite loop to keep on forcing the right input.
Also as a tip, you don't have to limit yourself into one function.
Here's a working code below.
def getNonBlankInput(message, error_message):
x = input(message)
while len(x.strip()) == 0:
x = input(error_message)
return x
def getValidIntegerInput(message, error_message):
msg = message
while(True):
try:
x = int(input(msg))
break
except ValueError:
msg = error_message
return x
def orderFunction(): # The function which allows the customer to choose delivery or pickup
global deliveryPickup
global customerName
global customerAddress
global customerPhnum
deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
if deliveryPickup == "d":
customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
customerAddress = getNonBlankInput("Please input your address: ", "Please input a valid address: ")
customerPhnum = getValidIntegerInput("Please input your phone number: ", "Please input a valid phone number: ")
print("There will also be a $3 delivery surcharge")
elif deliveryPickup == "p":
customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
else:
print("Please ensure that you have chosen d for Delivery or p for Pickup")
orderFunction()
orderFunction()
Try using a regular expression that checks if any character between "A-Z" has been inserted, if not, give an error
The while loops are a decent solution, you just need to add more checks to your if statements.
First, you don't need a try statement on the top two loops. Don't use a try statement unless you're expecting an error, which you need to handle with an except statement, like you do in the bottom while loop.
Then you just need to add more conditions to your top two loops, I don't know exactly what you want to prevent, but you could try checking the length of the input, also see this answer for an interesting method:
https://stackoverflow.com/a/2405300/8201979
Instead of using input right away you can make a function similar to this one that will only allow valid inputs.
You can use this valid_input function instead of input.
def valid_input(text):
not_valid = True
res = ''
while not_valid:
res = input(text)
if res.split(): # if text is empty or only spaces, this creates an empty list evaluated at False
not_valid = False
return res
here the check is pretty simple: every text made out of nothing or spaces won't be allowed and we will keep asking for the same input until a valid information is given.
I made this code simple just so you get a general idea. But you can change the validation test to your liking and maybe also output a warning saying why the input wasn't allowed so the person knows what to do. You can do more advanced validation with regex, and maybe you need a minimum text length etc...
You have indent error because you have a try statement without the corresponding except.
You need both to make it work (as you did in the Phone number section).
Here is a link to the try/except: docs
Also, you can check if a string is empty as detailed in this answer.
So for example you want to write:
try:
customerName = input("Please input your name")
if not customerName:
print("Please input a valid name")
else:
break
except ValueError:
print("Please input a valid name")
Although the above seems a bit redundant, so you might want to raise an exception if the customer name is empty, catch the exception in the except block, print the warning and return error (or something else).
try:
customerName = input("Please input your name")
if not customerName:
raise ValueError
except ValueError:
print("Please input a valid name")
else:
break
Try adding another while true for pick and delivery option so that it can prevent taking other inputs
you don't need any of those try/excepts (which are broken anyway).
Its difficult to figure out what you're trying to do, are you trying to raise an exception if an empty string is passed, or request another input from the user? You seem to be half implementing both at the moment.
If its the latter, something like this would work.
def func(fieldname):
while True:
val = input("Please input your {}".format(fieldname))
if val.strip() != "":
break
else:
print("Please input a valid {}".format(fieldname))
return val
delivery_pickup = input("Please input delivery or pickup: d for delivery p for pickup")
if delivery_pickup == "d":
customer_name = func("name")
address = func("address")
phone_number = func("phone number")
What you are looking for is the str.strip method that remove trailing whitespace in strings.
Also I think try is not particularly suited for your needs here.
customerName = input("Please input your name")
while not customerName.strip():
customerName = input("Please input a valid name")
for the phone number I would not convert to integer because if the phone number starts with zeros, they will not be stored.
I need to take multiple inputs from user and exit from the loop when the user hits the enter key.
this is what i am trying to do.
while True:
data = input("Enter name age and score:\t").split(",")
if data==' ':
break
else:
continue
try this
data = input("Enter name age and score:")
while data.strip() != '':
data = input("Enter name age and score:")
Just check for bool value:
while True:
data = input("Enter name age and score:\t")
if not data:
break
else:
continue