I am new to programming. I am currently taking python in school right now and I ran into a error and I figure it out. I keep getting a syntax error and I am not sure if it is typo on the instructor or myself.
def main():
num_emps=int(input("How many employee records? "))
empfile=open("employee.txt","w")
for count in range(1,num_emps+1):
print("Enter data for employee#",count,sep='')
name=input("Name: ")
id_num=input("ID Number: ")
dept=input("Department: ")
empfile=write.(name+"\n")
empfile=write.(id_num+"\n")
empfile=write.(dept+"\n")
print()
empfile.close
print("Employee records written to disk")
main()
I keep getting the error at
empfile=write.(name+"\n")
or is it supposed to be
empfile.write(name+"\n")
Thanks for the help
Use empfile.write() instead of empfile=write.()
Corrected and optimized version:
def main():
# indentation was missing in your question:
num_emps = int(input("How many employee records? "))
empfile = open("employee.txt","w")
for count in range(num_emps): # range from 0 to num_emps-1
print("Enter data for employee #{}:".format(count)) # use str.format(...)
name = input("Name: ")
id_num = input("ID Number: ")
dept = input("Department: ")
empfile.write(name + "\n")
empfile.write(id_num + "\n")
empfile.write(dept + "\n")
# alternative using Python 3's print function:
# print(name, file=empfile) # line-break already included
print()
empfile.close() # to call the function, you need brackets () !
print("Employee records written to disk")
main()
Also, there's not really a need to write a main() function in your example. You could have put the code directly into the file.
And if you want a proper main() function, use this construct to call it:
if __name__ == "__main__":
main()
else:
print("You tried to import this module, but it should have been run directly!")
It is used to determine whether a script was invoked directly or imported by another script.
Related
I am learning coding in Python. I am facing an issue today. My code is showing output correctly but it is showing a warning. I don't know where is the fault. Please help me to solve it.
Code:
class Info:
Name = ""
Roll = ""
Section = ""
Department = ""
Session = ""
University = ""
def display(a, b, c, d, e, f):
print(f"Name: {a}")
print(f"ID: {b}")
print(f"Section: {c}")
print(f"Department: {d}")
print(f"Session: {e}")
print(f"University: {f}")
Code = input("Enter Code: ")
Code = Info() # Error in this line
Code.Name = input("Enter Name: ")
Code.Roll = input("Enter ID: ")
Code.Section = input("Enter Section Name: ")
Code.Department = input("Enter Department Name: ")
Code.Session = input("Enter Session: ")
Code.University = input("Enter University Name: ")
display(Code.Name, Code.Roll, Code.Section, Code.Department, Code.Session, Code.University)
Error is showing in this line Code = Info()
Error message:
How can I solve this problem?
The warning message from your IDE's linter tells you:
Redeclared "Code" defined above without usage.
Code is defined by your input() function call. But then you define Code again immediately by calling Info(), without ever using the result of calling input().
Because you are reassigning the same variable (Code) on 2 consecutive lines.
You Can remove first line
Code = input....
The warning message is showing up because you define a variable called Code in which you store the input on this line:
Code = input("Enter Code: ")
but then you never actually use it, since you redefine it in the next line:
Code = Info()
As you noticed this may not cause any errors, but many modern code editors warn you about unused variables. In your case you should ask yourself what is the purpose of the user input and why aren't you using it anywhere?
My aim:
To create a python Modules with 3 functions:
Sample input1: bob
output:
Yes it is a palindrome
No. of vowels:1
Frequency of letters:b-2,o-1
=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
ch = input("Enter a character: ")
if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
In a new file I am giving :
import test
def main():
while True:
word = input("enter a word")
test.isPalindrome(word))
test.count_the_vowels(word))
if __name__ == "__main__":
main()
If I call my module in another file, it automatically does all the functions. But I want to give input(name) in this new module and check the output for it.But this is asking input again since name is present before def function in the other file. How to overcome this?
I am new to coding.Please be as elaborate as possible.Thanks in advance.
If you're question is "how to ask for the name only once and pass it to both function", the answer is simple: in your main.py script (or test.py or however you named it), add this:
import yourmodule # where you defined your functions
def main():
while True:
word = input("enter a word (ctrl+C to quit) > ")
yourmodule.isPalindrome(word)
yourmodule.count_the_vowels(word)
# etc
if __name__ == "__main__":
main()
Now note that your assignment doesn't say you have to do this - it says:
Import the module in another python script and test the functions by passing appropriate inputs.
Here, "passing appropriate inputs" can also be understood as having a harcoded list of words and calling your functions with those names... IOW, a unit test.
After trying several times to explain in the comments here is a brief example. so make a file with your functions. then in your other file import your funcs file then ask user for name and pass it to the funcs. This is just an example of how to define functions in one file and then call them from another. you probably want to look at your funcs as they should probably return values rather then just print stuff otherwise your calling file wont be able to validate the function since it will receive nothing back.
MyFuncs.py
def hello(name):
print(f"hello {name}")
def goodbye(name):
print(f"goodbye {name}")
stackoverflow.py
import MyFuncs
name = input("Name: ")
MyFuncs.hello(name)
MyFuncs.goodbye(name)
**OUTPUT: **when running the stackoverflow.py script
Name: Chris
hello Chris
goodbye Chris
names=["aaa","bbb","ccc","ddd","eee"]
itMarks=[90,98,87,98,78]
def printMainMenu():
print(" Main Menu")
print(" =========")
print(" (1)Add Student")
print(" (2)Search Student")
print(" (3)Delete Student")
print(" (4)List Student")
print(" (5)Exit")
choice = int(input("Enter Your choice[1-5]:"))
return choice
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(names)
print("Index is" + i)
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(names)
print("Successfully Deleted" + names)
def removeStudent(names):
name = input("Enter name to remove")
name.remove(name)
print("Successfully deleted" + names)
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(names)
itMarks = input("Enter IT Marks")
itMarks.append(itMarks)
def listStudent(names, itMarks):
for i in range(0, len(names)):
print(names[1], "", itMarks[i])
names = []
itMarks = []
choice = 1
while choice >= 1 and choice <= 4:
choice = printMainMenu()
if choice == 1:
addStudent(names, itMarks)
elif choice == 2:
searchStudent(names, itMarks)
elif choice == 3:
deleteStudent(names, itMarks)
elif choice == 4:
listStudent(names, itMarks)
elif choice == 5:
print("Exit from the program")
else:
print("invalid choice!")
choice = 1
I am new to the programming in Python. The following Python code is written to do some tasks with the array. There are two array named names and itMarks. And there are some functions :
addStudent() - To add students to the array
searchStudent() - To search a student with in the list.
deleteStudent() - To delete the given student from the list.
listStudent() - To list out the all the names of the students in the list.
When the program runs, it asks to select a choice. Then it do the task according to their choice. But when I run this coding it shows the errors.
Please help me. Thanks in advance.
ERROR :
When I select the choice 1 (Add student) and input name after the error is yield.
Traceback (most recent call last):
File "C:\Users\BAALANPC\Desktop\new 3.py", line 59, in <module>
addStudent(names, itMarks)
File "C:\Users\BAALANPC\Desktop\new 3.py", line 42, in addStudent
name = input("Enter Name")
File "<string>", line 1, in <module>
NameError: name 'rtrt' is not defined
Their so many mistakes in naming
In addStudent
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(name) # names cant appent it should be name
itMark = input("Enter IT Marks") # here itmark not itMarks
itMarks.append(itMark)
In searchStudent
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name) # try to find index of name not names
print("Index is" + i)
In deleteStudent
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name) # try to remove name not names
print("Successfully Deleted" + name)
after change above I run its running you have to also change the naming of the variable for all methods
Output
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:1
add student
Enter Name"aaa"
Enter IT Marks111
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:
I'm assuming this is the correct form:
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name)
print("Index is" + i)
note that I changed names to name.
also the same mistake again
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name)
print("Successfully Deleted" + names)
tl;dr revise your code
searchStudent(): You shouldn't need the itMarks argument if you're not using it inside your function at all. names refers to the list of names, but you are really trying to search name. i is an integer that is attempting to be concatenated with a string. Not allowed. It should be str(i).
deleteStudent(): Better to keep your arguments consistent and use names rather than student. Again, same problem as above, should be .remove(name) and you shouldn't need the itMarks argument. print statement should refer to name not names.
removeStudent(): This is the same code as deleteStudent(), but not used, so not sure why it's there.
addStudent(): Typo in the argument, .append(name). You have a global variable and a local variable named the same thing, which are conflicting to the program. Change the input set to itMark and .append(itMark).
listStudent(): print statement has a typo, 1 should be i. Not sure why the empty string is included as well.
Underneath your function def's, you restate your variables as empty lists. This can lead to ValueErrors from a lot of your functions as you're trying to look something up or modify something in an empty list. Simply delete this code.
Additionally, any error will break your while loop. I suggest adding more booleans or using a try except clause to catch these errors.
Good luck!
My code does not write to a file, what am I doing wrong? I am trying to program to continue to ask for products until the user does not enter a product code. I want all products to be saved in the file.
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
contine = input("Press 1 to enter a new product press 2 to leave: ")
if contine == "1":
print("Enter your product information")
information = []
product = input("What's the product code: ")
information.append(product)
description = input("Give a description of the product: ")
information.append(description)
price = input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean)
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close
I got the program working with the following adjustments. See comments for explanations:
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
continue = raw_input("Press 1 to enter a new product press 2 to leave: ")
#Changed to raw_input because input was reading in an integer for 1 rather than a
#string like you have set up. This could be specific to my IDE
if continue == "1":
print("Enter your product information")
information = []
product = raw_input("What's the product code: ")
information.append(product)
description = raw_input("Give a description of the product: ")
information.append(description)
price = raw_input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean + "\n")
#Added a line break at the end of each file write
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close() #Added parentheses to call the close function
I'm assuming the problem here is that you're using Python 2, and input isn't doing what you think it does. In Python 2, input evals the input as if it were Python source code, so if someone enters 2, it's going to return the int value 2, not "2". In Python 2, you want to use raw_input, always (eval-ing random user input not being secure/reliable).
Also, while on CPython (the reference interpreter) files tend to naturally close themselves when they go out of scope, you made an effort to close, but forgot to actually call the close method; store_file.close looks up the method without calling it, store_file.close() would actually close it. Of course, explicit close is usually the wrong approach; you should use a with statement to avoid the possibility of forgetting to close (or of an exception skipping the close). You can replace:
store_file = open("Database.txt", "w")
...
store_file.close()
with:
with open("Database.txt", "w") as store_file:
... do all your work that writes to the file indented within the with block ...
... When you dedent from the with block, the file is guaranteed to be closed ...
There are other issues though. What you're doing with:
information = str(information)
information = information.replace("]","").replace("[","").replace(",","").replace("'","")
is terrible. I'm 99% sure what you really wanted was to just join the inputs with spaces. If you switch all your input calls to raw_input (only on Python 2, on Python 3, input is like raw_input on Python 2), then your list is a list of str, and you can just join them together instead of trying to stringify the list itself, then remove all the list-y bits. You can replace both lines above with just:
information = ' '.join(information)
Like I said in my previous question, I'm a python amateur. I've made a couple silly mistakes. I'm attempting to make a highly simple greeting program using Python 3.4 however I have encountered an error. The error I have is:
UnboundLocalError: local variable 'lastNameFunction' referenced before assignment
Here's my code (I know I probably don't need to post it all, but there isn't much of it):
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()
I'd appreciate any help and advice! Please take into consideration I am really new to this stuff. I'm also not quite sure on having a function inside of a function, but I thought it would be a fix so that the 'firstName' was available when entering the 'lastName'.
Thanks in advance! :)
You need to move the lastNameFunction declaration somewhere before you call it using lastNameFunction(), e.g.:
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
if __name__ == '__main__':
main()
You can also move it outside the main function, but you will then need to pass the firstName in using the function arguments:
def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
def main():
...
lastNameFunction(firstName)
...
Move your lastNameFunction to somewhere before the call. Ideally, you would place this above the main function.
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...
The problem is you called lastNameFunction() before you defined it in the while loop. Try defining the function outside the while loop.
The organisation of the whole program seems a little bit off.
Imports usually go at the top of the module.
Functions defined in functions are usually just for closures, which you a) don't need here and b) might be a bit advanced for your current experience level.
Recursive calls like your calling main() from within main() are wrong. When you adopt that style of control flow instead of a loop, you will eventually run into limitations of recursive calls (→ RuntimeError). You already have the necessary loop, so simply leaving out the elif branch already asks the user again for the first name.
running isn't used anywhere, so you can remove it and just use while True:.
I would move asking the user for ”anything” + the question if the input was correct into its own function:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()