对于在python3中包含范围的循环
我需要定义一个函数,该函数接收由数字组成的字符串,并检查以下要求: 字符串不是空的 第一个字符的范围为1,10 除第一个字符外,每个字符的范围为0,10 如果字符串满足所有要求,则返回True,否则返回False。 我尝试的是if-in-for循环,反之亦然 我还尝试将下面代码中的返回函数移动到不同的缩进位置,但没有任何帮助对于在python3中包含范围的循环,python,python-3.x,Python,Python 3.x,我需要定义一个函数,该函数接收由数字组成的字符串,并检查以下要求: 字符串不是空的 第一个字符的范围为1,10 除第一个字符外,每个字符的范围为0,10 如果字符串满足所有要求,则返回True,否则返回False。 我尝试的是if-in-for循环,反之亦然 我还尝试将下面代码中的返回函数移动到不同的缩进位置,但没有任何帮助 def is_positive_int(st): n = len(st) if n > 0: if st[0]>= 0 and st[0]<= 9
def is_positive_int(st):
n = len(st)
if n > 0:
if st[0]>= 0 and st[0]<= 9:
for i in range(1,n):
if st[i]>= 0 and st[i]<= 9
return True
何处为
print(is_positive_int("123.0"))
should return False
及
您也可以在字符串上迭代:
for character in st:
# your conditionals
然后使用字符代替st[i]
但也要注意,使用条件句时,不能将字符串与数字进行比较。所以,您应该做的是创建一组数字,或者对字符串使用isdigit方法。
综上所述,您的函数应该是这样的:
def is_positive_int(st):
if not (st and st[0] != '0'):
return False
for character in st:
if not character.isdigit():
return False
return True
您需要将字符串中的条目转换为int,否则您的条件语句将抛出错误: 您的代码:
def is_positive_int(st):
n = len(st)
if n > 0:
if (st[0]>= 0) and (st[0]<= 9):
for i in range(1,n):
if st[i]>= 0 and st[i]<= 9:
return True
由于在这个函数中,如果有非数字字符,则不会断言它,因此遇到这些字符时,它不能返回False。相反,它在尝试转换时会抛出错误。所以你可以做:
def is_positive_int(st):
entries = list(st) # create a list of all items in the string
if entries: # assert this list has length > 0
output = True # initialise output
for e in entries:
output *= e.isdigit() # update outputs : a single False will convert output to 0.
return bool(output) # convert output to boolean
else: # if the string is empty, return False.
return False
我可以提出两种备选方法: 选项1:直接迭代字符串,并将每个字符与每个位置允许的字符进行比较。不要将字符与数字进行比较
import string
def func(input_str):
if len(input_str) == 0:
return False
for i, c in enumerate(input_str):
if i == 0:
allowed_chars = string.digits[1:] # exclude '0'
else:
allowed_chars = string.digits
if c not in allowed_chars:
return False
return True
选项2:使用正则表达式;我知道它们并不总是一个解决方案,但在本例中,它们允许使用非常短的代码解决方案
import re
def func(input_str):
if re.match(r'^[1-9][0-9]*$', input_str):
return True
return False
这有用吗?试试这个
如果您输入的内容不是可以转换为int的字符串,它将运行except条件。大于1只是确认有第二个数字
def is_positive_int(input):
try:
if int(input[0]) in range(1,10) and int(input) and len(input)>1:
return True
else:
return False
except:
print('invalid input')
使用rangeleniterable迭代iterable的索引:
def为正整数字符串:
正整数={1,2,3,4,5,6,7,8,9}
如果lenstring==0:
返回错误
如果intstring[0]不是正整数:
返回错误
对于范围1中的i,lenstring:
如果intstring[i]不是正数|{0}:
返回错误
返回真值
请注意使用集合来定义可接受的数字,因为它是用于此目的的有效数据结构,并且还可以使用正的_ints=setrange1,10动态构造
int调用之所以存在,是因为字符串[i]的元素将是字符串,并且总是与false比较,因为1==1是false
最后,返回的级联样式通常是首选的,因为它跳过了函数中不相关的部分,并且只有在没有其他东西阻止它直到结束时才返回True
您可以迭代字符串本身的字符,而不是对索引进行操作:
def为正整数字符串:
正整数=设置范围1,10
如果lenstring==0:
返回错误
如果intstring[0]不是正整数:
返回错误
对于字符串中的字符:
如果整数字符不在正整数{0}中:
返回错误
返回真值
请注意,如果字符串中的某个字符无法转换为int,这两种情况都会引发异常。可以通过将数字转换为字符串来防止这种情况:
def为正整数字符串:
正整数=范围为1,10的x的setstrx
如果lenstring==0:
返回错误
如果字符串[0]不是正整数:
返回错误
对于范围1中的i,lenstring:
如果字符串[i]不是正整数{0}:
返回错误
返回真值
如果必须只检查正整数,则可以使用.is.isdigit
使用内置函数all和列表理解,只需添加到许多选项中
def test_num(num):
# check for empty string
if len(num) == 0:
return False
# check all numbers are digits,
# if so, is the first digit > 0
return all(i.isdigit() for i in num) and int(num[0]) > 0
if __name__ == '__main__':
for num in ['', '0', '1', '123.0', '123', '+123', '-123']:
print(f'\'{num}\' is positive: {test_num(num)}')
# '' is positive: False
# '0' is positive: False
# '1' is positive: True
# '123.0' is positive: False
# '123' is positive: True
# '+123' is positive: False
# '-123' is positive: False
您可以使用该函数检查字符串是否是介于0和9之间的数字,我们可以按如下方式使用它
def is_positive_int(st):
#Get the length of the string
n = len(st)
#Flag to capture result
result = True
#If the string is empty, result is False
if n == 0:
result = False
#If the string has only one character, if the character is not 0, result is False
elif n == 1:
if st[0] == '0':
result = False
else:
#Otherwise iterate through all characters in the string
for i in range(1, n):
#If we find a character which is not a digit, result is False
if not st[i].isdigit():
result = False
break
#Return the final result
return result
上述功能的输出将为
print(is_positive_int(""))
#False
print(is_positive_int("0"))
#False
print(is_positive_int("1"))
#True
print((is_positive_int("123.0")))
#False
print((is_positive_int("123")))
#True
停在第一个问题上:您认为n>0:意味着什么?n=lenst是您的停止标准,但没有任何东西会将其传递给您的循环。for n>0在Python中没有任何意义,因为for在iterables上工作。while循环可以使用它,但是由于n不变,n>0将始终为True或False,除非在循环中递增它。请注意,这类操作通常是通过for循环完成的。我不确定我是否理解,我需要字符串不为空,因此只有当lenst>0时,我才能检查下一个requirementsSure,但我试图让您思考Python如何看待n>0。孤立地说,这对你意味着什么?大于0的任何值,因此它将是开放式的。没错,我不想对字符串长度设置上限,只是它不能为空。通过此更改,当我运行一个字符串(如99.0)时,它仍然返回True,如果可以避免,则应将其返回为false。您不应将字符串强制转换为int,因为您将需要除杂波之外的所有尝试来捕获所有可能的异常。不建议使用空白异常 pt;而是使用除ValueError:之外的值。
def is_positive_int(input):
try:
if int(input[0]) in range(1,10) and int(input) and len(input)>1:
return True
else:
return False
except:
print('invalid input')
def is_positive_int(st):
return st.isdigit() and int(st) > 0
>>>is_positive_int('123')
True
>>>is_positive_int('123.0')
False
>>>is_positive_int('0')
False
>>>is_positive_int('#$%')
False
>>>is_positive_int('-123')
False
>>>is_positive_int('')
False
def test_num(num):
# check for empty string
if len(num) == 0:
return False
# check all numbers are digits,
# if so, is the first digit > 0
return all(i.isdigit() for i in num) and int(num[0]) > 0
if __name__ == '__main__':
for num in ['', '0', '1', '123.0', '123', '+123', '-123']:
print(f'\'{num}\' is positive: {test_num(num)}')
# '' is positive: False
# '0' is positive: False
# '1' is positive: True
# '123.0' is positive: False
# '123' is positive: True
# '+123' is positive: False
# '-123' is positive: False
def is_positive_int(st):
#Get the length of the string
n = len(st)
#Flag to capture result
result = True
#If the string is empty, result is False
if n == 0:
result = False
#If the string has only one character, if the character is not 0, result is False
elif n == 1:
if st[0] == '0':
result = False
else:
#Otherwise iterate through all characters in the string
for i in range(1, n):
#If we find a character which is not a digit, result is False
if not st[i].isdigit():
result = False
break
#Return the final result
return result
print(is_positive_int(""))
#False
print(is_positive_int("0"))
#False
print(is_positive_int("1"))
#True
print((is_positive_int("123.0")))
#False
print((is_positive_int("123")))
#True