简体   繁体   English

如何在输入中找到随机数?

[英]How to find random numbers in input?

I want the print statement to print the number in the range between the low and upper. 我希望print语句打印上下限之间的数字。

I keep getting the error code: 我不断收到错误代码:

Traceback (most recent call last):File "python", line 5, in <module> ValueError: non-integer arg 1 for randrange()

From the program: 从程序中:

from random import*
lowRange = input('What is the lower range number?')
hiRange = input('What is the higher range nunmber?')

ran = randrange (lowRange,hiRange)
print (ran)

The input() function always returns a string. input()函数始终返回一个字符串。 If you want to use integers, as in this case, you have to convert those strings to integers using int() . 如果要使用整数(在这种情况下),则必须使用int()将这些字符串转换为整数。 However, if the user enters something that cannot be converted to an integer (eg 'hi', or just hitting return), you will get an error when trying to convert. 但是,如果用户输入的内容无法转换为整数(例如“ hi”,或仅按回车键),则在尝试转换时会出现错误。 To deal with that, you will want to look into try and except statements. 为了解决这个问题,您将需要研究try和except语句。 Hope that helps! 希望有帮助!

Try this: 尝试这个:

In here until you enter a number it wouldn't stop. 在这里,直到您输入数字,它才会停止。 Inputs other than int will take as an invalid input. int其他输入将视为无效输入。

What's wrong in your code is everything reads from input is taken as a string. 代码中的问题是从输入中读取的所有内容都被当作字符串。

from random import*
while True:
        try:
            lowRange = int(input('What is the lower range number?'))
            break
        except:
            print("That's not a valid input!")
while True:
        try:
            hiRange = int(input('What is the higher range nunmber?'))
            break
        except:
            print("That's not a valid input!")

ran = randrange (lowRange,hiRange)
print (ran)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 INPUT 生成范围内的随机数? - How to generate random numbers in range from INPUT? 如何使用随机数作为 if 语句的输入? - How to use random numbers as an input for a if statement? 如何生成具有给定输入长度的随机数以进行加法和乘法 - How to generate random numbers with given length of input to add and multiply 如何在用户输入的数字之间找到数字? - How to find the numbers in between the numbers that the user has input? 如何在python中找到一定范围内的随机数之和? - How do i find the sum of a range of random numbers in python? 我们如何在 Python 的随机生成列表中找到指定的数字 - How do we find specified numbers in a random generated list in Python python 如何在不使用随机库的情况下根据给定的输入生成随机数? - python how to generate random numbers based on given input without using random library? 如何在Python的随机数数组中找到最多和最少的猜测数? - How do I find the most and least guessed numbers in an array of random numbers in Python? 如何找到张量流中随机输入的训练网络的输出? - How to find the output of a trained network for a random input in tensor flow? 彩票循环通过列表中的随机数找到找到它需要多少计数 - lottery loop through random numbers in a list find how many counts it took to find it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM