Python 断开循环以返回开始并添加更多循环

Python 断开循环以返回开始并添加更多循环,python,Python,第一篇文章在这里发表,对Python来说相当陌生;我已经使用了搜索功能,并尝试了一些建议,但仍在努力。 我正在制作一个小程序,它接受一组数字并对这些数字执行简单的统计函数,而不使用任何库或统计软件包。 要求用户输入值,然后询问他们希望应用于集合的函数;当用户选择4时,我想返回到开头。 下面的代码-已略去部分供用户选择“4”。 我还希望用户有进一步的选择,并添加另一组数字,但也无法做到这一点 我知道这可能与缩进或我的草率代码有关,但我是个初学者 谢谢 # Library's used # none

第一篇文章在这里发表,对Python来说相当陌生;我已经使用了搜索功能,并尝试了一些建议,但仍在努力。 我正在制作一个小程序,它接受一组数字并对这些数字执行简单的统计函数,而不使用任何库或统计软件包。 要求用户输入值,然后询问他们希望应用于集合的函数;当用户选择4时,我想返回到开头。 下面的代码-已略去部分供用户选择“4”。 我还希望用户有进一步的选择,并添加另一组数字,但也无法做到这一点

我知道这可能与缩进或我的草率代码有关,但我是个初学者

谢谢

# Library's used
# none

# Statement to make function work
x=True

# Initial print statements
print( "Please enter a list of numbers...")
print("Enter these individually,hitting enter after each occasion...")

# Main function
while x==True:



  try:
# User input
# This wouldn't be suitable for large lists
# Need something more concise 
     f = int(input('Enter a value: '))
     g = int(input('Enter a value: '))
     h = int(input('Enter a value: '))
     i = int(input('Enter a value: '))
     j = int(input('Enter a value: '))
     k = int(input('Enter a value: '))
     l = int(input('Enter a value: '))
     m = int(input('Enter a value: '))
     n = int(input('Enter a value: '))
     o = int(input('Enter a value: ')) 
     # Values stored here in list
     list1 =[f, g, h, i, j, k, l, m, n, o]
     list2 =[f, g, h, i, j, k, l, m, n, o]   
     x=True
     # If input produces error (!=int)
  except (ValueError,TypeError,IndexError):
     print ("That was not a valid number.  Try again...")
  else:
     # Variables
     length_list1=len(list1)  # Length     
     list3= [int(i) for i in list1] # Convert list elements to int
     b_sort=sorted(list3) # Sorted ascending
     b_select=((length_list1+1)/2) # Select the middle value
     val_1=b_select-0.5 # Subtracts -0.5 from b_select
     val_2=b_select+0.5 # Add's 0.5 to b_select
     b_median_float=(list3[int(val_1)]+list3[int(val_2)])/2 # Selects values either side of middle value
     mode=max(set(list3),key=list3.count) # Establishes a count of each int in list, largest count stored in variable.
     x=True

    # When the values satisfy the condition
  if (list1==list2):
    print("\nAll values declared")
    print ("You entered",length_list1,"values","\n",list1)
    print("Select a function for your list of numbers\n1.Mean\n2.Median\n3.Mode\n4.New set of numbers\n5.Exit")
    # User prompted for further input

  choice = input('Enter a value (1 to 5): ')


  def b_median():
      # If number of values are odd
      if type(b_select)==float:
        return b_median_float 
        print(b_median_float)
        # If even
      else:
        return print(b_select)
# Variables from calculations
  a=(sum(list3)/length_list1)
  b= b_median()
  c=mode
# Responses to user input
  if (choice=='1'):
        print("The mean is:",a)
        choice=input('Enter a value (1 to 5): ') 
  if (choice== '2'):
        print("The median is:",b)
        choice=input('Enter a value (1 to 5): ')
  if (choice== '3'):
        print("The mode is:",c)
        choice=input('Enter a value (1 to 5): ')
  if (choice=='5'):
      sys.exit()

首先,您应该定义
b_中值
和循环之外的其他函数

循环的工作方式与此类似,通过设置
max\u size
变量,您可以请求任意数量的数字

max_size = 100  # can be as large as you like

# Main function
while x:
    try:
        list1 = []
        for i in range(max_size):
            list1.append(int(input('Enter a value: ')))
        list2 = list(list1)  # copy list1 to list2; see further down why it's super important
    except TypeError:
        # If input produces error (!=int)
        print("That was not a valid number.  Try again...")

    ................

    choice = ''
    while choice != '4':
        choice = input('Enter a value (1 to 5): ')
        if (choice == '1'):
            print("The mean is:", a)
        elif (choice == '2'):
            print("The median is:", b)
        elif (choice == '3'):
            print("The mode is:", c)
        elif (choice == '5'):
            sys.exit()
