AttributeError 'float' object has no attribute 'replace' - python

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.

Related

Return multiple values in a function

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]

How can I repeat my loop and add more information to my dictionary, and use different strings?

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()

Blackjack str iteration error

I am converting an array into a string to print, but the compiler still says not iterable.
Traceback (most recent call last):
File "python", line 157, in <module>
File "python", line 56, in total
TypeError: 'int' object is not iterable
The function total() is located on line 56, if you think it is the problem, but if you run the script, you should find that the function works properly every other instance.
import random
import time
def makeDeck():
cards = []
num = 1
for card in range(52):
cards.append(num)
num += 1
if num == 13:
num = 1
return cards
#def shuffle(cards):
#for card in cards:
#num = random.randint(0,51)
#cards.insert(0, cards[num])
#return cards
def shuffle(deck):
for card in deck:
hold = deck.pop(0)
deck.insert(random.randint(1,51),hold)
return deck
def cardToString(hand):
cardString = []
for card in hand:
if card == 1:
cardString.append('Ace')
elif card == 11:
cardString.append('Jack')
elif card == 12:
cardString.append('Queen')
elif card == 13:
cardString.append('King')
else:
cardString.append(str(card))
for card in cardString:
return card
def deal(user,deck):
hand = []
for x in range(2):
hand.append(deck.pop(0))
return hand
def deal1(user,deck):
hand = []
for card in deck:
hand.append(deck.pop(0))
return hand
def total(hand):
score = 0
for card in hand:
if(card>10):
score += 10
elif(card != 1):
score += card
else:
if(score>=11):
score+=1
else:
score+=11
return score
#def playGame():
#to do
name1 = input('Player 1, please enter your name:\n')
p2q = input('Will there be two plaers? (y/n)')
if(p2q == 'y' or p2q == 'Y' ):
p2yn = 1
name2 = input('Player 2, please enter your name:\n')
elif(p2q == 'n' or p2q == 'N'):
p2yn = 0
deck = makeDeck()
shuffle(deck)
p1hand = deal(name1,deck)
if(p2yn == 1):
p2hand = deal(name2,deck)
else:
print(end = ' ')
hs=0
print(str(name1)+', your hand is:', end = ' ' )
cardToString(p1hand)
print(str(p1hand[0])+',',p1hand[1], end = ' ')
print('and your total is', total(p1hand))
time.sleep(2)
tot1 = total(p1hand)
while(tot1 < 21):
p1cvar = input('Would you like another card? (y/n)\n')
if(p1cvar =='n' or p1cvar == 'N'):
break
else:
p1hand.append(deck.pop(0))
newCard = str(p1hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p1hand))
time.sleep(1)
if(total(p1hand) <= 21):
hs = total(p1hand)
else:
print('You went over 21!')
p1hand=0
time.sleep(1)
break
if(p1hand != 0):
print('The high score is', total(p1hand), 'held by', str(name1)+'.')
time.sleep(1)
shuffle(deck)
if(p2yn == 1):
print(str(name2)+', your hand is:', end = ' ' )
cardToString(p2hand)
print(str(p2hand[0])+',',p2hand[1], end = ' ')
print('and your total is', total(p2hand))
time.sleep(2)
tot1 = total(p2hand)
while(tot1 < 21):
p2cvar = input('Would you like another card? (y/n)\n')
if(p2cvar =='n' or p2cvar == 'N'):
break
else:
p2hand.append(deck.pop(0))
newCard = str(p2hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p2hand))
time.sleep(1)
if(total(p2hand)>21):
print('You went over 21!')
p2hand=0
time.sleep(1)
break
if(p2hand != 0 and total(p2hand)>hs):
print('The high score is', total(p2hand), 'held by', str(name2)+'.')
hs = total(p2hand)
time.sleep(1)
dealerHand = deal('Dealer',deck)
print("The dealer's hand is:", end = ' ' )
cardToString(dealerHand)
print(str(dealerHand[0])+',',dealerHand[1], end = ' ')
print('and their total is', total(dealerHand))
time.sleep(2)
totD = total(dealerHand)
while(totD < 21):
tdh = total(dealerHand)
if(tdh<hs and tdh<22):
dealerHand.append(deck.pop(0))
newCard = str(dealerHand[-1])
cardToString(newCard)
print('Dealer got a', newCard)
time.sleep(.5)
print("Dealer's total is now", total(dealerHand))
time.sleep(1)
if(total(dealerHand) <= 21 and total(dealerHand)>hs):
hs = total(dealerHand)
else:
print('Dealer went over 21!')
dealerHand=0
else:
break
if(dealerHand != 0):
print('The high score is', total(dealerHand), 'held by', str("Dealer")+'.')
while(total(p1hand)>21 or total(dealerHand)>21):
if(total(dealerHand)>21):
print('Dealer has been eliminated from play!')
elif(total(p1hand)>21):
print(name1,'has been eliminated from play!')
About 11 lines up from the bottom of your code block, you are setting the dealers hand to 0:
....
else:
print('Dealer went over 21!')
dealerHand=0
This is concerning since their hand should be a list. Thus when you try to iterate over it to count the total, you get that an int isn't iteratable.
Should probably be something like
dealerHand = []
Also, a few lines after that, you are asking if dealerHand!=0, when I think you mean total(dealerHand)
You should also be careful with your other assignments that change a variable from a list to an int such as
#Around line 111
print('You went over 21!')
p1hand=0
time.sleep(1)
break
.....
#Around line 140
print('You went over 21!')
p2hand=0
time.sleep(1)
break
Because Python is not strongly type, changing the type of a given variable name can lead to a lot of these kinds of problems
#Stephen gave you the direct answer. I suggest using pylint3 (or some other linter) on your code. It would have told you the problem
R:170, 6: Redefinition of dealerHand type from list to int
(redefined-variable-type)
This will help you in the future.

