I am trying to test user input, but it only seems to work the first time through. If I give the correct data the first time, it works, but if I originally give the wrong data and then use the correct data after being re-prompted it never recognizes it as correct. Any idea why it works the first time but not any time after that? Here is the code,
testDate = open("Sales.txt")
def DateTest(Date, Position):
firstTry = True
validSyntax = False
Done = False
while Done == False:
while validSyntax == False:
if firstTry == True:
print "debug 2"
try:
Date = Date.strip().split(',')
Year = int(Date[0])
Month = int(Date[1])
Day = int(Date[2])
Date = (Year, Month, Day)
except:
print "That is invalid input."
firstTry = False
else:
validSyntax = True
print "ok got it"
elif firstTry == False:
NewDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',')
Year = int(NewDate[0])
Month = int(NewDate[1])
Day = int(NewDate[2])
NewDate = (Year, Month, Day)
except:
print "That is invalid input."
else:
validSyntax = True
print" ok got it"
if validSyntax == True:
for line in testDate:
line = line.strip().split(',')
yearTest = int(line[0])
monthTest = int(line[1])
dayTest = int(line[2])
dateTest = (yearTest, monthTest, dayTest)
if Year == yearTest:
if Month == monthTest:
if Day == dayTest:
Done = True
print "success"
To address why it isnt working currently: you never set startDate, and so the attempt to strip().split() will not work:
NewDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',') // startDate isnt set
you can try
startDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',')
I agree with the commenters that you could take a stab at refactoring your code to consolidate repetitive sections.
Here is a refactored version:
import time
DATE_FORMAT = '%Y,%m,%d'
def parse_date(date_str, fmt=DATE_FORMAT):
try:
return time.strptime(date_str.strip(), fmt)
except ValueError:
return None
def get_date(adj='', fmt=DATE_FORMAT, prompt='Please enter the {}date (like {}): '):
prompt = time.strftime(prompt.format(adj.strip()+' ' if adj.strip() else '', fmt))
# repeat until a valid date is entered
while True:
inp = raw_input(prompt)
res = parse_date(inp, fmt)
if res is None:
print('Invalid input')
else:
return res
def get_test_date(date, adj='', fmt=DATE_FORMAT):
return parse_date(date, fmt) or get_date(adj, fmt)
def find_date_in_file(fname, date_str='', adj=''):
test_date = get_test_date(date_str, adj)
with open(fname) as inf:
for line in inf:
if test_date == parse_date(line):
print('Found!')
return test_date
def main():
find_date_in_file('Sales.txt', '2012,01,05', 'closing')
if __name__=="__main__":
main()
Related
I am getting the Attribute error:
'float' object has no attribute 'replace'
In my program i am reading 3 different files. When i run the code it works perfectly, but only for one of the files. I have no clue why the other 2 files give me this error. I was excpecting to get the amount of days in a given month from a .csv file. i am writing the code in python. If you need any aditional information please ask :)
Code below:
import pandas as pd
def getAMSdata(fileName):
startTid = []
sluttTid = []
forbruk = []
dataframe= pd.read_csv(fileName, sep=";")
startTid = dataframe["Fra"].tolist()
sluttTid = dataframe["Til"].tolist()
forbruk = dataframe["KWH 60 Forbruk"].tolist()
return startTid,sluttTid,forbruk #returnerer lister
dataLists = getAMSdata("data/meteringvalues-mp-xxxxx-consumption-202101.csv")
for i in range(len(dataLists[2])):
dataLists[2][i] = float(dataLists[2][i].replace(',','.'))
def getDayCount(timeStampList):
dayCount= len(timeStampList) // 24
return dayCount
def getMonth(dateAndTimeStr):
months = ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"]
monthStr = int(dateAndTimeStr[3:5])
month = months[monthStr - 1]
return month
def getDays(timeStampList):
#-------------------------------------
dayList = []
for i in range(0, len(timeStampList)):
dayList.append(int(timeStampList[i][0:2]))
#-------------------------------------
return dayList
def getHours(timeStampList):
#-------------------------------------
hourList = []
for i in range(len(timeStampList)):
hourList.append(int(timeStampList[i][11:13]))
#-------------------------------------
return hourList
import os
files = os.listdir('data')
def selectDataFile(fileIndex):
return files[fileIndex]
selectDataFile(0)
def printMainMenu():
print('\n')
print('------ MAIN MENU ------')
print('\n')
print('1) Show all the data files available.')
print('2) Select the year and month to study.')
print('3) Go to graph and statistics menu.')
print('4) Quit.')
return
def printMonth():
print('1 : January')
print('2 : February')
print('3 : March')
print('4 : April')
print('5 : May')
print('6 : June')
print('7 : July')
print('8 : August')
print('9 : September')
print('10 : October')
print('11 : November')
print('12 : December')
def processMainMenu(x, currentfile):
print('\n')
if x=='1' :
print("Files availables : ")
for i in range(len(files)):
print(files[i])
return True, currentfile
elif x=='2':
year = input('\nSelect the year : ')
if year != '2020' and year != '2021':
print('There is no data for ', year)
return True, currentfile
printMonth()
month = input('\nSelect the month : ')
if year == '2021' and month == '1':
currentfile = selectDataFile(1)
return True, currentfile
elif year =='2020' and month == '11':
currentfile= selectDataFile(0)
return True, currentfile
elif year =='2020' and month == '12':
currentfile = selectDataFile(2)
return True, currentfile
else :
print('There is no data for the selected year and month.')
return True, currentfile
elif x=='3':
if currentfile == '':
print('Select a file before going to the graph and stats menu.')
return True, currentfile
printGraphStatMenu()
y = input('Chose an option by entering its index number : ')
keepGoing = processGraphStatMenu(y, currentfile)
return keepGoing, currentfile
elif x=='4':
return False, currentfile
else:
print('Please enter a proper index number.')
return True,currentfile
def printGraphStatMenu():
print('\n')
print(' ------ GRAPH AND STATISTICS MENU ------')
print('\n')
print(' STATISTICS : ')
print(' 1) Show the number of days in the month.')
print(' 2) Show the average consumption in the month.')
print(' 3) Show the average hourly consumption per day.')
print(' 4) Chose an hour of the day and show its consumption.')
print(' 5) Show highest consumption and the hour it is reached.')
print(' 6) Show the average power peak in the month.')
print(' 7) Show standard deviation for the hourly consumption.')
print(' GRAPHS : ')
print(' 8) Graph the daily consumption.')
print(' 9) Graph an average day.')
print(' 10) Quit.')
def processGraphStatMenu(y, currentfile):
data = getAMSdata(str('data/' + currentfile))
for i in range(len(data[2])):
data[2][i] = float(data[2][i].replace(',','.'))
if y == '1':
print('\n THERE ARE ', getDayCount(data[0]),' DAYS IN THE MONTH.')
return True
elif y== '2':
print('\n THE AVERAGE CONSUMPTION IN THE MONTH IS :', getAverage(data[2]), 'KWH.')
return True
elif y=='3':
avgDay = pd.DataFrame(getAvgDay(data[2], getHours(data[0])))
print('\n THE AVERAGE HOURLY CONSUMPTION PER DAY IS :', avgDay , 'KWH.')
return True
elif y=='4':
hour = int(input(' Select an hour by entering an integer between 0 and 23 :'))
if hour < 0 or hour > 23 :
print('\n Please enter an hour between 0 and 23.')
return True
hours = getHours(data[0])
sameHourCons = []
for i in range(len(hours)):
if hours[i] == hour :
sameHourCons.append(data[2][i])
index = range(1, len(sameHourCons) + 1)
sameHourConsDF = pd.DataFrame(sameHourCons, index = index)
print('\n HERE IS THE CONSUMPTION AT HOUR ', hour, ' FOR EACH DAY OF THE MONTH : \n', sameHourConsDF)
return True
elif y == '5':
peakCons, peakDate, peakHour = findPeakInterval(data[2], getDays(data[0]), getHours(data[0]))
print('\n THE HIGHEST CONSUMPTION IS : ', peakCons, ' KWH. IT IS REACHED ON DAY ', peakDate, ' AT HOUR ', peakHour,'.')
return True
elif y == '6':
print('\n THE AVERAGE POWER PEAK IN THE MONTH IS : ', getEffectPeak(data[2]), 'KWH')
return True
elif y == '7':
hourlyCons = getDailyConsumption(data[2], getDays(data[0]))
print('\n THE STANDARD DEVIATION FOR THE HOURLY CONSUMPTION IS :', getStdDev(hourlyCons, getAverage(hourlyCons)), 'KWH.')
return True
elif y == '8':
plotDailyConsumption(getDailyConsumption(data[2], getDays(data[0])), getMonth(data[0][0]))
return True
elif y == '9':
plotAvgDay(getAvgDay(data[2], getHours(data[0])), getMonth(data[0][0]))
return True
elif y == '10' :
return False
else:
print('\n Please enter a proper index number.')
return
def main():
keepGoing = True
currentfile = ''
while(keepGoing):
printMainMenu()
x = input('Chose an option by entering its index number : ')
keepGoing, currentfile = processMainMenu(x, currentfile)
print('Bye !')
return
main()
I skipped some parts that I assumed were unimportant for my error
fyi this is my first major code and my first stack overflow question
I assume you're coding in Python.
In Python, you cannot write .replace('x', 'y') for floats, but you can for strings. Different types have different properties.
A very basic way of replacing floats with another number is as follows:
a = 5.5
if a == 5.5:
a = 9.3
There are many ways to change a float, but which one to use depends on your specific problem.
First of all I would just like to mention - I am a beginner, I am still learning. This code is probably an abomination and I might be missing something obvious, please be nice.
My question is this. I have written a for loop to find the highest earning employee but I would like for the user to select a start and end date for their earnings to be calculated.
So for example my program should be able to calculate an employees earning from 01/05/2021 to 09/05/2021.
The only thing I'm struggling with is how to reference the date, I've been googling for an hour but the responses are just too complicated for me.
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime as dt
df = pd.read_csv('Task_4a_data.csv', index_col='ID')
#main menu
def menu():
print("\t\t****MAIN MENU****")
print('1) Enter sales records')
print('2) Run reports')
x = int(input(""))
return x
#reports menu
def menu2():
print("**** Reports Dashboard ****")
print("1. Individual Employee Report")
print("2. Show employees with the highest sales value")###########
x = int(input(""))
return x
def ind_emp_check(df_r, id, date1, date2):
df_r = df_r.loc[df.index == id]
df_r = df_r.T[3:]
df_r.reset_index(inplace=True)
df_r['ID1'] = pd.to_datetime(df_r['index'], format='%d/%m/%Y')
date1 = pd.to_datetime(date1, format='%d/%m/%Y')
date2 = pd.to_datetime(date2, format='%d/%m/%Y')
mask = (df_r['ID1'] >= date1) & (df_r['ID1'] <= date2)
df_search = df_r.loc[mask]
print(df_search)
print('Total by id = {} is {}'.format(id, sum(df_search[id])))
plt.bar(df_search['index'], df_search[id])
plt.xticks(rotation=90)
plt.show()
y = menu()
while y == 1 or y == 2:
if y == 1:
try:
ID = int(input("Enter the Staff ID "))
if ID not in df.index.values:
print('yes')
date1 = input("Enter Date in dd/mm/yy: ")
day, month, year = date1.split("/")
date1 = datetime.date(int(year), int(month), int(day))
if datetime.datetime.strptime(date1.strftime('%d/%m/%Y'), '%d/%m/%Y') > datetime.datetime.strptime(
dt.today().strftime('%d/%m/%Y'), '%d/%m/%Y'):
print("Date is in the future")
else:
cost = float(input("Enter the cost : "))
df.loc[ID, date1.strftime('%d/%m/%Y')] = cost
# df.to_csv('test2.csv')
except:
print("\n\nError Occurred Please try again\n\n")
y = menu()
if y == 2:
x = menu2()
if x == 1:
try:
id = int(input("Enter the Employee Id : "))
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
day, month, year = s_date.split("/")
s_date = datetime.date(int(year), int(month), int(day))
e_date = input("Enter End Date in dd/mm/yyyy: ")
day, month, year = e_date.split("/")
e_date = datetime.date(int(year), int(month), int(day))
s_date = datetime.datetime.strptime(s_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
e_date = datetime.datetime.strptime(e_date.strftime('%d/%m/%Y'), '%d/%m/%Y')
ind_emp_check(df, id, s_date, e_date)
except:
print("\n\nError Occurred Please try again\n\n")
x = menu2()
elif x == 2:
s_date = input("Enter Starting Date in dd/mm/yyyy: ")
e_date = input("Enter End Date in dd/mm/yyyy: ")
total = 0
totals = []
for r in df.index:
for i in (df.loc[r]):
if PLACEHOLDER == e_date:
break
try:
total+=i
total = int(total)
except:
pass
totals.append(total)
total=0
largest_number = totals[0]
for number in totals:
if number > largest_number:
largest_number = number
print(largest_number)
else:
x = menu2()
else:
x = menu()
x = menu()```
I am pretty new to programming and I have made an app which works fine but I get warnings saying "Name "X" can be undefined". What does this mean and how could I get rid of the warning? I am using Python 3.8 with Intelij IDE 2020.1.
Here is a screenshot of my issue:
Here is a minimum repo of my code:
print("1. school a \n2. school b")
while True:
try:
school_number = int(input("\nEnter the number of what school you are at: "))
break
except ValueError:
print("That was an invalid number. Please try again...\n")
current_day = input("Please enter what day it is (mon/tue etc): ".lower())
if school_number == 1:
school_name = "school A"
cost = (7.50 * 2)
leave_time_multiplier = 1.15
if current_day == "mon":
start_time = 09.30
finish_time = 14.30
else:
pass
if school_number == 2:
school_name = "school B"
cost = (9.50 * 2)
leave_time_multiplier = 1.25
if current_day == "mon":
start_time = 17.00
finish_time = 20.30
else:
pass
# renames the days
if current_day == "mon":
day = "Monday"
else:
day = "Other"
leave_time = start_time - leave_time_multiplier - 1
print("\nOn {} at {}: It will cost {:.2f} return. You start at {:.2f} and finish at {:.2f} You should leave at"
"{:.2f}".format(day, school_name, cost, start_time, finish_time, leave_time))
finish_time will be undefined in case of: school_number not equal to 1 or 2, current_day is not equal to "mon", etc. In such cases, your script will raise an exception. So you have to define finish_time somewhere above line with if school_number == 1:
You must add a third condition where the value does not equal 1 and 2 numbers. Because if the user was input another number than 1 or 2, all variables that you print will not be created.
IDnum = input("\nprompt: ")
if int(IDnum) >= 0 :
if int(IDnum) in T.keys() :
print("ID number(s) that {} will contact is(are) {}.".format(int(IDnum),T[int(IDnum)]))
else :
print("Entered ID number {} does not exist.".format(int(IDnum)))
else:
break
It's actually a while loop, receiving ID numbers and checking whether the numbers are in the file.
I'd like to make it discern whether the input is an integer >= 0 and if it's anything else, (eg. space,enter,characters,float,etc) break the loop.
How can I do this using if statements?
I have tried
if IDnum == '' or IDnum == ' ' or int(IDnum) < 0 :
but as you know, it cannot cover all the other cases.
T = {1: 1, 2: 2}
while True:
IDnum = input("\nprompt: ")
try:
num = int(IDnum)
if num < 0:
raise ValueError('Negative Integers not allowed')
except ValueError: # parsing a non-integer will result in exception
print("{} is not a valid positive integer.".format(IDnum))
break
if num in T:
print("ID number(s) that {} will contact is(are) {}.".format(num,T[num]))
else:
print("Entered ID number {} does not exist.".format(num))
Thanks to #adirio and #moses-koledoye for the suggested improvements.
Do the check with a try-except statement.
def is_pos_int(IDnum):
''' Check if string contains non-negative integer '''
try:
number = int(IDnum)
except ValueError:
return False
if number >= 0:
return True
else:
return False
For example
is_pos_int('1 ') # notice the space
Out[12]: True
is_pos_int('-1')
Out[13]: False
is_pos_int('1.0')
Out[15]: False
is_pos_int('word')
Out[16]: False
Then:
while True:
if not is_pos_int(IDnum):
break
else:
val = int(IDnum)
if val in T.keys() :
print("ID number(s) that {} will contact is(are) {}.".format(val, T[val]))
else :
print("Entered ID number {} does not exist.".format(val))
I'm trying to write an object-oriented program that allows me to enter and store monthly income and bills, and view all data as needed. I can successfully store an object, but when I try to use my view_all function, I get this error:
in view_all print(item.get_month())
AttributeError: 'str' object has no attribute 'get_month'
If you could help me track down this problem I'd be grateful!
# Create a month class
class Month:
# Use __init__ method to initialize the attributes
def __init__(self, month, income, tds, pnm, zia, water):
self.__month = month
self.__income = income
self.__tds = tds
self.__pnm = pnm
self.__zia = zia
self.__water = water
# The set methods accept arguments:
def set_month(self, month):
self.__month = month
def set_income(self, income):
self.__income = income
def set_tds(self, tds):
self.__tds = tds
def set_pnm(self, pnm):
self.__pnm = pnm
def set_zia(self, zia):
self.__zia = zia
def set_water(self, water):
self.__water = water
# The get methods return the data:
def get_month(self):
return self.__month
def get_income(self):
return self.__income
def get_tds(self):
return self.__tds
def get_pnm(self):
return self.__pnm
def get_zia(self):
return self.__zia
def get_water(self):
return self.__water
# The __str__ method return's the object's state as a string
def __str__(self):
return "Month: " + self.__month + \
"\nIncome: " + self.__income + \
"\nTDS: " + self.__tds + \
"\nPNM: " + self.__PNM + \
"\nZia: " + self.__zia + \
"\nWater: " + self.__water
And the main program:
import Month_Class
import pickle
ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3
FILENAME = 'ruidoso.dat'
def main():
months = load_months()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == ADD_MONTH:
add_month(months)
elif choice == VIEW_ALL:
view_all(months)
save_months(months)
def load_months():
try:
input_file = open(FILENAME, 'rb')
months_dct = pickle.load(input_file)
input_file.close
except IOError:
month_dct = {}
return month_dct
def get_menu_choice():
print()
print('Menu')
print('------------------')
print("1. Add data for a new month")
print("2. View data for all months")
print('Any other number saves and quits the program!')
print()
choice = int(input('Enter your choice: '))
while choice < ADD_MONTH or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def add_month(months):
month = input('Enter the name of the month: ')
income = input('Total income for this month: ')
tds = input('TDS Broadband bill total: ')
pnm = input('PNM bill total: ')
zia = input('Zia Natural Gas bill total: ')
water = input('City of Ruidoso bill total: ')
entry = Month_Class.Month(month, income, tds, pnm, zia, water)
if month not in months:
months[month] = entry
print('The entry has been added')
else:
print('That month already exists!')
def save_months(months):
output_file = open(FILENAME, 'wb')
pickle.dump(months, output_file)
output_file.close()
def view_all(months):
for item in months:
print(item.get_month())
print(item.get_income())
print(item.get_tds())
print(item.get_pnm())
print(item.get_zia())
print(item.get_water())
main()
You need to iterate over the dictionary differently
for month, item in months.items():
print(item.get_month())
...
In the view_all method, you must to iterate over dictionary:
for key, item in months.iteritems():
print(item.get_month())
and you got other error in __str__ method of Month class:
"\nPNM: " + self.__PNM + \
the correct is:
"\nPNM: " + self.__pnm + \