簡體   English   中英

Python用戶輸入和數學運算錯誤

[英]Python user input and mathematical operation error

>>> g = input("Enter a number")
Enter a number43
>>> g + 2
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    g + 2
TypeError: Can't convert 'int' object to str implicitly

該程序不會讓我在數學運算中使用輸入變量,例如g + 2

在python 3中,即使您輸入數字, input()也會返回字符串類型。 因此,您正在嘗試添加帶有字符串的整數

您需要使用int()將其轉換為整數類型:

g = int(input("Enter a number"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM