I fixed the issue with the spacing and have corrected other errors a long the way. Now it is doing what i want but what i select choice 2 it will print out the record of the employee 4 times. And if i enter another employee it will just print the second one and not the 1rst one as well.
class EmployeeClass:
def Employee(name, lastName, age, salary):
name = name
lastName = lastName
age = age
salary = salary
def displayEmployee(x):
print("Name: " + name + ", " + lastName)
print("Age: " + age)
print("Salary: " + salary)
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()
if choice == "1":
name = input ("Enter First Name: ")
EmployeeArray.append(name)
if name == "":
Continue = False
print ("Goodbye!")
break
lastName = input ("Enter Last Name: ")
EmployeeArray.append(lastName)
age = input ("Enter Age: ")
EmployeeArray.append(age)
salary = input ("Enter Salary: ")
EmployeeArray.append(salary)
elif choice == "2":
for Employee in EmployeeArray:
EmployeeClass.displayEmployee(Employee)
Continue = False
elif choice == "3":
print ("Bye!")
break
else:
print ("Please choose a valid option")
print ("\n")
Your error message will give you an indication about the line number where this problem is happening. Basically, you are mixing tabs and blank spaces, so you need to use only one of them consistently for indentation.
PEP8 - The Style Guide for Python recommends the use of spaces and also notes:
When invoking the Python command line interpreter with the -t option,
it issues warnings about code that illegally mixes tabs and spaces.
When using -tt these warnings become errors. These options are highly
recommended!
From briefly examining your source it seems that there are tabs in front of the print statements - replace those with blanks (that is also the reason they are not rendered correctly in the post above)
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
There might be other spots, you'll have to check carefully. In fact I suspect where your code doesn't show as correctly indented in your post might be worth a look.
In the order to avoid problems like this it's best to use an editor or IDE that will consistently indent for you with the same characters.
It looks like you need to indent everything after the first line.
I.E.
class Employee:
empCount = 0
def _init_(self, name, lastName, age, salary):
...
The problem is that you are using a tab character ('\t') to indent some lines, and four spaces (' ') to indent others.
This can be a problem, because a tab doesn't necessarily mean a given number of spaces - different editors may interpret it as the equivalent of 2 or 4 or 8 spaces (or really, any number of spaces it likes, but those are the most common choices). If you indent using only spaces, or only tabs, that is unambiguous and Python is happy. If you use a mixture, the meaning of your code will be different depending on how many spaces a tab character is equal to - so instead of guessing, possibly leading to strange errors, Python stops with the warning message you see.
The immediate solution is to use search-and-replace to replace every tab character with 4 spaces. The longer-term solution is to use a text editor which will automatically insert 4 spaces whenever you hit the tab key. (On Windows, I like Notepad++, but there are lots of other good ones too).
Never use tabs in Python, you can but it's not conventional. The PEP8 convention is to use four spaces.
Related
I have attached part of some python code that is designed to make 'decisions' based on user inputs. I currently cannot work out how to make the text file at the end (shown in the asterisks) have a name that is inputted by the user.
Also, sorry if this is worded confusingly- I am quite new to coding.
import csv
times = 1
Ops = []
print()
genre = input("Genre: ")
num = input("How many " + str(genre) + "s do I have to choose from? ")
**text_file= open(genre.txt, "w+")**
while int(times) <= int(num):
option = input("Option " + str(times) + ": ")
Ops.append(option)
text_file.write(option)
times = times + 1
print()
How would go about doing this???
After reading your code and attempting to understand it -- I think I know what you are trying to do, so here is my attempt and suggestions.
Remove "import csv" (not necessary), maybe later, not now.
It looks like you are creating a file based on the input into the variable "genre", so in the open statement should be: open(genre+".txt", "w+")
Instead of asking how many different options you will be inputting and writing to the file, let that be dynamic, and provide a end-of-input designation that will stop accepting options and write everything to the file.
Suggested code:
options = list()
genre = input("Genre: ")
option = ""
count = 1
while option != "done":
option = input("Option "+str(count)+": ")
if option != "done":
options.append(option)
count += 1
with open(genre+'.txt', 'w+') as text_file:
text_file.write("\n".join(options))
Explanations:
If using Python2, use raw_input() instead of input().
The while statement will continue to loop, accepting "options", and incrementing counter until you specify "done" by itself, which will not be included in the list of options, and the loop will end.
The "with" statement, tells python to execute everything indented under it with the context of the open file "text_file".
The ".join()" statement is an list operator that joins each element in the list with a "\n" which means "newline". So with a list of ["rock", "classical", "pop"] it would write: "rock\nclassical\npop\n" which when written to the file it will look like:
rock
classical
pop
I am using python 3.6.5
I want to input a variable which can take in name of the person with space. This is my code for it right now:
def addition():
with open('Directory.csv','a',newline='') as file:
w=csv.writer(file,delimiter=',')
def names():
name=input('Enter Name :')
n=0
for i in name:
if i.isalpha() or i.isspace():
n+=0
else:
n+=1
if n==0:
return name
else:
print('Error')
return names()
name=names()
But when I press enter without any value inputted, it still accepts it:
Enter Value of k : 2
Enter Name :
Enter Year of Birth :
What should be my code to correct this?
The basic problem here is that the loop for i in name: won't run if name is empty, leaving n at zero. The least invasive way to fix this is to check in the subsequent if:
if name and n == 0:
There are other improvements I'd recommend, starting with removing the recursive call in favor of a loop. A user could trigger a stack overflow by typing in bad characters enough times.
Rather than counting bad characters, you can break out of the loop early. This removes your dependence on n entirely:
def names():
while True:
name = input('Enter Name: ')
if name:
for i in name:
if not i.isalpha() or not i.isspace():
break
else:
return name
print('Error')
The else clause here is correctly matched to the for loop. It's a neat python trick for running code only if the loop didn't break.
There are less manual ways to check that a string contains only letters and spaces. The most popular likely being regular expressions, which are supported by the standard library. This would be a simple regex:
import re
...
name_pattern = re.compile('[a-zA-Z ]+')
...
def names():
while True:
name = input('Enter Name: ').strip()
if name_pattern.fullmatch(name):
return name
print('Error')
def headName():
print (Name[0].upper())
def tailName():
print (Name[1:].lower())
Name = input("Please enter a name ")
headName()
tailName()
That's my code; I want to know how to concatinate headName() and tailName(), so that they're on the same line. Thanks
You can't do that without rewriting the functions. The newline is added by print. Since you call print inside the functions, nothing you do outside the function can undo the newline that was already added inside.
A better idea is to have your functions return the values, and then do the printing outside:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print(headName(), tailName(), sep="")
Incidentally, what you are doing can also be accomplished directly with Name.title().
To print on the same line call them in one print statement, something like:
print(headName(), ' ', tailName())
You can also use string formatting, which in case that you wanted to customize further the output would give you more control over the outcome:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print('{}{}'.format(headName(), tailName()))
You can also try:
def headName():
print ((Name[0].upper()), end="")
This will cause your print function to end with nothing, instead of ending with a newline (default).
For more information: https://docs.python.org/3/whatsnew/3.0.html
I'm trying to make a quiz using a questions file, and a choice between two answer files. I am going to have the user choose between printing all questions and answers, or just a few randomly generated ones. My problem is that I am having trouble getting it to display as intended. I need for it to display like:
1. how many... etc.
a.answer
b.answer
c.answer
d.answer
e.none of the above
but I can't get the output right. the text files consists of the answers placed like this:
C,3,4,5,6
A,4O,30,20,10
E,65,245,456,756
so I have replaced the commas with spaces, and have been succesful displaying them as a row rather than one line by using \n in place of spaces.. but it won't work as some answers are more than one word. I also need to remove the letter before the answers (it's the correct answer) and place this into a list, and I'm really unsure of how to do this.
import random
def main():
print("Welcome to the Garbology Quiz \n")
quizfilecheck = input("First off, what is the quiz file name? ")
while quizfilecheck != "questions.txt":
quizfilecheck = input("File not found.. what is the correct quiz file name? ")
answerfilecheck = input("And now what answer file are you using? ")
while answerfilecheck != "american-answers.txt" and answerfilecheck != "metric-answers.txt":
answerfilecheck = input("File not found.. please enter the correct answer file name. ")
questionList = getData()
answerList = getFormat()
inputanswers = printinputanswers(questionList,answerList)
def getData():
with open("questions.txt") as questionFile:
questionList = questionFile.readlines()
return questionList
def getFormat():
formatchoice = input("\n Would you like the answers printed in metric or american format? (m or a): ")
formatchoice = formatchoice.lower()
while formatchoice != "a" and formatchoice != "m":
formatchoice = input("Invalid input, please enter a correct value (m or a): ")
formatchoice = formatchoice.lower()
if formatchoice == "a":
answerPath = "american-answers.txt"
else:
answerPath = "metric-answers.txt"
with open(answerPath) as answerFile:
answerList = answerFile.readlines()
return answerList
def printAllanswers(questionList,answerList):
for i in range(0,len(questionList)):
print(questionList[i])
print(''.join(map(str,answerList[i].replace(',',' ').replace(' ','\n'))))
allanswers = printAllanswers(questionList,answerList)
def printinputanswers(questionList,answerList):
numofquestions = input(" How many questions do you want to print? ")
if numofquestions.isdigit():
numofquestions = int(numofquestions)
for i in range(0,numofquestions):
randomnum = random.randint(0,len(questionList))
print (questionList[randomnum])
print(''.join(map(str,answerList[randomnum].replace(',',' ').replace(' ',' '))))
main()
***********output and i know I haven't called printallanswers() yet, I'm going to after I have the correct output working
First off, what is the quiz file name? questions.txt
And now what answer file are you using? metric-answers.txt
Would you like the answers printed in metric or american format? (m or a): m
How many questions do you want to print? 4
If every country consumed and threw away at the rate Americans do, how many planets' worth of resources would be required to meet the demand?
C 3 4 5 6
If every country consumed and threw away at the rate Americans do, how many planets' worth of resources would be required to meet the demand?
C 3 4 5 6
America is home to 4 percent of the world's children. What percentage of the world's toys do Americans buy and throw away?
A 4O 30 20 10
How many nonrecyclable Styrofoam cups do Americans throw away in a year?
D 5 billion 10 billion 15 billion 25 billion
code
def printsingleanswer(questionList,answerList):
randomnum = random.randint(0,len(questionList))
chars1= string.ascii_lowercase
answers=answerList[randomnum].split(',')[1:] #removes the answer letter
answers.append('none of the above')
print ('\n'.join(chars1[i]+'. '+answers[i] for i in range(len(answers))))
output
Would you like the answers printed in metric or american format? (m or a): m
a. 5 billion
b. 10 billion
c. 15 billion
d. 25 billion
e. none of the above
It's adding a new line before every "e" choice, is there a way to keep it grouped together like the first four choices?
For answer sets that do not have commas, how about:
import string
chars1= string.ascii_lowercase
answers=answerList[randomnum].strip().split(',')[1:] #removes the answer letter
answers.append('none of the above')
print '\n'.join(chars1[i]+'. '+answers[i] for i in range(len(answers)))
The statement:
chars1[i]+'. '+answers[i],
adds a character to the beginning of each answer, and as string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' this will give a alphabetic character to every answer starting with 'a'.
If there are commas then you have to store the file as a full csv and use the csv module to load the file and then rather than using a split as in the code above, you just use each row from the extracted csv.
I'd like to receive a list of user aliases for the purpose of looking up an email. As of now, I can do this for only 1 input with the following code:
def Lookup(Dict_list):
user_alias = raw_input("Please enter User Alias: ")
data = []
for row in Dict_list:
#print "row test"
#print row
if user_alias in row.values():
print row
for row in Dict_list:
if user_alias == row['_cn6ca']:
email = row['_chk2m']
print email
return email
But I want to be able to have the user enter in an unknown amount of these aliases (probably no more than 10) and store the resulting emails that are looked up in a way that will allow for their placement in a .csv
I was thinking I could have the user enter a list [PaulW, RandomQ, SaraHu, etc...] or have the user enter all aliases until done, in which case they enter 'Done'
How can I alter this code (I'm guessing the raw_data command) to accomplish this?
This will accept input until it reaches an empty line (or whatever sentinel you define).
#! /usr/bin/python2.7
print 'Please enter one alias per line. Leave blank when finished.'
aliases = [alias for alias in iter (raw_input, '') ]
print (aliases)
You can ask the user to enter a list of aliases, separated by spaces, and then split the string:
In [15]: user_aliases = raw_input("Please enter User Aliases: ")
Please enter User Aliases: John Marry Harry
In [16]: for alias in user_aliases.split(): print alias
John
Marry
Harry
In [17]:
In case the user aliases can have spaces in them, ask them to use, say, a comma as a separator and split by that: user_aliases.split(',')