我的問題是當我在輸入欄位中輸入一個數字時,它變成了帶有特殊字符的數字。我不知道為什么它會在輸入中添加額外的字符。你可以看看這個例子。我只輸入了 5.2,它變成了 '5.2&
"""
length of rectangle = a
width of rectangle = b
calculate the area and perimeter of the rectangle
"""
a = 6
b = float(input("width: "))
area = a*b
perimeter = (2*a) (2*b)
print("area: " str(area) " perimeter: " str(perimeter))
File "c:\Users\HP\OneDrive - Karabuk University\Belgeler\Downloads\first.py", line 8, in <module>
b = float(input("width: "))
ValueError: could not convert string to float: '5.2&
請你幫助我好嗎?
uj5u.com熱心網友回復:
對我來說它作業正常...查看我的輸出..
注意:它會在代碼的最后一行引發錯誤,因為您無法將 astr與int.
因此,您需要在連接變數之前轉換int為str
a = 6
b = float(input("width: "))
print(b)
area = a*b
perimeter = (2*a) (2*b)
print("area: " str(area) " perimeter: " str(perimeter))
#輸出
width: 5.2
5.2
area: 31.200000000000003 perimeter: 22.4
替代解決方案 2
Idk 為什么它會在您的用戶輸入中添加額外的字符......無論如何,您可以在輸入后過濾用戶輸入,如下所示。
import re
a = 6
b = (input("width: "))
b=str(b)
b=re.sub("[^0-9^.]", "", b)
b=float(b)
print(b)
area = a*b
perimeter = (2*a) (2*b)
print("area: " str(area) " perimeter: " str(perimeter))
輸出 #
width: 5.2b
5.2
area: 31.200000000000003 perimeter: 22.4
uj5u.com熱心網友回復:
"""
length of rectangle = a
width of rectangle = b
calculate the area and perimeter of the rectangle
"""
"""
We cannot replicate this error.
b = float(input("width: "))
ValueError: could not convert string to float: '5.2&
Debug by breaking down the code to see which function is the source of the
error.
"""
a = 6
# b = float(input("width: "))
s = input("width: ")
print("s= " s)
b = float (s)
area = a*b
perimeter = (2*a) (2*b)
print("area: " str(area) " perimeter: " str(perimeter))
輸出
width: 5.2
s= 5.2
area: 31.200000000000003 perimeter: 22.4
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526198.html
