中断循环以重新开始并添加更多循环

时间:2018-10-05 08:27:14

标签: python

第一篇文章是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()

2 个答案:

答案 0 :(得分:1)

首先,您应该在循环之外定义b_median和其他函数。

您的循环最像这样工作,通过设置max_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()

While x循环

您可能会注意到,我们将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)(存在其他方式)。

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

id(list1) == id(list2)  # False, that means the two lists are different

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

list2[0] = "I love chocolate"

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

答案 1 :(得分:1)

您可以使用循环来完成所有您想做的事情。

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)

我为您提供一些建议:

  1. 尝试从一开始就编写函数-看起来很清楚。

  2. 尝试使用google并使用所有python功能。

  3. 更清楚地给变量命名。

祝您一切顺利。