Python - TypeError: 'NoneType' object is not iterable - typeerror

I am attempting to prevent the input of anything other than an integer for an average, but I keep receiving a Traceback for a TypeError. Below is my program, and the program output when attempting to input anything other than an int for an average:
grades_file = open('grades.txt', 'w')
def get_averages():
student = 1
for i in range(3):
name, average = get_name_average()
student += 1
grades_file = open('grades.txt', 'a')
grades_file.write("Student Name: " + name + '\n' + "Student Average: " + str(average) + '\n\n')
grades_file.close()
print(("Added %s's average of %i to the file 'grades.txt. You are now entering information for student %i of 12.") % (name, average, student))
def get_name_average():
student_name = input("Please enter the student's name: ")
try:
student_average = int(input(("Please enter the average for %s: ") % student_name))
verified_average = check_grade_input(student_average)
return student_name, verified_average
except ValueError:
print("ERROR!! Please enter grade value as an integer!")
except TypeError:
print('Type error too!')
def check_grade_input(average):
legal_input = False
while not legal_input:
if (average < 0):
print("Nah bro, invalid number...")
average = int(input("Please enter another average that is above 0: "))
elif (average > 100):
print("Nah bro, invalid number...")
average = int(input("Please enter another average that is below 100: "))
else:
return average
def show_grades_file():
grades_file = open('grades.txt', 'r')
grade_contents = grades_file.read()
grades_file.close()
print("\nThe information you entered for into file 'grades.txt' is:\n\n" + grade_contents)
def main():
get_averages()
show_grades_file()
main()
Traceback and input:
Please enter the student's name: Aaron
Please enter the average for Aaron: as
ERROR!! Please enter grade value as an integer!
Traceback (most recent call last):
File "Documents/ProgrammingFundamentals/Lab6/aaron_blakey_Lab6b.py", line 52, in <module>
main()
File "Documents/ProgrammingFundamentals/Lab6/aaron_blakey_Lab6b.py", line 49, in main
get_averages()
File "Documents/ProgrammingFundamentals/Lab6/aaron_blakey_Lab6b.py", line 13, in get_averages
name, average = get_name_average()
TypeError: 'NoneType' object is not iterable

In function get_name_average you have printed message in Exception part print("ERROR!! Please enter grade value as an integer!") and you did not return any value.
By default system will return none value & required two values name, average.
You need to follow below code.
def get_name_average():
student_name = input("Please enter the student's name: ")
try:
student_average = int(input(("Please enter the average for %s: ") % student_name))
verified_average = check_grade_input(student_average)
return student_name, verified_average
except ValueError:
print("ERROR!! Please enter grade value as an integer!")
return False,False
except TypeError:
print('Type error too!')
return False,False
After that if you got exception then name,average=False,False.
In function get_averages you need add one condition if name is False then system should not write in the file.
This may help you.

Related

how to fix the calculation error which says 'DataFrame' object is not callable

im working on football data set and this is following error im getting. please help,
#what is the win rate of HomeTeam?
n_matches = df.shape[0]
n_features = df.shape[1] -1
n_homewin = len(df(df.FTR == 'H'))
win_rate = (float(n_homewin) / (n_matches)) * 100
print ("Total number of matches,{}".format(n_matches))
print ("Number of features,{}".format(n_features))
print ("Number of maches won by hom team,{}".format (n_homewin))
print ("win rate of home team,{:.2f}%" .format(win_rate))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-122-7e4d81fc684e> in <module>
5 n_features = df.shape[1] -1
6
----> 7 n_homewin = len(df(df.FTR == 'H'))
8
9 win_rate = (float(n_homewin) / (n_matches)) * 100
TypeError: 'DataFrame' object is not
expected result should print the team winning ratio
I think problem is with (), need [] for filter by boolean indexing:
n_homewin = len(df[df.FTR == 'H'])
Or simplier count Trues values by sum:
n_homewin = (df.FTR == 'H').sum()
you should modify it to df[df.FTR == 'H']. The parentheses imply a function call

ValueError: invalid literal for int() with base 10: 'O'

I am relatively new to python, and as such I don't always understand why I get errors. I keep getting this error:
Traceback (most recent call last):
File "python", line 43, in <module>
ValueError: invalid literal for int() with base 10: 'O'
This is the line it's referring to:
np.insert(arr, [i,num], "O")
I'm trying to change a value in a numpy array.
Some code around this line for context:
hOne = [one,two,three]
hTwo = [four,five,six]
hThree = [seven, eight, nine]
arr = np.array([hOne, hTwo, hThree])
test = "O"
while a != Answer :
Answer = input("Please Enter Ready to Start")
if a == Answer:
while win == 0:
for lists in arr:
print(lists)
place = int(input("Choose a number(Use arabic numerals 1,5 etc.)"))
for i in range(0,len(arr)):
for num in range(0, len(arr[i])):
print(arr[i,num], "test")
print(arr)
if place == arr[i,num]:
if arr[i,num]:
np.delete(arr, [i,num])
np.insert(arr, [i,num], "O")
aiTurn = 1
else:
print(space_taken)
The number variables in the lists just hold the int version of themselves, so one = 1, two = 2 three = 3, etc
I've also tried holding "O" as a variable and changing it that way as well.
Can anyone tell me why I'm getting this error?

Guess number, no such attribute, python 3

