修改为先前的问题:程序耗时数英里 [英] revised to earlier question: program laps to miles

查看:57
本文介绍了修改为先前的问题:程序耗时数英里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import re

user_miles = input()

def miles_to_laps(user_miles):
miles = float(user_miles) * 4
    print('%0.2f'% miles)
    return
miles_to_laps(user_miles)

def parse_function_text(s):
    try:
        return re.search("miles_to_laps\((.+)\)", s)[1]
    except TypeError:
        return None

def accept_input(user_input):
    desugar = parse_function_text(user_input)
    if desugar is not None:
        user_input = desugar    
    try:
        return float(user_input)
    except ValueError:
        raise ValueError("Cannot process input %s" % user_input)

assert accept_input("miles_to_laps(3.5)") == 3.5

因此,执行此操作将显示用于创建程序的新代码,该代码允许输入为"miles_to_laps(20)"我目前的错误代码是

So doing this to show the new code that is being used to create the program allowing for the input to be " miles_to_laps(20)" my error code for this right now is

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    miles_to_laps(user_miles)
  File "main.py", line 6, in miles_to_laps
    miles = float(user_miles) * 4
ValueError: could not convert string to float: 'miles_to_laps(20)'

推荐答案

此行代码接受输入,但始终返回字符串,因此如果您键入 20 作为对此输入的响应,它以 '20'(字符串或 str 类型)存储在内存中

This line of code accepts an input, but always returns a string, so if you type a 20 as a response to this input, it is stored in memory as a '20' (a string OR str type)

user_miles = input()

您的函数旨在执行数学运算,因此需要数字(即整数类型( int )或浮点类型( float ).

Your function is intended to perform math and thus expects numbers (i.e. integer type (int) OR a float type (float).

解决此问题的最简单方法是使用 int()函数包装 input()函数立即将字符串转换为整数.

The easiest way to fix this is to immediately convert the string to an integer, using the int() function to wrap the input() function.

user_miles = int(input())

这篇关于修改为先前的问题:程序耗时数英里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