How do I import my own object in vs studio code? - python

I'm trying to import the Human object I created for my contact book program and im doing it in VS Studio Code but it gives me an error:
Import "Human" could not be resolved
I tried to make the program in pycharm instead and it imported just fine and I even finished the program. And while looking around for a solution for the VS Studio Code version, I found some stuff like adding
"python.autoComplete.extraPaths": ["./**"],
to my settings.json and I did and a few other things i found on google, but it nothing helped.
VS Studio Code:
from Human import Human
#from Contact_Book_Project.Human import Human # auto generated, Not sure how it is different but i do have these 2 classes in a folder called Contact_Book_Project
book = []
def main():
while (True):
choice = int(input("Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
def addPerson(person):
book.append(person)
if __name__ == "__main__":
main()
class Human:
def __init__(self, name, phone_Number, address):
self.Name = name
self.Phone_Number = phone_Number
self.Address = address
def getName(self):
return self.Name
def getPhoneNumber(self):
return self.Phone_Number
def getAddress(self):
return self.Address
PyCharm Code:
from Human import Human
book = []
def main():
while (True):
try:
choice = int(input(
"Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to "
"list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
elif (choice == 2):
name = input("Enter name of person to remove: ")
temp = 0
for i in book:
if i.getName() == name:
book.pop(temp)
print(i.getName() + " removed.")
break
temp += 1
# elif (choice == 3):
# name = input("Enter name of person to check if they are in your contact book and retrieve their "
# "information: ")
#
# if name in book:
# temp = book.__getitem__(name)
# print(
# "Name: " + temp.getName() + "\nPhone Number: " + temp.getPhoneNumber() + "\nAddress: " + temp.getAddress())
# else:
# print(name + " does not exist in your contact book.")
elif (choice == 4):
for p in book:
print(
"Name: " + p.getName() + "\nPhone Number: " + p.getPhoneNumber() + "\nAddress: " + p.getAddress() + "\n")
except ValueError:
print("\nInvalid input.\n")
def addPerson(person):
book.append(person)
if __name__ == '__main__':
main()
both are using the same Human class. How can I fix this? Why is it throwing an error in VS Studio but work in Pycharm?

Maybe try directing VS Code to the exact location of the Human module:
import sys
sys.path.append('file path to Human.py') # Add file path to 'Human.py' here
from Human import Human

Related

Class Attributes not updating in program

I am fairly new to coding on Python. In my code, I am trying to change the myPlayer.hp and myPlayer.sp values based on what the myPlayer.job is. But, for some reason, regardless of job, the HP and SP values are still 0 when I check them in the program. If you know how to change them, please let me know and thank you.
Here is the code that deals with my question:
class player:
def __init__(self):
self.name = ''
self.job = ''
self.hp = 0
self.sp = 0
self.pwr = 0
self.res = 0
self.agi = 0
self.smr = 0
self.wll = 0
self.status_effects = []
self.location = 'b2'
self.game_over = False
myPlayer = player()
def main_game_loop():
while myPlayer.game_over is False:
prompt()
def setup_game():
os.system('cls')
question1 = "Hello, what's your name?\n"
for character in question1:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
player_name = input("> ")
myPlayer.name = player_name
question2 = "Hello, what role do you want to play?\n"
question2added = "(You can play as a warrior, mage, or priest)\n"
for character in question2:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
for character in question2added:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.01)
player_job = input("> ")
valid_jobs = ['warrior', 'mage', 'priest']
if player_job.lower() in valid_jobs:
myPlayer.job = player_job
print("You are now a " + player_job + "!\n")
while player_job.lower() not in valid_jobs:
player_job = input("> ")
if player_job.lower() in valid_jobs:
myPlayer.job = player_job
print("You are now a " + player_job + "!\n")
if myPlayer.job == 'warrior':
myPlayer.hp = 25
myPlayer.sp = 0
elif myPlayer.job == 'mage':
myPlayer.hp = 15
myPlayer.sp = 20
elif myPlayer.job == 'priest':
myPlayer.hp = 20
myPlayer.sp = 15
Your code isn't necessarily incorrect, but there is a good chance for an error when the player enters their job.
You have the following code:
if player_job.lower() in valid_jobs:
That means that if the player enters Warrior you understand that they meant warrior. That is good. But when you assign the player's job you do the following:
myPlayer.job = player_job
That can cause a problem, since you aren't calling lower() on the job.
Instead, you likely want:
myPlayer.job = player_job.lower()
That way, when you look at the player's job to assign sp and hp it will match the lowercase strings you are comparing it to.

No attribute present

I am quite new to python and I am getting an attribute error.
import FileHandeling as fh;
import os;
CounterFilePath = os.path.dirname(os.path.realpath(__file__))+"/counter.txt";
FilePath = os.path.dirname(os.path.realpath(__file__))+"/FileIO.txt";
class Employee:
def createEmployee(self):
numOfEmployees = int(input("Enter number of employees: "));
empDetails = [];
for i in range(numOfEmployees):
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
string = str(i)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
empDetails.append(string);
with open(FilePath,"a+") as fo:
fo.seek(0);
fh.createFile(fo,numOfEmployees,empDetails,CounterFilePath);
def searchEmployee(self):
choice = int(input("Press:\n1 to search by First Name\n2 to search by Last Name\n3 to search by Salary\n4 to search by Email ID\n"));
print "Enter the",;
if(choice == 1):
print "First Name:",;
elif(choice == 2):
print "Last Name:",;
elif(choice == 3):
print "Salary:",;
elif(choice == 4):
print "Email ID:",;
searchStr = raw_input();
with open(FilePath,"r") as fo:
string = fh.readFile(fo,searchStr,choice-1);
while line in string:
print line;
def updateEmployee(self):
print "Leave the entries empty if you dont want to update that entry.";
lineNum = input("Enter the line number of the entry you want to update: ");
with open(FilePath,"r") as fo:
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
if(empFName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empFName = empDetails[1];
if(empLName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empLName = empDetails[2];
if(empSalary == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empSalary = empDetails[3];
if(empEmailId == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empEmailId = empDetails[4];
updateStr = str(lineNum-1)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
fh.updateRecord(fo,FilePath,updateStr,lineNum-1);
def deleteEmployee(self):
lineNum = input("Enter the line number of the entry you want to delete: ");
with open(FilePath,"r") as fo:
fh.deleteRecord(fo,FilePath,lineNum-1);
def main(self):
goOn = True;
employee = Employee();
while goOn:
choice = input("Press:\n1 to enter a new employee\n2 to search employee\n3 to update employee\n4 to delete employee\n0 to exit\n");
if(choice == 1):
employee.createEmployee();
elif(choice == 2):
employee.searchEmployee();
elif(choice == 3):
employee.updateEmployee();
elif(choice == 4):
employee.deleteEmployee();
elif(choice == 0):
goOn = False;
else:
print "Wrong Choice!!!";
emp = Employee();
emp.main();
Here I am importing this class:
class FileHandeling:
def createFile(fo,numOfRecords,data,counterFile):
#Getting the value of counter
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
#Taking input and writing to the file
for i in range(counter,numOfRecords+counter):
string = str(i)+data[i];
fo.write(string);
counter += 1;
#Writing back to counter the updated value.
fwc = open(counterFile,"w");
fwc.write(str(counter)+"\n");
fwc.close();
def readFile(fo,searchStr,criteria):
line = fo.readline();
string = [];
while line:
entries = line.split();
if(searchStr == entries[criteria]):
string.append(line);
line = fo.readline();
return string;
def printFile(fo):
fo.seek(0);
lines = fo.readlines();
print "The File: "
for line in lines:
print line;
def updateRecord(fo,fileLoc,updateStr,lineNum):
#Replacing the given record with he updated record and writing back to file
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines[lineNum]= updateStr;
for line in lines:
fwu.write(line);
fwu.close();
def deleteRecord(fo,fileLoc,lineNum):
#Deleting the record
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines.pop(lineNum);
#Correcting the Employee Ids and Writing Back to File
for line in lines:
entry1, entry2, entry3, entry4, entry5 = line.split();
entry1 = str(lines.index(line));
line = entry1+" "+entry2+" "+entry3+" "+entry4+" "+entry5+"\n";
fwu.write(line);
fwu.close();
#Reducing Counter value
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
fwc = open(counterFile,"w");
fwc.write(str(counter-1)+"\n");
fwc.close();
In this code I am trying to replicate a database with the help of file but my code gives error saying that 'module' object has no attribute 'createFile'. I also tried creating packages and doing like in java but then it started saying that ImportError: No module named src.fileManipulation. they were just my folders in which I was working and wanted them as packages so I put an __init__.py in them and the tutorials said that this will help in making packages but that didn't happen and since both my files were in same directory I imported it directly but now it gives attribute error and I don't know what that means. Please Help.
I have executed the code in Python default IDLE after correcting some print statements. I am using Python3 so used print (" "). And the result was an endless loop of
Wrong Choice!!!
Press:
1 to enter a new employee
2 to search employee
3 to update employee
4 to delete employee
0 to exit
My kind requtest to you is to revise Python once again.

How to properly use __repr__ when two classes are involved

I am working on some Python code where I create a basic ATM. The issue I am having is I am not able to get the result that I want its printing "<'function Account.balance at 0x012CBC90>" Instead of the actual balance number. So far I have only tested using jsmith. Feel free to call out any other issues that may cause a problem later.
class Account:
def __init__(self,user,pin,balance):
self.user = user
self.pin = pin
self.balance = int(balance)
def get_user(self):
return self.user
def get_pin(self):
return self.pin
def balance(self):
return int(self.balance)
def setBalance(self,newBalance):
self.balance = newBalance
def __repr__(self):
return str(self.user) + " " + str(self.pin) + " " + str(self.balance)
class ATM:
def withdraw(self,Person,amount):
result = Person - amount
return result
def check(self,Person):
Person = Account.balance
return str(Person)
def transfer(self,id1,id2):
pass
def __str__(self):
return self
def main():
Chase = ATM()
Database = []
Teron_Russell = Account("trussell",1738,0)
Joe_Smith = Account("jsmith",1010,1350)
print(Teron_Russell)
Database.append(Teron_Russell)
Database.append(Joe_Smith)
print("Welcome to the ATM")
id = input("Please enter your user ID: ")
pin = input("Enter your pin: ")
chosen = ""
for i in Database:
print("Test1")
name = Account.get_user(i)
print(name)
checkPin = Account.get_pin(i)
print(checkPin)
if id == name and pin == checkPin:
chosen = i
choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")
if(choice == "Check" or "check"):
print(Chase.check(chosen))
# if(choice == "Withdraw" or "withdraw"):
# wAmount = eval(input("How much would you like to Withdraw: "))
# # Chase.withdraw(Account.balance,)
# elif(choice == "Check" or "check"):
# Chase.check()
# else:
# print("Invalid Choice!")
if __name__ == "__main__":
main()
You named a variable and a method the same name, so the interpreter is confused on which one to use. Change the name of either the method or variable balance and you won't have this problem. Additionally, this isn't java, and you shouldn't use classes for no reason. Since you aren't using any instance variables, it is pointless to have all of those methods inside that class.

How do I access the array using the for loop in the while loop

I am working with an external file which has data in the form of:
-12345 CSEE 35000 Bart Simpson
-12346 CSEE 25000 Harry Potter
-12350 Economics 30000 Krusty The Clown
-13123 Economics 55000 David Cameron
With the first item being the ID, the second the subject, the third the salary, and the rest being the name of the person.
In part of my program I am trying to print the information of the people who have salaries between values submitted by the user. I have put all the data in a list called lecturers then I put all the salaries in a separate list called lecturers salary and tried to make them integers because at first I thought the reason the for loop wasn't working was because when trying to access them from the lectures loop I thought they might still be part of a string at this point.
I have already used a loop in my program to print all the people who teach a specific subject. This subject is submitted by the user. I tried to use a for loop again for the salaries but its not working.
print""
# To God be the Glory
lecturer = []
lecturer_salary = []
x = 0
a = " "
print ""
String = raw_input("Please enter the lecturers details: ")
print ""
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
ID_Subject = " ".join(String[0:2])
money = String[2]
print "%s,%s %s %s" % (lastname,firstnames,ID_Subject,money)
printFormat(String)
while x < len(lecturer):
lecturer_salary.append(int(lecturer [x][2]))
x = x + 1
print ""
try:
fname = input("Enter filename within " ": ")
with open(fname) as f:
for line in f:
data = line.split()
printFormat(line)
line = line.split()
lecturer.append(line)
except IOError as e :
print("Problem opening file")
print ""
print ""
answer = raw_input("Would you like to display the details of lectureers from a particular department please enter YES or NO: ")
if answer == "YES" :
print ""
department = raw_input("Please enter the department: ")
print ""
while x < len(lecturer) :
for line in lecturer:
if lecturer[x][1] == department:
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
**elif answer == "NO" :
print ""
answer2 = raw_input ("Would you like to know all the lecturers within a particular salary range: ")
print ""
if answer2 == "YES":
lower_bound = int(input("Please enter the lower bound of the salary range: "))
upper_bound = int(input("Please enter the upper bound of the salary range: "))
print ""
while x < len(lecturer) :
for line in lecturer_salary:
if lower_bound < lecturer_salary[x] < upper_bound :
print lecturer_salary[x]
x = x + 1**
else:
print ""
print "Please enter a valid input"
So, you have an array of lecturer and one of lecturer salary. the
for line in lecturer_salary:
is not needed - just the while followed by the if. Note that this will only print out the salary, not the lecturer details. Since x is the index to both arrays you can access lecturer[x] for the rest. In truth you don't need the lecturer_salary at all, just walk through lecturer and check:
while x < len(lecturer) :
if lower_bound < lecturer[x][2] < upper_bound :
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
For starters, you shouldn't name your variable with a capital letter like String or Id_Subject.
It is simpler to break code into functions and try using a dictionary or class to improve readability and extensibility.
Here is a minimal code using class:
lecturers = [] # To store Lecturer instances, which isn't necessary
class Lecturer():
def __init__(self, id, subject, salary, name):
self.id = id
self.subject = subject
self.salary = salary
self.name = name
def readfile(filename):
"""read each line in a file and yield a list of fields"""
with open(filename, "r") as f:
for line in f.readlines():
# return a list of fields
yield line.replace("\n", "").split()
def new_lecturer(detail):
"""Return a new lecturer instance from a list of fields"""
return Lecturer(detail[0],
detail[1],
detail[2],
{"firstname": detail[3],
"lastname": detail[4]
})
def print_lecturer_detail(lecturer):
"""Accept a lecturer instance and print out information"""
print "{0},{1} {2} {3}".format(lecturer.name["lastname"],
lecturer.name["firstname"],
lecturer.id,
lecturer.salary)
def main():
"""This is where all the main user interaction should be"""
fname = raw_input("Enter filename: ")
for lecturer in (readfile(fname)):
lecturers.append(new_lecturer(lecturer))
print ""
answer = raw_input("Would you like to display lecturers by department(Y/N)?: ")
if answer == "Y":
print ""
department = raw_input("Please enter the department: ")
print ""
for lecturer in lecturers:
if lecturer.subject == department:
print_lecturer_detail(lecturer)
elif answer == "N":
# implement salary code here
pass
if __name__ == '__main__':
main()
This may be an overkill now, but it's better than dealing with lists in a long run. You'll see that dealing with properties become much simpler. You may want to improve each function further and make it more modular and reusable.
#Paul Morrington has the straight answer on the while part.

class in python 3 not working as expected

I have started work on a program that will allow a user to easily take pictures with the raspberry pi camera. The problem I am having is the class I have created does not do what I expected. When the code is run there is no output, what should happen is the Picture_Name_Settings function should be run. I'm still new to classes so I am probably missing something simple and the tutorials I have read online do not give a solution to my problem. Below is my code:
import picamera, time
class CameraController:
def _init_(self):
pass
def Picture_Name_Settings(self, user_name, automatic_name, name_setting):
pic_name = input("To name the image input N\nTo use automatic naming input A ")
pic_name = pic_name.upper()
if pic_name == "N":
user_name = input("Please enter the name of what you want your image to be called ")
name_setting = 1
if pic_name == "A":
current_time = (time.strftime("%H:%M:%S"))
current_date = (time.strftime("%d:%m:%Y"))
automatic_name = "".join(("Image taken at ", current_time, " on the ", current_date, ".jpg"))
name_setting = 2
def Camera_Capture(self):
self.Picture_Name_Settings(user_name, automatic_name, name_settings)
if name_setting == 1:
picture_name = user_name
if name_setting == 2:
picture_name = automatic_name
camera = picamera.PiCamera()
camera.capture(picture_name)
Declare user_name, automatic_name and name_setting variables as instance variables and you should be fine
class CameraController:
def _init_(self):
pass
def Picture_Name_Settings(self):
pic_name = input("To name the image input N\nTo use automatic naming input A ")
pic_name = pic_name.upper()
if pic_name == "N":
self.user_name = input("Please enter the name of what you want your image to be called ")
self.name_setting = 1
if pic_name == "A":
current_time = (time.strftime("%H:%M:%S"))
current_date = (time.strftime("%d:%m:%Y"))
self.automatic_name = "".join(("Image taken at ", current_time, " on the ", current_date, ".jpg"))
self.name_setting = 2
def Camera_Capture(self):
self.Picture_Name_Settings()
if self.name_setting == 1:
picture_name = self.user_name
if self.name_setting == 2:
picture_name = self.automatic_name
camera = picamera.PiCamera()
camera.capture(picture_name)

Categories