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

需求:编写Python脚本生成两个指定数字间的随机数(含报错代码)

生成指定区间随机数的正确Python脚本

需求说明

编写Python脚本,实现接收用户输入的两个数字,返回这两个数字之间(包含两端)的随机整数,运行示例如下:

Type the first number: 2
Type the last number: 8
Choosing a number between 2 and 8.
The number is 7.

Type the first number: -1
Type the last number: 5
Choosing a number between -1 and 5.
The number is -1.

用户错误代码分析

第一段错误代码

import random
first = input('Type the first number: ')
last = input('Type the last number: ')
print('Choosing a number between '+str(first)+' and'+ (last))
roll = random.randint +str
print('The number is ',(roll),'.')

报错原因:random.randint是需要传入参数调用的方法,这里错误地将它和str类型直接相加,属于语法错误,触发TypeError: unsupported operand type for +: 'method' and 'type'。

第二段错误代码

import random
first = input('Type the first number: ')
last = input('Type the last number: ')
print('Choosing a number between '+str(first)+' and'+ (last))
roll = random.randint (first,last)
print('The number is ',(roll),'.')

报错原因:

  1. input()默认返回字符串类型,random.randint()要求传入整数参数,直接传字符串会触发类型错误;
  2. 打印语句中first已经是字符串,无需再用str()转换,且and后缺少空格,会导致输出格式异常。

正确实现脚本

import random

# 获取用户输入并转换为整数类型
first = int(input('Type the first number: '))
last = int(input('Type the last number: '))

# 输出区间提示信息,使用f-string简化字符串拼接
print(f'Choosing a number between {first} and {last}.')

# 生成指定区间内的随机整数(包含两端数值)
roll = random.randint(first, last)

# 输出最终随机数
print(f'The number is {roll}.')

代码说明

  • 用int()将用户输入的字符串转换为整数,满足random.randint()的参数类型要求;
  • 使用f-string进行字符串格式化,代码更简洁易读,避免拼接错误;
  • random.randint(a, b)会生成包含a和b在内的区间随机整数,完全符合需求。

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:17:17