making columns with specific textfile data in python 3.2 - python

This is meant to ask a user for their username, find the username in a textfile and then output in columns, just their information. The information is ID, Last name, Year joined, Status, Nights booked and Points. How do I do this???
import time
membr = int(input("Do you have a membership already?\n"
"1.Yes\n"
"2.No\n"
"Option: "))
if membr == 1:
MemberID = []
LastName = []
YearJoined = []
Status = []
NightsBooked = []
Points = []
theirid = input("Please enter your id number (It is case sensitive): ")
Myfile = open("Memberships.txt", "r")
x = 0
for line in Myfile:
if theirid in line: return(line)
information = line.split(",")
MemberID.append(information[0])
LastName.append(information[1])
YearJoined.append(information[2])
Status.append(information[3])
NightsBooked.append(information[4])
Points.append(information[5])
x = x+1
Myfile.close()
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
for y in range(1,x):
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
time.sleep(2)
mainmenu()
elif membr == 2:
createnewuser()
else:
print("Invalid")
time.sleep(2)
mainmenu()

You don't need to return the line there.
...
YearJoined = []
Status = []
NightsBooked = []
Points = []
theirid = input("Please enter your id number (It is case sensitive): ")
Myfile = open("Memberships.txt", "r")
x = 0
for line in Myfile:
# this will use the line found to do your work.
if theirid in line:
information = line.split(",")
MemberID.append(information[0])
LastName.append(information[1])
YearJoined.append(information[2])
Status.append(information[3])
NightsBooked.append(information[4])
Points.append(information[5])
x = x+1
Myfile.close()
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
for y in range(1,x):
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
time.sleep(2)
mainmenu()
elif membr == 2:
createnewuser()
else:
print("Invalid")
time.sleep(2)
mainmenu()

Related

Checking a list to make sure a user inputted item is in there

condition = True
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
for item in range(0, len(classes)):
print(item+1, ".", classes[item])
while condition:
if(len(classes) < 5):
course = str(input("What course(s) would you like to take?: \n"))
course = course.title()
course = str(course)
print(course)
print(len(classes))
classes = course.split(",")
for i in range(len(classes)):
classes[i] = classes[i].strip()
print(len(classes))
print(classes)
printClasses()
elif (len(classes) > 5):
removeClass = input("Please select a class to remove: \n")
removeClass = removeClass.title()
removeClass = str(removeClass)
removeClass = removeClass.strip()
classGone = []
classGone = removeClass.split(",")
for i in range(len(classGone)):
classGone[i] = classGone[i].strip()
for item in classGone:
removeClass = []
inputCheck = classGone.count(removeClass)
if inputCheck > 0:
classes.remove(item)
else:
print("Please select a class that exists...")
printClasses()
else:
print("Done!")
break
Im having trouble with my inputCheck statement. I need to be able to remove things from the list but they have to be on there.
Thank you!
I tried to make a iputCheck variable that checks the list for the input to make sure it matches something in the list, but it all went downhill.
There were numerous mistakes in your code. Instead of pointing then all out I have fixed them and will allow you to figure it out on your own.
global classes
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
count = 1
for item in classes:
print('{}. {}'.format(count, item))
count += 1
while True:
if(len(classes) < 5):
course = str(input("What course(s) would you like to take?: \n"))
classes += course.split(",")
for i in range(len(classes)):
classes[i] = classes[i].strip().title()
printClasses()
elif (len(classes) > 5):
removeClass = str(input("Please select a class to remove: \n"))
classGone = removeClass.split(",")
for item in classGone:
i = str(item)
if i.strip().title() in classes:
classes.remove(i)
else:
print("Please select a class that exists...")
printClasses()
else:
print("Done!")
break
Had a pretty hard time understanding what you meant but I think I got it. You want to check if the selected class for removal is in the list? If that's the case you can use the following code:
#The list
classes=["English","Math","Coding"]
##Asking what classes to remove
Class_To_Remove=input("What class do you want to remove?")
#Removing the classes and checking if they are
for x in classes:
if Class_To_Remove.capitalize() in x:
classes.remove(Class_To_Remove.capitalize())
print("Class removed")
else:
print("Class isn't added")
If I understand everything correctly this will replace your:
removeClass = input("Please select a class to remove: \n")
removeClass = removeClass.title()
removeClass = str(removeClass)
removeClass = removeClass.strip()
classGone = []
classGone = removeClass.split(",")
for i in range(len(classGone)):
classGone[i] = classGone[i].strip()
for item in classGone:
removeClass = []
inputCheck = classGone.count(removeClass)
if inputCheck > 0:
classes.remove(item)
else:
print("Please select a class that exists...")
For future reference try to only use the few lines you are having trouble with and explaining the problem more clear.
I've been trying to understand this for some time. For the next one please be more clear.
Since there's several mistakes on your code, I tried to make a solution that could work for you. Here it is!
global classes
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
for i in range(0, len(classes)):
print(i+1, ".", classes[i])
control = True
while control:
if(len(classes) < 5):
course = str(input("What course(s) would you like to take?: \n"))
classes += course.split(",")
for i in range(len(classes)):
classes[i] = classes[i].strip().title()
printClasses()
elif (len(classes) >= 5):
option = input("Do you want to remove a class?\n 1.Yes\n 2.No\n")
if option == "1":
classGone = []
for i in range(1):
removeClass = input("Please select a class to remove: \n")
if (removeClass == classes[0] or
removeClass == classes[1] or
removeClass == classes[2] or
removeClass == classes[3] or
removeClass == classes[4]):
classes.remove(removeClass)
classGone.append(removeClass)
print("Classes removed are: ", classGone)
printClasses()
i += 1
break
else:
print("Please select a valid class")
elif option == "2":
print("Done!")
break
Hope it works!

