You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python快餐随机代码报错‘invalid literal for int() with base 10’的原因解析

问题原因及解决方案

1. 触发报错的直接原因

invalid literal for int() with base 10是因为你试图把"mcdonalds"、"burger_king"这类非数字字符串用int()强制转换——整数转换只能处理纯数字组成的字符串,餐厅名称完全不符合这个要求,自然会报错。

2. random.randint的用法完全错误

random.randint的设计是接受两个整数参数:表示随机数的最小值和最大值(比如random.randint(1,6)会生成1到6之间的整数),而不是传入一堆整数。你现在的调用方式从参数数量到参数类型都不符合API要求。

3. 隐藏问题:缺少random模块导入

代码里只导入了time,但使用了random.randint,如果解决了字符串转整数的问题,接下来会触发NameError: name 'random' is not defined的错误。


修正后的代码

import time
import random  # 补充导入random模块

# 将餐厅名称存入列表,方便直接随机选择
restaurants = [
    "mcdonalds",
    "burger_king",
    "culvers",
    "little_ceasers",
    "Panda Express",
    "Taco Bell"
]

print("welcome to the fast food randomizer! I choose between some of the most popular fast food restaurants in maricopa")
print("randomizing")
time.sleep(3)
# 用random.choice直接从列表中随机选取一个元素
answer = random.choice(restaurants)
print(f"The food place you are eating at is! ")
print(answer)

内容的提问来源于stack exchange,提问作者ZDilly Da Silly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 20:21:43