简体   繁体   中英

Python list reading integers

I am trying to create a simple script that should count how many integers or strings there are in a list. At first the list is empty, then the user is asked to fill it with numbers or strings, this is the script:

lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters
while True:
   x = input("digit an int or string, 'stop' returns values: ")
   if(x=='stop'):
      False
      break

   i = lis.append(x)
   if isinstance(i, int): # check whether is integer
       num += 1
   else:
       lett += 1    

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

The program works, but the problem comes in the end, because when I print the list, it sees only strings, even numbers are returned as '10', for example.

I need the interpreter to automatically recognise integers.

d = l = 0
res = []
while True:
    s = input("input string or digit\n")
    if s == 'exit':
        break

    ## this is one way, might be faster to do it using isdigit suggested in the comment
    try:            
        temp = int(s)
        d += 1
    except ValueError:
        l += 1
    res.append(s)

print(d)
print(l)
print(res)

You are checking if the return value of list.append is an integer, which is not. Therefore, it counts it as a string.

lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters
while True:
   x = input("digit an int or string, 'stop' returns values: ")
   lis.append(x)
   if(x=='stop'):
      break

for items in lis:
    if items.isdigit(): # check whether is integer
        num += 1
    else:
        lett += 1   

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

here is my solution that works on my Python IDLE version 3.6.0 (Please reply if it doesn't work for you):

lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters

while True:
    try:
        x = input("digit an int or string, 'stop' returns values: ")
        i = lis.append(x)
        if(x=='stop'):
            False
            break   
    except ValueError:
        print("Not an integer!")
        continue
    else:
        num += 1

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

here's my code

while True:
    l,num,lett = [],0,0
    while True:
        x = input('digit an int or string, "stop" returns values: ').lower().strip()
        try:
            x = int(x)
        except:
            pass
        if x == ('stop'):
            break
        l.append(x)

    for element in l:
        if isinstance(element, int):
            num += 1
        else:
            lett += 1

    print (l)
    print ("there are " + str(num) + " numbers")
    print ("there are " + str(lett) + " strings")
    l,num,lett = [],0,0     #reset to go again

You can use isdigit and change your code to this:

lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters
while True:
    x = input("digit an int or string, 'stop' returns values: ")
    if(x=='stop'):
      False
      break
    if x.isdigit(): # check whether is integer
        lis.append(int(x))
        num += 1
    else:
        lis.append(x)
        lett += 1   

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

Also, you can fix your code with this (it need an indented and move it into your main while ):

if isinstance(int(x), int): # check whether is integer
    num += 1
    lis.append(int(x))
else:
    lett += 1
    lis.append(x)
lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters
while True:
  x = input("digit an int or string, 'stop' returns values: ")
  if(x=='stop'):
    break
  if x.isdigit():
    lis.append(int(x))
    num += 1
  elif x.isalpha(): 
    lis.append(x)
    lett += 1

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

Result

digit an int or string, 'stop' returns values:  1
digit an int or string, 'stop' returns values:  2
digit an int or string, 'stop' returns values:  3
digit an int or string, 'stop' returns values:  a
digit an int or string, 'stop' returns values:  b
digit an int or string, 'stop' returns values:  c
digit an int or string, 'stop' returns values:  stop
[1, 2, 3, 'a', 'b', 'c']
there are 3 numbers
there are 3 strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM