我刚刚开始学习Python,并对我正在阅读的教科书中出现的练习提出疑问。
我发现了一个功能正常的解决方案,但我想知道是否有更简单/推荐的解决方案?
问题:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ' '
#concatenate X to print numXs times print(toPrint)
我的解决方案:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
while (toPrint == ''):
if numXs == 0:
numXs = int(input('Enter an integer != 0 '))
else:
toPrint = abs(numXs) * 'X'
print(toPrint)
答案 0 :(得分:4)
我建议您事先处理所有数据检查和纠正,这样您的实际算法就会简单得多:
numXs = 0
while numXs <= 0:
numXs = int(input('How many times should I print the letter X? '))
if numXs <= 0:
print('Enter an integer > 0')
print('X' * numXs)
答案 1 :(得分:1)
一个简单的解决方案是
try:
print("x" * int(input("how many times?")))
except:
print("you entered an invalid number")
如果您想要零或负面检查
try:
num = int(input("how many times?"))
if num > 0:
print("x" * num)
else:
print("need a positive integer")
except:
print("not a number")
如果您希望永远发生这种情况,只需将其包裹在while循环中
while True:
#code above
答案 2 :(得分:-1)
您没有处理错误的转换(输入“Eight”) - 因此您可以将其缩短为:
print(abs(int(input("How many?")))*"X") #loosing the ability to "requery" on 0
相同的功能:
numXs = abs(int(input('How many times should I print the letter X? ')))
while not numXs: # 0 is considered FALSE
numXs = abs(int(input('Enter an integer != 0 ')))
print(numXs * 'X')
更安全的:
def getInt(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg)
while not i.isdigit():
i = input(errorMsg)
return int(i)
我正在使用isdigit()
来确定input
是否是我们可以使用的数字。您还可以在try:
周围执行except:
和int(yourInput)
,这样您就可以捕获不可以转换为整数的输入:
def getIntWithTryExcept(msg, errorMsg):
'''Function asks with _msg_ for an input, if convertible to int returs
the number as int. Else keeps repeating to ask with _errorMsg_ until
an int can be returned'''
i = input(msg) # use 1st input message
num = 0
try:
num = int(i) # try convert, if not possible except: will happen
except:
while not num: # repeat with 2nd message till ok
i = input(errorMsg)
try:
num = int(i)
except: # do nothing, while is still True so it repeats
pass
return int(i) # return the number