我有下面的示例代码,如果输入值是整数,我想执行特定的。 如果用户输入了一个整数特定代码将被执行,否则它应该提示输入值不是整数的错误并再次提示输入。 应该这样做直到输入整数或强制完全退出代码。 我还必须对输入值进行多次测试。
import random
print('Hello , What is your name')
name = input()
print('hello '+ name +' i am thinking a number between 1 to 20. Please take a guess')
inputNumber = input()
if inputNumber == int:
#Code
else:
print('please enter the int')
答案 0 :(得分:3)
您需要try
将其转换为integer
,假设用户提供的输入为整数然后继续,在您的代码段中input()
函数从用户获取输入并转换为它变成了字符串See Documentation,因此if b == int:
总是会给你错误的。
正确的程序:
import random
print('Hello , What is your name')
name = input()
print('hello ' + name + ' i am thinking a number between 1 to 20. Please take a guess')
while(True):
try:
inputNumber = int(input())
# now it is sure that input number is integer.
### CODE
except ValueError:
print('please enter the int')
这里我已根据无限循环进行了更新但您可以根据您的代码逻辑修改类似while(inputNumber != randomNumber)
的内容,但为此您需要在while循环开始之前从用户那里获取输入:
import random
print('Hello , What is your name')
name = input()
print('hello ' + name + ' i am thinking a number between 1 to 20. Please take a guess')
randomNumber = random.randint(1,21)
try:
inputNumber = int(input())
except ValueError:
print('please enter int only')
while(inputNumber != randomNumber):
try:
print('try again!')
inputNumber = int(input())
# now it is sure that input number is integer.
if (inputNumber == randomNumber):
print('correct')
break
except ValueError:
print('please enter the int')
答案 1 :(得分:1)
如果您的猜测太高或太低,它会使反馈变得更具互动性。
import random
lower = 1
upper = 20
rand = random.randint(lower,upper)
name = input('Hello , What is your name? ')
entered = input('hello %s i am thinking a number from %s to %s. Please take a guess: ' % (name, lower, upper))
while True:
try:
guess = int(entered)
if guess > rand:
print('Lower!')
elif guess < rand:
print('Higher!')
elif guess == rand:
break
except:
print('You did not enter a valid integer!')
entered = input('Try again: ')
print('Congratulations! You guessed correctly!')
答案 2 :(得分:0)
感谢大家帮助我,特别是术士和埃文。 我在这里粘贴代码只是为了确认问题已经解决。
##This the guess the number.
import random
print('Hello , What is your name')
name = input()
print('hello '+ name +' i am thinking a number between 1 to 20. Please take a guess')
guess = random.randint(1,10)
while True:
try :
inputNumber = int(input())
if inputNumber > guess :
print('Lower!')
elif inputNumber < guess :
print('Higher!')
elif inputNumber == guess :
print('Well Done, Its a Correct Guess')
break
except:
print('Enter a number dear')
print('Thanks for playing')
答案 3 :(得分:-2)
您可以将代码(包括if
)放入while循环中。像这样:
invalidInput = True
while invalidInput:
# Ask for user input
if (test_if_user_input_is_valid) :
invalidInput = False
# Rest of the code
else:
# Ask the user for the right format. This takes back to the beginning of while loop