需求:编写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),'.')
报错原因:
input()默认返回字符串类型,random.randint()要求传入整数参数,直接传字符串会触发类型错误;- 打印语句中
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
相关产品推荐
相关产品推荐

