I'm trying to make a few scripts of my own to practice what I'm learning. But I'm coming up with some issues on the following script.
#!/usr/bin/python
def empInfoEntry():
firstName = input("Enter Employee's First Name: ")
lastName = input("Enter Employee's Last Name: ")
address = input("Enter Employee's Address: ")
city = input("Enter Employee's City: ")
state = input("Enter Employee's Complete State: ")
zip = input("Enter Employee's Zip Code: ")
def empInfo():
empFirstName = empInfoEntry.firstName
empLastName = empInfoEntry.lastName
print (empFirstName + " " + empLastName)
empAddress = empInfoEntry.address
print (empAddress)
empCity = empInfoEntry.city
empState = empInfoEntry.state
empZip = empInfoEntry.zip
print (empCity + ", " + empState + " " + empZip)
empInfoEntry()
empInfo()
According to the error "unhandled AttributeError "'function; object has no attribute 'firstName'"
I've looked it up but most of the results I find are quite complex and confusing to grasp my issue here.
I know that when this script runs it starts with empInfoEntry()
It works since I can type all the info in.
however, empInfo() seems to give me that function error. I have tried also using a simple print (firstName) although I know that it's outside of the function. Even when I append it to print (empInfoEntry.firstName) it gives me an error.
I can imagine it's because there is no return but i'm still a bit confused about returns as simple as people claim.
Any eli5 responses would be appreciated but a full explanation will work as well.
Thanks.
Also using python 3.4 and eric 6 on windows 8
Firstly, try to use raw_input() instead of input().
According to the official documentation, input() is actually eval(raw_input()). You might want to know what is eval(), check the documentation, we do not discuss it here. Sorry I thought it was Python 2.
As it seems you are not far from start learning Python, I would not write a class for you. Just using functions and basic data structures.
If you are interested, check pep8 for the naming convention in Python.
#!/usr/bin/python
def enter_employee_info_and_print():
# use a dictionary to store the information
employee_info = {}
employee_info['first_name'] = input("Enter Employee's First Name: ")
employee_info['last_name'] = input("Enter Employee's Last Name: ")
employee_info['address'] = input("Enter Employee's Address: ")
employee_info['city'] = input("Enter Employee's City: ")
employee_info['state'] = input("Enter Employee's Complete State: ")
employee_info['zip'] = input("Enter Employee's Zip Code: ")
first_name = employee_info['first_name']
last_name = employee_info['last_name']
# pay attention that there is no space between `print` and `(`
print(first_name + " " + last_name)
address = employee_info['address']
print(address)
city = employee_info['city']
state = employee_info['state']
zip = employee_info['zip']
print(city + ", " + state + " " + zip)
# use this statement to run a main function when you are directly running the script.
if __name__ == '__main__':
enter_employee_info_and_print()
Try this. I think this is the sort of thing your'e looking for.
class InfoEntry(object):
def __init__(self):
self.first_name = input("Enter your first name:")
self.last_name = input("Enter your last name:")
def __str__(self):
return self.first_name + " " + self.last_name
me = InfoEntry()
print(me)
Although functions can have attributes, when you want something to hold information, the format of which you know a priori, the thing you want is a class
Related
Here is my code:
name = ' '
Nameval = name("Enter the victims IP address: ")
print("Hello, " + name)
I want this code to take the input from Nameval, store it in the "name" variable and then print the name variable. However, it wont work. How can I do this?
You need to use input([prompt]).
name = input("Enter the victims IP address: ")
print("Hello, " + name)
Your code is wrong. You are not asking for an input, try this.
name = input('Enter IP address: ')
print(f'Hello {name}')
F string are better than concatination
I have no idea what I am doing wrong. Here is the question:
● Write a Python program called “John.py” that takes in a user’s input as a String.
● While the String is not “John”, add every String entered to a list until “John” is entered.
Then print out the list. This program basically stores all incorrectly entered Strings in a
list where “John” is the only correct String.
● Example program run (what should show up in the Python Console when you run it):
Enter your name :
Enter your name:
Enter your name:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This is what I have so far:
name_list = [" "]
valid_name = "John"
name = str(input("please enter a name: "))
if name != valid_name.upper():
#name = str(input("please enter a name: ")
name_list.append(name)
name_list += name
elif name == valid_name.upper():
name_list.append(name)
name_list += name
print("Incorrect names that you have added: ")`enter code here`
print(name_list[0:])
You almost got it! just need to use a while loop instead of a if/else:
name_list = []
valid_name = "John"
name = str(input("please enter a name: "))
while name != valid_name:
name_list.append(name)
name = str(input("Incorrect! please enter a name: "))
print(f"Correct! Incorrect names that you have added: {name_list}")
I'm learning Python and I'm wondering how you would insert a name into a list and for it to be held in that variable so the script can identify if it's seen you before.
Any help would be much appreciated
# Default People Already In List at program start
list = ['Bob','Jim',]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again" + Name)
else:
list.insert(0, Name)
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(list)
Your should rename your variables - here a short correction of your code, although it is looking good already! I changed the insert to append as well!
But it will obviously forget since the list is always initialized with Bob and Jim in it, and then you ask for the name - if is not Bob or Jim, it is new and therefore appended. But then your program ends, so when you start it new, your list is only populated with Bob & Jim again. You could put the whole construct in a "while True" construct to make the same question multiple times until you dont want to anymore!
EDIT: included the while (you can enter it numerous times if you just press "Enter" for the question! and put the list in the beginning, so it will not be initialized every time you run a new name! and important: if you see someone for the first time, include the print in the else-clause, otherwise it will be printed everytime, even if you saw the name before!
name_list = ['Bob','Jim']
while True:
print("Hello, What\'s your name? ")
input_name = input("Enter your Name: ")
if str(input_name) in name_list:
print("Nice to meet you again, " + input_name)
else:
name_list.append(input_name)
print("Hi " + input_name + ", Nice too meet you for the first time.")
# Troubleshoot
print(name_list)
if str(input("Another name? ")) == '':
continue
else:
break
This is what I did. This works with a CSV file.
# Load from file
list = []
listfile = open('list.csv', 'r+')
for name in listfile:
list.append(name[:-1])
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again " + Name)
else:
print("Hi " + Name + ", Nice too meet you for the first time.")
listfile.write(Name + "\n") #adding to file
# Troubleshoot
print(list)
This will store it to a file, also its not a good practice to use built in functions and utilities as variable names. so I modified the name as lists
try:
with open("listofnames.txt","r") as fd:
lists=eval(fd.read())
except:
lists=[['Bob','Jim',]]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in lists:
print("Nice to meet you again", Name)
else:
lists.insert(0, Name)
with open("listofnames.txt","w") as f:
f.write(str(lists))
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(lists)
I've got a simple question but I can't really find a right solution for that.
I have a csv file that contains students' names and subjects for which they are registered:
name,subject1,subject2,subject3
Student1,MN1,MN2,MN3
Student2,BN1,BN2,BN3
Student3,MN4,MN5,MN6
Student needs to enter his name and subject name in order to check whether he is registered or not for this subject
My code:
import csv
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
with open('students.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['name'] == Name and row['subject1'] == Subject or
row['subject2'] == Subject or row['subject3'] == Subject):
print ("You are registered. It won't take long to run your VM")
else:
print ("You are not registered")
My problem is that it gives multiple outputs to me
Output:
Please provide your name: Student3
Please provide your Subject: MN4
You are not registered
You are not registered
You are registered. It won't take long to run your VM
Obviously, it should be just:
You are registered. It won't take long to run your VM
Could you please help me to solve this problem?
Thank you
Note that for loops in Python have an optional else clause that will execute when the loop ends without a break statement...
Your code prints each iteration of the loop. What you want is to print only at the end of the loop...
with open('students.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['name'] == Name and (row['subject1'] == Subject or row['subject2'] == Subject or row['subject3'] == Subject)):
print("You are registered. It won't take long to run your VM")
break
else:
print("You are not registered")
I believe a dictionary will work best for you:
import csv
data = {i[0]:i[1:] for i in csv.reader(open('filename.csv'))}
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
if Subject in data[Name]:
print("you are registered")
else:
print("you are not registered")
A dataframe will be a good structure to store you csv file. Please give it a read here, anyway coming to your code. Please refer the below code.
Please install pandas and numpy for this
pip install pandas
pip install numpy
Code:
import pandas as pd
import numpy as np
df = pd.read_csv("testing.csv")
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
query = '(name == '+ '\'' + Name + '\'' + ') and (subject1 == '+ '\'' \
+ Subject + '\'' + ' or subject2 == ' + '\'' + Subject + '\'' \
+ ' or subject2 == ' + '\'' + Subject + '\')'
if df.query(query).empty:
print ("You are registered. It won't take long to run your VM")
else:
print ("You are not registered")
Reference:
pandas query
I'm basically running a code that builds up an address book into a text file through user entries.
While doing so, I'm checking to see if the inputed information is correct and, in the case that it's not, asking them to correct it. However, I realize that it's possible (though unlikely) that a user could input incorrect information an indefinite number of times and so I'm looking to implement a "while" loop to work around this.
In the case of the code below, I'm basically attempting to have it so that instead of the first ifelse entry I can enter into a loop by checking for the boolean value of "First_Name.isalpha():". However, I can't really think of a way to enter into it as when "First_Name.isalpha():" is true I don't need to enter into the loop as the entry is correct. When it's false, we skip over the loop altogether without having the entry corrected.
That basically prompts the question of whether or not there is a way to enter into a loop for when a boolean value is false. Or, if there's another creative solution that I'm not considering.
Thanks,
A Novice Coder
NewContact = "New Contact"
def NewEntry(NewContact):
# Obtain the contact's information:
First_Name = input("Please enter your first name: ")
Last_Name = input("Please enter your last name: ")
Address = input("Please enter your street address: ")
City = input("Please enter your city of residence: ")
State = input("Please enter the 2 letter abbreviation of your state of residence: ")
ZipCode = input("Please enter your zip code: ")
Phone_Number = str(input("Please enter your phone number: "))
# Ensure all information inputted is correct:
if First_Name.isalpha():
First_Name = First_Name.strip()
First_Name = First_Name.lower()
First_Name = First_Name.title()
else:
First_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
if Last_Name.isalpha():
Last_Name = Last_Name.strip()
Last_Name = Last_Name.lower()
Last_Name = Last_Name.title()
else:
Last_Name = input("Please reenter your first name. Be sure to to include letters exclusively: ")
# Organize inputted information:
NewContact = Last_Name + ", " + First_Name
FullAddress = Address + " " + City + ", " + State + " " + ZipCode
# Return information to writer to ensure correctness of information
# Write information onto document
TheFile = open("AddressBook", "w")
TheFile.write(str(NewContact) + "\n")
TheFile.write(str(FullAddress) + "\n")
TheFile.write(str(Phone_Number) + "\n")
TheFile.close()
NewEntry(NewContact)
You're looking for the not operator, which inverts a boolean value:
>>> not False
True
>>> not True
False
>>> not "".isalpha()
True
>>> not "abc".isalpha()
False
You can tack it on the front of any expression that's a valid condition for an if or while.
Use this structure
invalid = True
while invalid:
## get inputs
## validate inputs
## set invalid accordingly