I'm learning OOP in python and was trying to run this small game in OOP style, but for some reason system doesn't find object's attributes.
Here's the problem:
Traceback (most recent call last):
File "HelloUsername.py", line 47, in <module>
newGameGTN = GuessTheNumber()
File "HelloUsername.py", line 6, in __init__
self.start_game()
File "HelloUsername.py", line 32, in start_game
player = player_choice()
NameError: name 'player_choice' is not defined
On this code in python 3:
from random import randint
class GuessTheNumber(object):
"""docstring for GuessTheNumber"""
def __init__(self):
self.start_game()
self.player_choice()
self.compare_numbers()
def player_choice(self):
choice = int(input("Choose your number: "))
if choice in range(101):
return(choice)
else:
print("Please enter a number 0-100")
player_choice()
def compare_numbers(self, computer, player):
if player == computer:
return(0)
elif player > computer:
return(1)
elif player < computer:
return(-1)
def start_game(self):
computer = randint(0, 100)
turn = 0
for turn in range(3):
player = player_choice()
x = compare_numbers(computer, player)
print(computer)
if x == -1:
print("too small")
elif x == 1:
print("too big")
elif x == 0:
print("you win")
break
turn += 1
print("game over")
newGameGTN = GuessTheNumber()
newGameGTN.start_game()
NameError is not the same as AttributeError (which you mention in the question's summary). A NameError exception means that the name referenced in your code does not exist. A name can be a local variable, or a variable in an enclosing scope.
All methods in a class need to be called on an instance of that class. (staticmethods and classmethods not withstanding) Instead of name = player_choice() you need to write name = self.player_choice(). Likewise for all other occurrences where you call a method defined in the class.

How to fix when Python says: UnboundLocalError: local variable 'money' referenced before assignment

I am having troubles with my money variable. Each time I save and run, a ERROR pops up and I try to fix the problem but can't figure out how? I really need a reply so please soon. This is my project:
money = 0.0
Chop = 0
spike = 0
name = input("What is your name?")
greeting = 'Hello ' + name + ','
def Command():
Command = input('Press \"C\" to continue or Press \"E\" to exit -->')
if name == 'SpikeTheKing':
print('Welcome Spike,')
spike = 1
elif name == 'Spike':
spike = 1
print ('Welcome Spike,')
else:
print(greeting)
def draw_line():
print ('----------------')
def Work1():
Chop = input('Type anything to earn $1 -->')
while Chop == ('C') or ('c'):
print ('$1 earned')
money = money+1
displayMoney()
Chop = 0
Command()
def displayMoney():
draw_line()
print(('Money = '),('$'),(money))
draw_line()
displayMoney()
Work1()
if Command == ('C'):
Work1()
if Command == ('E'):
quit()
Each time I save and run this happens:
Traceback (most recent call last):
File "C:\Users\Leora\Desktop\Python Files\Python.py", line 35, in <module>
Work1()
File "C:\Users\Leora\Desktop\Python Files\Python.py", line 26, in Work1
money = money+1
UnboundLocalError: local variable 'money' referenced before assignment
What should I change?
In the def Work code, before you do money = money+1, you will need to initialize money. So in the first statement after def Work, do: money = 0...
Alternatively, money is global , so you could do global money, in the first line after def Work instead of money=0....
The global keyword tells the interpreter, that money is defined outside the scope of Work function and to look for it there

Learning Python 3.3 - TypeError: 'int' object is not callable

I was trying to solve Challenge 2 at the end of the classes chapter (Chapter 8) in "Python Programming for the Absolute Beginner" which is stated as:
Write a program that simulates a television by creating it as an object. The user should be able to enter a channel number and raise or lower the volume. Make sure that the channel number and the volume level stay within valid ranges.
I keep getting: TypeError: 'int' object is not callable, which at this stage just isn't very helpful.
I'm a beginner but I've seen something really similar working (see at the bottom right below my code) and nearly went as far as nearly copying that code. Could somebody maybe explain what's wrong with this and how I can get it to work?
Here's the complete error:
Traceback (most recent call last):
File "Untitled 3.py", line 59, in <module>
main()
File "Untitled 3.py", line 50, in main
tv.channel(newchannel = int(input("What channel would you like to set the TV to?")))
TypeError: 'int' object is not callable
My code is below,
Thanks
class Television(object):
"""a TV"""
def __init__(self, channel = 0, volume = 0):
self.channel = channel
self.volume = volume
def channel(self, newchannel = 0):
if newchannel <= 0 or newchannel >9:
print("No negative numbers or numbers higher than 9. Start again from the menu")
else:
self.channel = newchannel
print("You set the TV on channel", self.channel)
def volume(self, newvolume = 0):
if newvolume <= 0 or newvolume >9:
print("No negative numbers or numbers higher than 9. Start again from the menu")
else:
self.volume = newvolume
print("You set the TV on volume", self.volume)
def watch(self):
print("You are watching channel", self.channel, "at volume", self.volume)
def main():
tv = Television()
choice = None
while choice != "0":
print \
("""
TV
0 - Quit
1 - Watch the TV
2 - Change channel
3 - Set the volume
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
elif choice == "1":
tv.watching()
elif choice == "2":
tv.channel(newchannel = int(input("What channel would you like to set the TV to?")))
elif choice == "3":
tv.volume(newvolume = int(input("What channel would you like to set the TV to?")))
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
("\n\nPress the enter key to exit.")
Why does the following work instead? To me, it looks pretty similar to what I've done.
class Critter(object):
"""A virtual pet"""
def __init__(self, hunger = 0, boredom = 0):
self.hunger = hunger
self.boredom = boredom
def eat(self, food = 4):
print("Brruppp. Thank you.")
self.hunger += food
if self.hunger < 0:
self.hunger = 0
crit = Critter()
print(crit.hunger)
crit.eat(food = int(input("how much do you want to feed him?")))
print(crit.hunger)
The problem is you are defining a method with the same name as a property. That is, you're saying Television.channel is an int, but later you are binding a method to that name.