whilex循环 您可以注意到,我们将
while x==True
更改为
while x
,这是因为,while循环将在表达式为True时循环,这意味着您可以为无限循环编写
while True
。这里我们保留了
x
变量,但您可以删除它,直接使用
True

名单副本 我们将在这里为您提供一个列表复制在python中如何工作的快速示例,因为您(每个人)也会落入陷阱

list1 = [1, 2, 3, 4]
list2 = list1  # we made a "copy" of list1 there

print(list1)  # [1, 2, 3, 4]
print(list2)  # [1, 2, 3, 4]

# seems good to me so far
# Now let's update the list2 a bit

list2[0] = "I love chocolate"

print(list2)  # ['I love chocolate', 2, 3, 4]
print(list1)  # ['I love chocolate', 2, 3, 4]

# whyyyyyy I just changed the value in list2, not in list1 ?!
这是因为在python中,执行
list2=list1
将使list2引用与list1相同的内存位置,它将克隆list1

id(list1) == id(list2)  # True

# By the way, the id() function will give you the "social security number"
# of whatever you ask for. It should be unique for each element, and when
# it's not, that means those two elements are in fact one.

# That means here, that list2 is like the second name of list1, that's
# why changing one will change both.
为了避免这种情况,我们使用语法
list2=list(list1)
(还有其他一些方法)


你可以用循环做你想做的一切

def median(numbers):
    if len(numbers) % 2 == 1:
        return sorted(numbers)[int(len(numbers)/2)]
    else:
        half = int(len(numbers)/2)
        return sum(sorted(numbers)[half-1: half+1])/2
def mode(numbers):
    counts = {numbers.count(i): i for i in numbers}
    return counts[max(counts.keys())]
def read():
    print("Please, enter N: a length of your list.")
    number_count = int(input())
    print("Please, enter all of your numbers")
    numbers = list()
    for i in range(number_count):
        numbers.append(int(input()))
    return number_count, numbers


while True:
    number_count, numbers = read()
    while True:
        print("Please, select an option:\n1 - Median\n2 - Mode\n3 - Exit\n4 - \
New numbers\n5 - Add numbers to existing list\n6 - Print your list")
        option = int(input())
        if option == 1:
            print(median(numbers))
        if option == 2:
            print(mode(numbers))
        if option == 3:
            sys.exit()
        if option == 4:
            break
        if option == 5:
            new_number_count, new_numbers = read()
            number_count += new_number_count
            numbers = numbers + new_numbers
        if option == 6:
            print(numbers)
我有一些建议给你:

  • 试着在开始的时候写下你的函数——看起来很清楚

  • 尝试谷歌搜索并使用所有python功能

  • 为变量提供更清晰的名称


  • 祝您好运。

    在python中,您可能的副本应始终使用4个空格缩进。到底是什么问题?@Georgy不是同一个问题。感谢您的建议,这真的很有帮助-尤其是列表建议!感谢您的帮助,找到模式的部分-我可以看到它工作了,但是您能解释一下函数背后的逻辑吗?@KyleDavis我制作了一个
    dict
    ,其中每个键都是数组
    中元素的计数
    I
    ,值是元素
    I
    。如果在dict中数组[1,1,1]可以重复,它看起来像{3:1,3:1,3:1},但在dict中不能重复,所以我们只有{3:1},其中3是计数,1是数字。然后,我们从键(从计数)中获取一个最大值,并返回该值。我认为它不是最优的,但它很短=)如果你愿意,你可以更有效地搜索
    模式
    @KyleDavis的代码,正如你所看到的,如果我们有两个(或更多)相同计数的数字,我们将取最后一个。因为在每个步骤中,我们都用相同的键重写值。
    def median(numbers):
        if len(numbers) % 2 == 1:
            return sorted(numbers)[int(len(numbers)/2)]
        else:
            half = int(len(numbers)/2)
            return sum(sorted(numbers)[half-1: half+1])/2
    def mode(numbers):
        counts = {numbers.count(i): i for i in numbers}
        return counts[max(counts.keys())]
    def read():
        print("Please, enter N: a length of your list.")
        number_count = int(input())
        print("Please, enter all of your numbers")
        numbers = list()
        for i in range(number_count):
            numbers.append(int(input()))
        return number_count, numbers
    
    
    while True:
        number_count, numbers = read()
        while True:
            print("Please, select an option:\n1 - Median\n2 - Mode\n3 - Exit\n4 - \
    New numbers\n5 - Add numbers to existing list\n6 - Print your list")
            option = int(input())
            if option == 1:
                print(median(numbers))
            if option == 2:
                print(mode(numbers))
            if option == 3:
                sys.exit()
            if option == 4:
                break
            if option == 5:
                new_number_count, new_numbers = read()
                number_count += new_number_count
                numbers = numbers + new_numbers
            if option == 6:
                print(numbers)