【问题标题】:Python code not running, do I need to reinstall python? [duplicate]Python代码没有运行,我需要重新安装python吗? [复制]
【发布时间】:2018-01-09 20:11:13
【问题描述】:

所以当我试图运行这段代码时。如您所见,它要求输入一个数字。

print('How old is Vini?')
number= 17
guess= int(input('enter a number'))
if guess== number:
    print('Bravo Vini is 17')
elif guess < number:
    print('Vini is older than '+guess)
elif guess > number:
    print('Vini younger than '+guess)

现在如果数字等于 17,它会执行,但如果数字更高或更低,它会给我这个错误:

当数字较大时:

Traceback (most recent call last):
  File "C:\Users\ervin\Desktop\loja.py", line 9, in <module>
    print('Vini younger than '+guess)
TypeError: must be str, not int

当数字较低时:

Traceback (most recent call last):
  File "C:\Users\ervin\Desktop\loja.py", line 7, in <module>
    print('Vini is older than '+guess)
TypeError: must be str, not int

【问题讨论】:

  • 为什么您首先考虑的是重新安装python而不是调查错误消息?
  • 见上文.. 并修正标题以避免过多的反动反对票。因为答案是:,你应该修复你的代码。
  • 我更倾向于print('Vini is older than', guess),而不是使用转换和连接。
  • 你不需要重新安装python,你需要rewrite python,这样你就可以像在Javaaaaah中那样添加带有整数的字符串
  • @Mangohero1:我认为这不适用。标题很差,但问题符合“itsnotworking”链接中提到的所有内容。

标签: python python-3.x


【解决方案1】:

您需要将guess 转换为字符串才能使print 语句起作用,请尝试编写+ str(guess) 而不是+ guess

【讨论】:

  • 你的方法有效。但是如果我希望猜测是一个整数呢?
  • @ErsonCokaj str(guess) 不会将guess 永久更改为字符串,它仅用作该事件的字符串,在这种情况下在print 中,它不会有任何副作用
  • @NickA 好的,谢谢,非常有帮助:)
【解决方案2】:

在语句print('Vini is older than '+guess) 中,您尝试将字符串('Vini is old than ')与整数(17)连接起来,这是错误的,因此您得到了错误。

使用

 print('Vini is older than '+str(guess))

str(guess) 将整数转换为字符串。 现在你正在连接两个有效的字符串。

【讨论】:

    猜你喜欢
    • 2012-11-20
    • 2023-03-22
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2013-09-18
    • 2016-05-20
    相关资源
    最近更新 更多