class PersonalInfo:
def set_titles(self, title):
self.__titles = title
def set_names(self, name):
self.__names = name
def set_addresses(self, add):
self.__addresses = add
def set_ages(self, age):
self.__ages = age
def set_numbers(self, number):
self.__numbers = number
# Accessor methods
def get_titles(self):
return self.__titles
def get_names(self):
return self.__names
def get_addresses(self):
return self.__addresses
def get_ages(self):
return self.__ages
def get_numbers(self):
return self.__numbers
def main():
# references PersonalInfo object
info = PersonalInfo()
# stores values in the object
info.set_titles(input("Enter Mr, Mrs, Miss:"))
info.set_names(input("Enter full name:"))
info.set_addresses(input("Enter address:"))
info.set_ages(input("Enter age:"))
info.set_numbers(input("Enter number:"))
#displays values stored in object's fields
print("Name: " + info.get_titles() + " " + info.get_names() + "\n"
+"Address: " + info.get_addresses() + "\n"
+ "Birth: " + info.get_ages() + "\n"
+ "Number: " + info.get_numbers() + "\n")
main()
main()
I want this to be printed out 2 times since I have 2 users who will answer the questions, but I can't seem to understand how to save the input answers in a text file. Can someone please give me an example??:)
I'm such a noob at this
Change your main() to init(self): And call it twice if you need run it twice. You could write a method to output the data to a file instead of including it in init if you wanted to.
def __init__(self):
# stores values in the object
self.title = self.set_titles(input("Enter Mr, Mrs, Miss: "))
self.name = self.set_names(input("Enter full name: "))
self.age = self.set_ages(input("Enter age: "))
self.address = self.set_addresses(input("Enter address: "))
self.number = self.set_numbers(input("Enter number: "))
# displays values stored in object's fields
print("Name: " + self.get_titles() + " " + self.get_names() + "\n"
+"Address: " + self.get_addresses() + "\n"
+ "Birth: " + self.get_ages() + "\n"
+ "Number: " + self.get_numbers() + "\n")
# Appends data to file
outfile = open('data_from_user.txt','a')
outfile.write("Name: " + self.get_titles() + " " + self.get_names() + "\n")
outfile.write("Address: " + self.get_addresses() + "\n")
outfile.write("Birth: " + self.get_ages() + "\n")
outfile.write("Number: " + self.get_numbers() + "\n")
outfile.close()
person_1 = PersonalInfo()
person_2 = PersonalInfo()
# storing data inside string
string = 'NAME: {} \n Address: {} \n Birth: {} \n Number: {} \n'.format(info.get_titles(),info.get_names(),
info.get_addresses(),info.get_ages(),info.get_numbers())
# printing 2 times
print(string,string,sep='\n')
# writing in a file
x = open('filename','a')
x.write(string)
x.close()
Related
from datetime import datetime
from datetime import date
import datetime
import time
import math
seconds_Yearly = 3656060*24
seconds_Daily = 606024
seconds_Hourly = 60*60
minute = 60
eventName1 = input("What is the name of the first event?")
print(" ")
eventName2 = input("What is the name of the second event?")
print(" ")
event_Year1 = input("Which year is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Month1 = input("Which month [1-12] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Day1 = input("Which day [1-31] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Year2 = input("Which year is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Month2 = input("Which month [1-12] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Day2 = input("Which day [1-31] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Year1 = int(event_Year1)
event_Month1 = int(event_Month1)
event_Day1 = int(event_Day1)
event_Year2 = int(event_Year2)
event_Month2 = int(event_Month2)
event_Day2 = int(event_Day2)
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
event1_date = event1_dates.strptime((event_Year1), (event_Month1), (event_Day1), "d/m/Y")
print(str(event1_date))
print(" ")
event2_date = date((event_Year2), (event_Month2), event_Day2)
print(event2_date)
print(" ")
seconds_event1 = time.mktime(event1_date.timetuple())
print(seconds_event1)
print(" ")
seconds_event2 = time.mktime(event2_date.timetuple())
print(seconds_event2)
print(" ")
seconds_difference_rough = seconds_event2 - seconds_event1
seconds_difference = abs(seconds_difference_rough)
print(seconds_difference)
print(" ")
minutes_difference = seconds_difference/60
print(minutes_difference)
print(" ")
hours_difference = minutes_difference/60
print(hours_difference)
print(" ")
days_difference_rough = hours_difference/24
days_difference = abs(days_difference_rough)
print(days_difference)
print(" ")
years_difference_roughs = seconds_difference/seconds_Yearly
years_difference_rough = seconds_difference//seconds_Yearly
years_difference = abs(years_difference_rough)
years_difference_remainer = seconds_difference%seconds_Yearly
print(years_difference)
print(years_difference_roughs)
weeks_difference_parta = (days_difference/7)/52
weeks_difference_partb = weeks_difference_parta/years_difference_roughs
weeks_difference = abs(weeks_difference_partb)
print(weeks_difference)
months_difference_part1a = hours_difference/24/30.435
months_difference_part1aa = months_difference_part1a//1
months_difference_part1b = abs(months_difference_part1aa)
print(months_difference_part1b)
months_difference_part2a = (years_difference * 12) - months_difference_part1b
month_difference_roughs = (years_difference * 12) - months_difference_part1a
months_difference_part2b = abs(months_difference_part2a)
days_decimal, whole = math.modf(months_difference_part1a)
print(" ")
print(months_difference_part2b)
print(" ")
print(months_difference_part1a)
print(" ")
days_difference1a = days_difference/28
days_difference1ab = days_difference/30.45
days_difference1b = days_difference1ab//1
days_difference1c = (days_difference1a - days_difference1ab)
days_difference_total = abs(days_difference1b)
print(days_difference_total)
print(" ")
print(days_difference1ab)
week_difference = days_difference_total/7
week_difference_total = abs(week_difference)
print(week_difference_total)
print(" ")
#hours_one = hours_difference
def days ():
global days, days_remaing_negative, days_remaing_positve, days_remaing
if event_Year2 > event_Year1:
months_difference_rough = days_difference/(hours_difference/24/30.435)
months_difference = abs(days_difference_rough)
months_difference_remainer = seconds_difference%seconds_Daily
print(months_difference)
print(days_decimal)
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
days_remaing = abs(days_remaing)
print(days_remaing)
else:
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
print(days_remaing)
def weeks():
global days_remaing, days, new_week, new_days2
if days_remaing >= 7:
new_weeks = days_remaing/7
abs_new_week = abs(new_weeks)
new_week = new_weeks//1
new_week_decimal, whole = math.modf(abs_new_week)
new_days1 = new_week_decimal * 7
new_days2 = new_days1//1
print(new_week)
print(new_days2)
else:
new_week = 0
new_days2 = days_remaing
print(new_days2)
def difference():
global new_days2, new_week, months_difference_part1b, years_difference, eventName1, eventName2, days_remaing, days, new_week, months_difference_part2b
if event_Year2 > event_Year1 or event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("a")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("b")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 == event_Month1 and event_Day2 > event_Day1:
print("C")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
else:
print("D")
print(str(eventName1) + " " + "is" + " " + "on" + " " + str(event1_date) + " " + " " + "which is" + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "After" + " " + " " + str(eventName2))
days ()
weeks()
difference()
Are you trying to convert event1_dates?
from datetime import date
event_Year1=2020
event_Month1=1
event_Day1=30
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
print(event1_dates)
event1_date = event1_dates.strftime("%d/%m/%Y")
print(event1_date)
Output:
2020-01-30
30/01/2020
I can't get the data within each ticket object to print. What am I doing wrong? I've never used __dict__ beofre but do I need to? Output I am getting is
t1 = Ticket_1()
TypeError: __init__() missing 3 required positional arguments: 'Ticket_1', 'Ticket_2', and 'Ticket_3'
Code:
class Ticket: #creates ticket and makes a count of each ticket created
counter = 2000 # static field counter + 2000
counter += 1
ticket_number = counter
def __init__(self, Ticket_1, Ticket_2, Ticket_3):
self.Ticket_1 = Ticket_1()
self.Ticket_2 = Ticket_2()
self.Ticket_3 = Ticket_3()
class Ticket_1(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "martha"
staff_id = "MARTHAT"
email = "martha#whitecliffe.co.nz"
issue = "monitor is broken"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class Ticket_2(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "Not Specified"
staff_id = "PAULG"
email = "Not Specified"
issue = "need to change password"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class Ticket_3(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "Not Specified"
staff_id = "CARLH"
email = "carlhemmingway#whitecliffe.co.nz"
issue = "wifi isn't working"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class main:
t1 = Ticket_1()
t2 = Ticket_2()
t3 = Ticket_3()
myobj = Ticket(t1, t2, t3)
t1.display()
t2.display()
t3.display()
Clearly for now, I'm just trying to print the information within each ticket object, but also not sure if I should be using init to define those variables or not...?
All my variables seem to be string data types however I keep getting the above error message
elif menu == 'a':
pass
user_1 = input("Please enter a user name: ")
task_title = input("Please enter a title for the task to be done: ")
task_desc = input("Please describe the task: ")
task_due = input("Please enter due date of the task: ")
date_assign = str(date.today())
with open("task.txt", "a") as fa:
fa.write("\n" + {} + {} + {} + {} + {} + "No".format(task_title,task_desc,task_due,str(date_assign)))
Your brackets need to actually be within the string itself in order to use the str.format() function. So your code line:
fa.write("\n" + {} + {} + {} + {} + {} + "No".format(task_title,task_desc,task_due,str(date_assign)))
should look more like this:
fa.write("\n{} {} {} {} No".format(task_title,task_desc,task_due,str(date_assign)))
To add on to Nathan Robert's answer, consider using f-strings like so:
with open("task.txt", "a") as fa:
fa.write(f"\n{task_title} {task_desc} {task_due} {date_assign} No")
I find them to be much cleaner then '+' string concatenation.
You cannot create a format string with:
"\n" + {} + {} + {} + {} + {} + "No"
You could:
"\n" + repr({}) + repr({}) + repr({}) + repr({}) + repr({}) + "No"
Which will yield:
"\n{}{}{}{}{}No"
But if you want:
"\n + {} + {} + {} + {} + {} + No"
Then you just need to eliminate two "s.
"\n + {} + {} + {} + {} + {} + No"
Also note that you've provided 5 sets of brackets, but only four arguments to format. This suggests a possible error on your part.
Hi Need clarification for python variable stored as wrong value , here is code :
userinput1 = int(input('enter start value\n'))
userinput2 = int(input('enter stop value\n'))
userinput3 = int(input('enter rampup time in seconds\n'))
userinput4 = float(input('enter increments delta \n'))
userinput5 = input('Enter sequence channels: A A A A or D D D D - A Ascend, D Descent , E Exclude \n')
command1 = "RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3
port.write(command1.encode())
#### ERROR #####
command1 = str("RAMP " + str(userinput5) + " " + userinput1 + " " + userinput2 + " " + userinput4 + " " + userinput3)
TypeError: can only concatenate str (not "int") to str
Can you please clarify me correct method to store both type variable input in single variable command. type caste was done already.
You can concate only strings, so before concate all your userinputs you must "convert" them into strings
Example1:
command1 = "RAMP " + " ".join(map(str, [userinput5, userinput1, userinput2, userinput4, userinput3]))
Example2:
command1 = f"RAMP {userinput5} {userinput1} {userinput2} {userinput4} {userinput3}"
I have a module with a Class
class Record(object):
Name = ''
Gender = ''
Age = ''
Line = 'Bob=Male=40'
M = Line.split('=')
exec(M[0] + ' = ' + 'Record()')
exec(M[0] + '.' + 'Name' + ' = ' + "'" + M[0] + "'")
exec(M[0] + '.' + 'Gender' + ' = ' + "'" + M[1] + "'")
exec(M[0] + '.' + 'Age' + ' = ' + "'" + M[2] + "'")
I am trying to import the above module but to pass it the "Line" variable.
How could I do that ?
Adding this one line should do the job
# in main script
from lib import file_name
file_name.Line = Line #Assuming line is declared already
you need not declare Line in your module
You create objects by calling a class. You don't need to use exec to do that
#record.py
class Record:
def __init__(self, name, gender, age):
self.Name = name
self.Gender = gender
self.Age = age
def __str__(self):
return ' '.join((self.Name, self.Gender, self.Age))
Person = Record("Bob", "Male", "30")
# workspace.py
import record
print(record.Person)
Person2 = record.Record("Alice", "F", "30")
print(Person2)
Outputs:
Bob M 30
Alice F 30
In python you probably would get away with this
name = "Bob"
gend = "M"
age = '30'
exec(f'{name} = record.Record("{name}", "{gend}", "{age}")')
print(Bob)
# Bob M 30
But I would not advise that