How to run the same python code for multiple input files

I have two output files which contain the same data (but different values). I'm using the following Python code to read them and return the data/value that I want:
upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")
fhr = open(upper)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
tot_upper = float(sabs)
print('Total upper:', tot_upper)
fhr.close()
fhr = open(lower)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
tot_lower = float(sabs)
print('Total lower:', tot_lower)
fhr.close()
Which gives me the output:
Total upper: x
Total lower: y
Is there are way that I can simplify the code such that I open the first file, run the code, then loop back to the beginning, open the second file and run the same code? Something like this:
upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")
file = [upper, lower]
for inp in file:
fhr = open(file)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
if inp == upper:
tot_upper = float(sabs)
print('Total upper:', tot_upper)
elif inp == lower:
tot_lower = float(sabs)
print('Total lower:', tot_lower
fhr.close()
I still want the same output:
Total upper: x
Total lower: y
You could do this:
for label in 'upper', 'lower':
# Ask for filename, using the label.
# Process the file.
# Print the result, using the label.
You probably need to use functions:
upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")
def f(name, s): # idk what is the function for so change to a custom name
fhr = open(name)
for line in fhr:
word = line.rstrip().split()
if len(word) > 1 and word[1] == '1:47':
try:
sabs = word[2]
except:
continue
tot = float(sabs)
print(f'Total {s}:', tot)
fhr.close()
f(upper, 'upper')
f(lower, 'lower')

Search within a dictionary with a lot of values in python

In the following code I'm showing a function that lets you add students to a dictionary (book) with rut being the key, the issue I have is that I'm trying to make a function that can search by department and then print all students of that are part of that department, basically I'm asking how do you search a dictionary with 1 key that is associated to a lot of values and you want to search for a particular value and then print all keys that have it along with their info?
book = {}
def add(rut, name, age, department):
student = {}
student['rut'] = rut
student['name'] = name
student['age'] = age
student['department'] = department
book[rut] = student
def printall():
for rut in book:
student = book[rut]
print(student['rut'], student['name'], student['age'], student['department'])
def main():
count = 0
x = 0
y = int(input("How many students will you add?: "))
while count < y:
print('Input data of the student: ', count+1)
rut = input("rut: ")
name = input("name: ")
age = int(input("age: "))
print("Department 1: RH, 2: Logistic, 3: Cleaners, 4: TI ")
department = ''
while x == 0:
num_dept = int(input("department number: "))
if num_dept == 1:
department = "RH"
x = 1
elif num_dept == 2:
department = "Logistic"
x = 1
elif num_dept == 3:
department = "Mathematics"
x = 1
elif num_dept == 4:
department = "TI"
x = 1
else:
print('Error')
x = 0
add(rut, name, age, department)
count = count + 1
printall()
main()
You can use a list comprehension.
students = [student for student in book.values()
if student["department"] == desired_department]
This will give you a list, which you can then print out if you so choose.

Running my code and nothing is showing

I fixed most of my code but the only problem I'm having is that none of the text is showing. I'm supposed to input golfer names and their scores but nothing shows up when I run the program.
def main():
inGolf = open('golfers.txt', 'r')
names = []
scores = []
for line in inGolf:
line_list = line.split(",")
names.append(line_list[0])
scores.append(line_list[1])
for i in range(len(names)):
print ("{0:20}{1:10}".format(names[i], scores[i]))
inGolf.close()
def w(numPlayers):
counter = 0
outGolf = open('playerData.txt', 'w')
while counter < numPlayers:
name = raw_input("Please enter the player's name:")
outGolf.write(name + ",")
score = input("Please enter that player's score:")
outGolf.write(str(score) + "\n")
counter = counter + 1
outGolf.close()
main()
I have slightly modified this script to try it here and it actually worked:
It prompts the players' names and scores by players number.
It saves the players file
It reads the players file and show scoring results.
I had to change raw_input to input as for Python3 and called the w function passing a number of player by user inputs:
def main():
num_players = input("How many players?")
w( int(num_players) )
inGolf = open('golfers.txt', 'r')
names = []
scores = []
for line in inGolf:
line_list = line.split(",")
names.append(line_list[0])
scores.append(line_list[1])
for i in range(len(names)):
print ("{0:20}{1:10}".format(names[i], scores[i]))
inGolf.close()
def w(numPlayers):
counter = 0
outGolf = open('golfers.txt', 'w')
while counter < numPlayers:
name = input("Please enter the player's name:")
outGolf.write(name + ",")
score = input("Please enter that player's score:")
outGolf.write(str(score) + "\n")
counter = counter + 1
outGolf.close()
main()

Python dictionary if/else invalid syntax

I cant figure out why line 104 keeps returning invalid syntax, can someone please point me in the right direction? Does it have something to do with the way i used elif? Sorry if this is a newbie question!
Line 104 is the else statement in the for item in workingDict.keys() loops inside printGrammar
import sys
import string
from collections import defaultdict
#default length of 3
stringLength = 3
#get last argument of command line(file)
if len(sys.argv) == 1:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
elif len(sys.argv) == 2:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = sys.argv[1]
except ValueError:
print("Not a number")
elif len(sys.argv) == 3:
filename = sys.argv[2]
stringLength = sys.argv[1].split('l')[1]
else:
print("Invalid input!")
#get start symbol
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
start = lines[0].split('=')[0]
start = start.replace(" ", "")
#checks
#print(stringLength)
#print(filename)
#print(start)
def str2dict(filename):
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
line = line.rstrip()
result[line[0]].append(line.split('=')[1])
return result
workingDict = str2dict("Binary.txt")
print(workingDict)
def printGrammar(result):
sentenceList = []
workList = []
workList.append(start)
i = 0
firstNT = ""
#While the worklist is not empty:
while(len(workList) != 0):
#Get and delete one potential sentence s from the worklist.
symbol = workList.pop()
#If the | s | > N, continue.
if len(str(symbol).replace(" ", "")) > int(stringLength):
continue
else:
if str(symbol) in workingDict.keys():
#append the right derivation
for item in workingDict.get(symbol):
workList.append(list(item.replace(" ", "")))
#workList.append(str(workingDict.get(symbol)))
#add derivation
print(workingDict.keys())
#If s has no nonterminals, print s and continue.
for item in workingDict.keys():
print("test")
print(''.join(item))
if len(item) != 1:
continue
#if the element is in dictionary, dont print
elif ''.join(item) in workingDict.keys():
continue
print(symbol)
#if element is not in dictionary, print
else:
print("THIS IS A TERMINAL!!")
print(item)
#Choose the leftmost nonterminal NT.
print(workList)
#For all productions NT -> rhs:
#Replace NT in s with rhs; call it tmp.
#Store tmp on worklist.
return workList
print (printGrammar(workingDict))
You need to indent the line
print(symbol)
to the same level as continue.

Categories