无法获取要分配给variab的值

2024-04-30 06:54:05 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
print('-\n')
begin=int(raw_input('-\n')
end=int(raw_input('-\n')
rep=int(raw_input('-\n')
def dop():
    print random.randinterga
ivfhoierh
while count < rep:
    print do
    count = count + 1

print('Thanks for using this program!\n')
raw_input('press enter to continue')

好吧,我真的不知道iv做错了什么,但我一直得到一个语法错误和空闲突出显示“结束”

编辑:C


Tags: importinputrawdefcountrandomintend
2条回答

从原始输入判断,我猜您正在使用Python2。 将代码更正为:

import random
print 'Hi, I will print out random intergers from a range you specify.\n'
#No need for parenthesis
begin=float(raw_input('Please enter the starting range. \n'))
end=float(raw_input('Please enter the end range. \n'))
rep=float(raw_input('Please enter how many times you cant to repeat the function. \n'))
# ERROR you forgot an extra parenthesis on the end of each of the last 3 lines.
def do():
    print random.randint(begin, end)

count = 0
while count < rep:
    do()  # <- Parenthesis, and no need to print.
    count = count + 1

print 'Thanks for using this program!\n' #No need for parenthesis
raw_input('press enter to continue')

还包括:

count = 0
while count < rep:
    do()  # <- Parenthesis, and no need to print.
    count = count + 1

可替换为:

for count in range(rep):
    do()

我会这样做:

import random
print 'I will print out random integers from a range you specify.'

begin = int(raw_input('Please enter the starting range: '))
end = int(raw_input('Please enter the end range: '))
rep = int(raw_input('Please enter the repeat value: '))

def get_random():
    return random.randint(begin, end)

for _ in range(rep):
    print get_random()

对细节的关注非常重要

解决的问题:

  • 不匹配的括号
  • 不一致的任务
  • 不一致地使用print
  • 个人偏好高于返回,然后打印
  • 为清晰起见,重命名了函数do()
  • raw_input()不需要\n新行
  • randint()在浮点值上生成ValueError: non-integer arg 1 for randrange()时出错;相应地投射raw_input()
  • (小调)输出中更正的拼写
  • 将while循环替换为for循环,删除不需要的变量count和赋值

希望这有帮助

相关问题 更多 >