[英]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.