我的任务是编写程序。
代码中有一个名为num1的变量,num1必须仅是数字,且长度为5。
该代码应打印num1中的每个数字及其总和。
这里的问题是,如果num1的长度不为5,则它不起作用,并且num1中的字符不是数字。
问题似乎出在其中。
请告诉我程序中有什么不好的地方(我仍然是python的初学者) 编辑:感谢您的帮助!我很欣赏,我也很满意,新的代码是正确的。 :D
>>> var1s
'ppleADayKeepsTheDocto'
>>> var2s
'Ig00000noranceIsBliss'
答案 0 :(得分:0)
我的任务是编写代码。在代码中有一个名为num1的变量,num1必须仅是数字,且长度为5。该代码应打印num1中的每个数字,它们是和。这里的问题是,如果num1的长度大于5或小于5,则它不起作用,并且num1中的字符不是数字。
这听起来像作业。
此外,您的代码示例是屏幕截图。请在问题正文的格式化代码块中包含完整的示例代码。
更多细节也是必要的,但是我认为以下内容可能是您开始思考如何完善问题的一个很好的起点:
import re
def print_numbers_and_sum(input_string: str):
"""
Find all numbers in an input string, print them and their sum
"""
all_numbers = []
# Using Regular Expressions (re), define a pattern
# that will catch numbers from the input string
number_pattern = r"[-+]?[0-9]*\.?[0-9]*"
number_regex = re.compile(number_pattern)
# Iterate over the matches in our input string
for number_string in number_regex.findall(input_string):
# the input string can potentially be empty
if number_string:
current_number = float(number_string)
all_numbers.append(current_number)
print(current_number)
# Sum is part of the standard library and will sum values in an iterable
print(sum(all_numbers))
if __name__ == "__main__":
input_string = "-206.35 and another number 4005.32"
print_numbers_and_sum(input_string)
答案 1 :(得分:0)
尝试一下:
# -*- coding: utf-8 -*-
max_value = 5
#The main function, it only summons the other functions and gets an input for num1.
#If the value entered in the functions is not ok, a loop happens in the main function.
def main():
global max_value
#This line requests from you to put an input with 5 digits
num1 = input("Please enter a number with 5 digits\n")
bol = check_everything(num1)
if bol == False:
while (len(num1) != max_value) or (num1.isdigit() == False):
num1 = input("Please enter a number with 5 digits and with digits only\n")
num1 = int(num1)
printer(num1)
def check_everything(num1):
if (len(num1) == max_value) and (num1.isdigit() == True):
return True
else:
return False
def printer(num1):
numsum = 0
s1 = ''
for x in range(max_value):
s1 += str(num1)[x] + ','
print(s1[:-1:])
for i in range(len(str(num1))):
numsum = numsum + int(str(num1)[i:i+1])
print(str(numsum))
if __name__ == '__main__':
main()
答案 2 :(得分:0)
您可以使用while loop
设置条件,该条件仅接受满足拥有string
和len of 5
的要求的is.digit()
num1 = input('Enter a number with a length of 5: ')
while len(num1) != 5 and num1 != num1.isdigit():
num1 = input('Please enter a number with a length of 5: ')
num1 = int(num1)