Python input statement

I have created a battleship like game, and have it all completed except for one detail.
I have the following input statement:
x, y = input("Enter two numbers here: ").split()
with the 2 numbers being entered corresponding to the players chosen coordinates. I also need to be able to handle the entry of 'q' or 'h' for the quit or help options. However, since i am taking two variables from this statement when only a q or h is entered i get the error that the statement needs 2 elements to unpack, which makes sense. Any pointers on how to get around this?
import random, math
class oceanTreasure:
def __init__(self):
self.board = self.board()
self.found = 0
self.left = 3
self.sonarsLeft = 20
self.chests= []
self.chest()
def board(self):
board = []
for x in range(16): # the main list is a list of 60 lists
board.append([])
for y in range(61): # each list in the main list has 15 single-character strings.
board[x].append('~')
return board
def chest(self):
chest1 = [random.randint(0,60), random.randint(0,15)]
chest2 = [random.randint(0,60), random.randint(0,15)]
chest3 = [random.randint(0,60), random.randint(0,15)]
self.chests = [chest1, chest2, chest3]
def getChestsLeft(self):
return self.found
def getChests(self):
return self.chests
def getTreasuresLeft(self):
return self.left
def getSonarsLeft(self):
return self.sonarsLeft
def dropSonar(self,x,y):
ySonar = ['a','b','c','d','e','f','g']
whichAxis, axis = self.checkDistance(x,y)
if whichAxis == True:
sonar = axis
if whichAxis == 'xaxis':
sonar = axis
elif whichAxis == 'yaxis':
sonar = ySonar[axis-1]
elif whichAxis == None:
sonar = axis
self.board[int(y)][int(x)] = sonar
self.sonarsLeft -=1
return axis
def checkDistance(self,x,y):
closest = self.chests[0]
distance = 100
for chest in self.chests:
temp = math.sqrt(math.pow((chest[0]-int(x)),2) + math.pow((chest[1]-int(y)),2))
if temp < distance:
closest = chest
distance = temp
xaxis =math.fabs((closest[0] - int(x)))
yaxis = math.fabs((closest[1]-int(y)))
if yaxis == 0 and xaxis == 0:
self.chests.remove(closest)
self.found +=1
self.left -=1
return True, 'X'
elif xaxis <= 9 and yaxis <=5 :
if yaxis == 0 :
return 'xaxis',int(math.fabs(xaxis))
if xaxis == 0 :
return 'yaxis',int(math.fabs(yaxis))
if min(xaxis//2,yaxis) ==(xaxis//2) :
return 'xaxis', int(math.fabs(xaxis))
elif min(xaxis//2,yaxis) == (yaxis) or xaxis == 0 :
return 'yaxis', int(math.fabs(yaxis))
else: return None,0
def drawBoard(self):
firstLine = ' '
for i in range(1,7):
firstLine += (' '*9) + str(i)
print(firstLine)
secondLine = ' '
secondLine += ('0123456789' *6)
print(secondLine)
print()
i = 0
for i in range(0,16):
boardRow = ''
for x in range(0,61):
boardRow += str(self.board[i][x])
if i < 10:
print(str(i) +' ' + str(boardRow) + str(i))
if i >= 10:
print(str(i) +' ' + str(boardRow) + str(i))
print()
print(secondLine)
print(firstLine)
device = 'devices'
if self.sonarsLeft ==1:
device = 'device'
print('You have %s sonar %s availabe. You have found %s treasures and have %s left' %(self.sonarsLeft, device, self.found, self.left))
ocean = oceanTreasure()
ocean.drawBoard()
gameOver = False
instructionsList = ['This is a treasure hunting game.' , 'You begin the game with 20 sonar devices available (each device has a range of 9 units in the x axis and 5 in the y axis).','When you place a device, if an "O" is displayed that means there are no chests in range.', 'If a number from 1-9 is displayed, the closest chest is within n units away on the X axis.', 'If a letter from a-e is displayed, the closest chest is n units away on the Y axis (a =1, b =2 and so on...).', 'The game ends when you run out of sonar devices, all the treasure is found or you enter "q" to quit.', 'Thanks for playing and happy hunting!']
while ocean.getTreasuresLeft() != 0 and ocean.getSonarsLeft() >0 and gameOver == False:
response = False
coordinate = False
while response == False:
inputString = input("Enter two numbers seperated by a space (X Y): ")
if inputString == 'q':
gameOver = True
response = True
elif inputString == 'h':
for instruction in instructionsList:
print(instruction)
response = True
else:
try:
x,y = inputString.split()
assert int(x) <=60 and int(y) <=15
response = True
coordinate = True
except AssertionError:
print('Please enter a valid move')
if gameOver == True:
break
#whichAxis, axis =ocean.checkDistance(x,y)
#print(axis)
if coordinate == True:
axis = ocean.dropSonar(x,y)
ocean.drawBoard()
if axis == 'X':
print('Congratulations, you have found a treasure!')
if ocean.getTreasuresLeft() == 0:
print('Congratulations, you found all the treasure')
elif ocean.getSonarsLeft() == 0:
print('Sorry, you ran out of sonar devices, the remaining chests were: %s ' % str(ocean.getChests()))
How about separating the tests to be a little clearer:
input_string = input("Enter two numbers here: ")
if input_string == 'q':
do_quit()
elif input_string == 'h':
do_help()
else:
x,y = input_string.split()
That way you can test for your special cases, and process the x and y if they are not found.
may be this, for example:
a = input("text")
b = a.split()
if len(b) == 1:
if b[0] == 'q':
return
elif b[0] == 'h':
print 'it is help ... '
elif len(b) == 2:
# process for two inputted numbers
You can just separate the input:
# get the input
ipt = input("Enter two numbers here: ")
# check if your option is entered
if ipt == 'q' or ipt == 'h':
# do something
else:
x,y = ipt.split()

Division by zero error when adding rogue value without any data

Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()

Categories