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.
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.
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
I am trying to create a program so that I can input all the shifts I work in a week, and it will calculate the total number of hours I work, and how much I money I will make.
I have created a dictionary called week_schedule and an input prompt to ask the user what day of the week they are going to log. The program then asks the shift start and finish, creating variables for both of them, and storing it all in a dictionary.
How can I rerun this loop, so that I can input more than one day, and store it all in a dictionary that I can then print out later? Currently rerunning the loop just adds more information to the same strings.
week_schedule = {}
day = input("Day of the week: ")
day_promp = True
while day_promp:
dayStart = input("Shift Start: ")
dayEnd = input("Shift End: ")
dayHours = (float(dayEnd) - float(dayStart)) / 100
dayPay = (float(dayHours) * 15.75)
week_schedule[day] = format(dayHours) + " hours", "$ " + format(dayPay)
repeat = input("\nMore days?: ")
if repeat == 'no':
day_promp = False
print("\n--- Week summary ---")
for day, dayHours in week_schedule.items():
print(format(day) + ": " + format(dayHours))
print("Total earned: $" + format(dayPay))
Currently I can run the program and it works for only one day.
For example if I imputed 'Tuesday" for the day, "1200" for the shift start, and "1800" for the shift end, it would output the following:
--- Week summary ---
Tuesday: ('6.0 hours', '$ 94.5')
Total earned: $94.5
--------------------
I would like to be able to print out all the days I input in the dictionary as well.
Move your day = input("Day of the week: ") inside the loop, so it will be
week_schedule = {}
grand_total = 0
day_promp = True
while day_promp:
# Do it each iteration
day = input("Day of the week: ")
dayStart = input("Shift Start: ")
dayEnd = input("Shift End: ")
dayHours = (float(dayEnd) - float(dayStart)) / 100
dayPay = (float(dayHours) * 15.75)
# sum up all the totals
total += dayPay
week_schedule[day] = format(dayHours) + " hours", "$ " + format(dayPay)
repeat = input("\nMore days?: ")
if repeat == 'no':
day_promp = False
print("\n--- Week summary ---")
# Now your dict has a key per day, so all values are printed.
for day, dayHours in week_schedule.items():
print(format(day) + ": {} ".format(dayHours))
print("Total earned: $ {0:.2f}".format(dayPay))
print("Grand Total earned $ {0:.2f}".format(total))
Your original code assigns day = input("Day of the week: ") only once, that's why
you're always getting only one value.
As mentioned in the comments above, the easiest way to make a program like this would be to have it write to a file in a given format. For example:
WagePerHour = 9.50
Mode = input("Would you like to log another day, clear the log, or see the current total? ")
if Mode == "log":
EnterMore = True
while EnterMore == True:
Day = input("What day of the week are you logging? ")
Hours = input("How many hours did you work? ")
Days = { "Sunday" : "1", "Monday" : "2", "Tuesday" : "3", "Wednesday" : "4", "Thursday" : "5", "Friday" : "6", "Saturday" : "7"}
File = open("File", "a")
DayAsNumber = Days[Day]
File.write(DayAsNumber + " " + Hours)
File.write("\r\n")
File.close()
continuevar = input("Would you like to log another day? (Y/N) ")
if continuevar != "Y":
EnterMore = False
if Mode == "total":
File = open("File", "r")
TotalHours = 0
for line in File.readlines():
if line[2:] != "":
TotalHours += int(line[2:])
TotalHoursString = str(TotalHours)
print("So far this week, you have logged " + TotalHoursString + " hours.")
File.close()
TotalHoursAsInt = int(TotalHoursString)
TotalWages = (TotalHoursAsInt * WagePerHour)
TotalWagesString = str(TotalWages)
print("Your wages before taxes are " + TotalWagesString)
else:
print("You have not logged any hours this week.")
if Mode == "clear":
File = open("File", "w")
File.write("")
File.close()
I was trying to make it so that my program will keep asking the user to input a certain value and if the user doesn't it keeps asking until they do.
I tried to use "while" instead of "if" but I know I'm probably missing something, somewhere.
def terrain(surface):
surface = raw_input("What surface will you be driving on? ")
if surface == "ice":
u = raw_input("what is the velocity of the car in meters per second? ")
u = int(u)
if u < 0:
u = raw_input("Velocity must be greater than 0")
return
if u == 0:
u = raw_input("Velocty must be a number greater than zero")
return
a = raw_input("How quickly is the vehicle decelerating? ")
a = int(a)
if a > 0:
print ("Deceleration cannot be a positive integer")
return
else:
s1 = u**2
s2 = 2*.08*9.8
s = s1/s2
print "This is how far the vehicle will travel on ice: "
print ("The vehicle will travel %i meters before coming to a complete stop" % (s))
terrain("ice")
The problem is you are using return after checking the condition which causes the function to return None you have to use break instead of return with while loop instead of if to achieve this. A better way to validate and get data is below
class ValidationError(Exception):
pass
def validate_and_get_data_count(x):
if int(x) < 0:
raise ValidationError("Cannot be less than 0")
return int(x)
def validate_and_get_data_name(x):
if len(x) < 8:
raise ValidationError("Length of name cannot be less than 8 chars")
elif len(x) > 10:
raise ValidationError("Length of name cannot be greater than 10 chars")
return x
validators = {
"count": validate_and_get_data_count,
"name": validate_and_get_data_name
}
data = {}
params = [
("count","Please enter a count: "),
("name","Please enter a name: "),
]
for param in params:
while True:
x = input(param[1])
try:
data[param[0]] = validators[param[0]](x)
break
except ValidationError as e:
print(e)
print(data)
What the above code does is for every param in params list it runs a while loop checking for every validation condition defined in its validator if valid it breaks the while loop and proceeds to next param and repeats the same process again
run = 1
list1 = []
for i in range(2):
while run > 0 :
print("-------------------------------------------------------")
run = 1
reg_num = input("Registration Number in caps: ")
tsh = int(input("Hour Entered : "))
tsm = int(input("Minute Entered : "))
tss = int(input("Second Entered : "))
print("")
teh = int(input("Hour Exited : "))
tem = int(input("Minute Exited : "))
tes = int(input("Second Exited : "))
print("Time Entered (camera1)", tsh, ":", tsm, ":", tss, "and Time Exited (camera2)", teh, ":", tem, ":", tes)
if tsh < teh:
tm = (((teh - tsh)*60) + (tem - tsm) +((tes - tss)/60))/60
elif tsh > teh:
teh = 24 + teh
tm = (((teh - tsh)*60) + (tem - tsm) +((tes - tss)/60))/60
speed = run/tm
print("speed of", reg_num, "is", "{:.2f}".format(speed), "mph")
if speed > 70:
list1.append(reg_num)
break
print("Overspeeding vehicles are: ")
for item in list1:
print (item)
this is the code to calculate the speed of a vehicle that passes through a speed camera set 1 mile apart. i have to out put a list of vehicles that are exceeding the speed limit. the problem is when the code calculates the speed (speed = run/time) the error massage states that "tm"(totalminutes) is not defined. can you make some corrections and tell me what is wrong.
The problem is none of your conditions in the 'if' statement are met.
if tsh = teh:
tm = bla
elif tsh < teh:
tm = bla * 2
else:
tm = bla / 2 # Add the 'else' part to do something when all else fails.