Python:将字符串转换为整数

问题描述 投票:0回答:1

首先,我是Python新手。我正在尝试制作一个简单的费用计算器。我有一个功能,用户可以输入行驶距离,另一个功能应该通过将行驶距离乘以每公里金额来计算旅行费用。

我知道我必须将输入从行驶距离转换为整数,然后才能将其相乘,但似乎无法获得整数值。

这是行驶距离函数:

def give_travel():
    """
    Function to prompt user to insert distance travelled in kilometers.
    While loop to ask user to confirm data given.
    """    
    print("Please enter the distance travelled for this event.")
    print("Distance should be given in kilometers")
    travel_input = input(f"The distance travelled is: (km) \n")
    
    print(f"You travelled {travel_input} kms for this event")
    correct_input = input("Is this correct? y/n \n")
    while True:
        if correct_input.lower() in ["yes", "y"]:
            print("Distance travelled confirmed.")
            break
        elif correct_input.lower() in ["no", "n"]: 
            return give_travel()  
        else:
            print("Invalid input. Please re-enter distance travelled to continue.")
            return give_travel()

这是计算费用的函数:

def travel_expenses():
    """
    Function to calculate travel expenses based on distance travelled.
    """
    
    travel_total = give_travel(travel_distance) * 0.43
    print(travel_total)    

我尝试使用

travel_distance = int(travel_input)
将travel_input定义为整数,但我不确定将其放在哪里,并且它不断返回错误。

如有任何建议,我将不胜感激...

python function integer string-conversion
1个回答
0
投票

要将用户输入转换为整数,您可以像这样进行转换:

 travel_input = int(input("The distance travelled is: (km) \n"))

顺便说一句,当您接受用户输入时,您还应该对其进行验证。您可以使用

try-catch
块来确保用户输入正确类型的数据:

try:
    travel_input = int(input(f"The distance travelled is: (km) \n"))
except ValueError:
    print("That's not an int!")
© www.soinside.com 2019 - 2024. All rights reserved.