2017-07-04 35 views
-2

非常感谢您阅读我的第一篇文章。Python初学者 - TypeError:'''不支持'str'和'int'的实例

开始学习Python的3.6.1 - 被困在起动 - 有什么不对下面的代码:

print('Hi there! What is your name?') 
myName = input() 
print("Hello " + myName + ' its good to met you. My name is Kendo.') 

print('how old are you?') 
myAge = input() 
if myAge < 15: 
    print('go to bed, kiddo') 
elif myAge > 95: 
    print('Sup, grandma') 
elif myAge > 1000: 
    print('Lol, stop kidding me') 
+0

看看https://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int,涵盖Python 2和3. –

+0

@Marko Petkovic我发布了一个小的答案覆盖python 2.x和3.x – sera

回答

0

你输入一个字符串,你需要将其转换为int使用比较操作。

相反的:

print('how old are you?') 
myAge = input() 

试试这个:

myAge = int(input('How old are you?') 
0

的问题是,你需要一个整数但是输入()返回一个字符串。 您可以将输入使用somrthing像下面这样诠释:

对于Python 3.x都有

myAge = int(input("Enter a number: ")) 

对于的Python 2.x的

myAge = input("Enter a number: ") 
>>>Enter a number: 5 + 17 

myAge, type(myAge) 
(22, <type 'int'>) 
0

输入返回python 3中的一个字符串对象。您试图查看一个字符串是小于还是大于一个整数。这不起作用。

从Python 3.6文档 https://docs.python.org/3/library/functions.html#input 输入([提示]) 如果提示参数存在时,它被写入到标准输出没有尾随换行符。然后该函数从输入中读取一行,将其转换为字符串(剥离尾随的换行符),然后返回该行。

尝试:

myAge= int(myAge) 

不要但是请注意,如果当你给任何非数字字符输入在myAge = input()这将引发其他错误。因为你不能强迫非数字字符转换为整数。

相关问题