-2

I have a while loop which I would like to keep prompting a user to enter a number until the user types "exit". Unfortunately when the user enters anything, they aren't prompted to enter another number, and the procedure doesn't end. I'm using Pycharm as my IDE. Here is my code:

a = []
num = ""
newa = []
def makelist():
    num = input("Type a number! Or if you want to exit, type 'exit' ")
    while num != "exit":
        if int(num):
            a.append(num)
        num
def firstandlast():
    newa.append(a[0]) and newa.append([len(a)])
    print("Here are the first and last numbers you typed:")
    print(newa)
makelist()
firstandlast()
xxxRxxx
  • 357
  • 2
  • 7
  • 17
  • 3
    You never ask for `input()` again after the first time. – xdurch0 Jul 14 '19 at 12:14
  • 1
    `newa.append(a[0]) and newa.append([len(a)])` will only append `a[0]`. `append` returns `None` and `and` is short-circuited so whatever is after `and` is not even evaluated. Also, `a[-1]` is the last element in `a`, not `[len(a)]`. – DeepSpace Jul 14 '19 at 12:15
  • What is the `num` doing on the last line of `makelist`? – blackbrandt Jul 14 '19 at 12:15

3 Answers3

1

Modify the makelist function to:

def makelist():
    num = input("Type a number! Or if you want to exit, type 'exit' ")
    while num != "exit":
        if int(num):
            a.append(num)
        num = input("Type a number! Or if you want to exit, type 'exit' ")      
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

You will need to assign num again in the while loop to be equal to the input again:

while num != "exit":
    num = input("Type a number! Or if you want to exit, type 'exit' ")
Dakota Maker
  • 633
  • 4
  • 24
1

First of all it's better to use isdigit() as a function to determine whether the input is number or not. So this part would be like below:

if num.isdigit():
     a.append(num)

And to get new input in each level of loop you can add an additional input() into your loop:

while num != "exit":
     if num.isdigit():
          a.append(num)
     num = input()

And you were adding your first and last number in one line using and. I edited it into two line which works fine right now.And by the way you can achieve the last element of an array using -1. So a[-1] will give you the last item. The firstandlast function would be like this:

def firstandlast():
    newa.append(a[0])
    newa.append(a[-1])
Alireza HI
  • 1,873
  • 1
  • 12
  • 20