AttributeError:' NoneType'对象没有属性' title'

时间:2016-03-23 23:13:46

标签: python python-3.x error-handling attributeerror

试图运行此代码,但错误说我用.title犯了一个错误。我怎样才能解决这个问题? (请注意,我仍然是Python世界的业余爱好者,并且对任何可以改进我的代码的建议持开放态度。但是,除非有解释,否则我可能无法理解它,如果它是新的,例如你可以使用__________而不是_________。)

这是我的代码:

import time
import sys

print("Welcome to my quiz")
time.sleep(2)
input('Press enter to continue')

score = int(0)
failed = int(0)

def points():
    print("Correct! Well done!")
    global score
    score = score + 1

def fail():
    print("Oh no, that is incorrect")
    global failed
    failed = failed + 1

def printtotal():
    global score
    global failed
    print("You have ",score,"points, and ",failed,"/3 lives used.")

if failed == 5:
    sys.exit('Program terminated.')

print('You will have 5 seconds to answer each question \nIf you fail 5 times or more, the program will exit')
time.sleep(3)
print('Good luck!')
time.sleep(2)

q1 = print(input("What is the capital of England?")).title
if q1 == 'London':
    points()
else:
    fail()
printtotal()

q2 = print(input("Who is the prime minister's wife?")).title
if q2 == 'Samantha' or 'Samantha Cameron':
    points()
else: 
   fail()
printtotal()

print('How would you say \'I came, I saw, I conquered\' in latin?')
print('a) veni, vidi, vici')
print('b) veni, vedi, vici')
print('c) vini, vedi, vici')
q3 = print(input('Type the letter here:'))
if q3 == 'a)' or 'a':
    points()
else:
    fail()
printtotal()

如果我尝试执行此代码,这就是我得到的错误:

Traceback (most recent call last):
  File "/root/Desktop/Python_Stuff/quiz.py", line 34, in <module>
    q1 = print(input("What is the capital of England?")).title
AttributeError: 'NoneType' object has no attribute 'title'

如果有人碰巧发现错误,请告诉我。我该如何解决这个错误?

4 个答案:

答案 0 :(得分:1)

print函数不返回任何内容,或者更具体地说它返回NoneType。因此,您无法获得其成员title的价值。

print(input("What is the capital of England?")).title

相当于:

answer = input("What is the capital of England?")
print(answer).title

print(answer)只会打印出用户输入的任何内容,然后返回一个无对象。你真正想要的是:

print(input("What is the capital of England?").title())

See this for more about print and title.

这将揭示您的代码的一个单独问题:您正在尝试同时输入内容并打印您想要输入的问题。在这种情况下this is what you want

q1 = input("What is the capital of England?")  # This will automatically print 'What is...' when it reaches this point in the program

以上内容会将用户输入保存到q1

答案 1 :(得分:0)

错误消息表明问题出在此行:

q1 = print(input("What is the capital of England?")).title

你在这里做的是询问用户输入(使用python3.x的input功能),然后将结果打印到标准输出(通常是屏幕或“终端窗口”) )。但是,print不会返回任何特殊内容,因此在python术语中,它返回NoneNone是一个单例(认为它是一种特殊类型的变量),它没有属性title,所以你不能输入例如None.title

考虑将输入存储到q1,如下所示:

q1 = input("What is the capital of England?")

答案 2 :(得分:0)

print()返回None。因此,print(...).title会提升您所看到的AttributeError

答案 3 :(得分:0)

print没有名为&#34; title&#34;的属性。也就是说,你不能这样做:

print().title

我觉得你想要做的就是完全摆脱print(),所以这样:

q1 = input("What is the capital of England?")
if q1 == 'London':