预期类型'int'改为'float'

时间:2019-08-11 20:52:10

标签: python python-3.x

weight_lbs = input ('weight (lbs): ')
weight_kg = int(weight_lbs * 0.45)
print(weight_kg)
  

错误:预期类型'int'改为'float'。

请告知。

4 个答案:

答案 0 :(得分:1)

您的输入weight_lbs是一个字符串,而不是数字。将其转换为intfloat

weight_kg = int( float(weight_lbs) * 0.5)

(而且,磅不是半公斤。为什么不更准确?您有电脑!)

答案 1 :(得分:1)

我尝试了您的代码,尽管遇到了另一个问题,但我没有遇到相同的问题。

此代码:

weight_kg = int(weight_lbs * 0.5)

应该是:

weight_kg = int(weight_lbs) * 0.5

否则,您将收到此错误:

  

TypeError:无法将序列乘以'float'类型的非整数

原因是您的代码将字符串乘以数字。您首先需要将input()返回的字符串转换为数字,然后进行乘法。

答案 2 :(得分:0)

您可以尝试以下方法:

weight_lbs = input('weight (lbs): ')
weight_kg = int(float(weight_lbs) * 0.5)
print(weight_kg)

答案 3 :(得分:0)

它对我有用:

import SwiftUI
import UIKit

struct CustomTextField: View {
    @State var text: String
    @State var pos: CGPoint

    var body: some View {
        StrokeTextLabel(text: text)
//            .frame(width: UIScreen.main.bounds.width - 16, height: 40, alignment: .center)
            .position(pos)
            .gesture(dragGesture)
    }

    var dragGesture : some Gesture {
        DragGesture()
            .onChanged { value in
                self.pos = value.location
                print(self.pos)
        }
    }
}

struct StrokeTextLabel: UIViewRepresentable {
    var text: String

    func makeUIView(context: Context) -> UITextField {
        let attributedStringParagraphStyle = NSMutableParagraphStyle()
        attributedStringParagraphStyle.alignment = NSTextAlignment.center
        let attributedString = NSAttributedString(
            string: text,
            attributes:[
                NSAttributedString.Key.strokeColor : UIColor.white,
                NSAttributedString.Key.foregroundColor : UIColor.black,
                NSAttributedString.Key.strokeWidth : -4.0,
                NSAttributedString.Key.font: UIFont(name: "impact", size: 50.0)!
            ]
        )

        let strokeLabel = UITextField(frame: CGRect.zero)
        strokeLabel.attributedText = attributedString
        strokeLabel.backgroundColor = UIColor.clear
        strokeLabel.sizeToFit()
        strokeLabel.center = CGPoint.init(x: 0.0, y: 0.0)
        strokeLabel.sizeToFit()
        return strokeLabel
    }

    func updateUIView(_ uiView: UITextField, context: Context) {}
}

#if DEBUG
struct CustomTextField_Previews: PreviewProvider {
    static var previews: some View {
        CustomTextField(text: "test text", pos: CGPoint(x: 300, y: 500))
    }
}
#endif