[Tutor] Python

Alan Gauld alan.gauld at yahoo.co.uk
Thu Oct 21 07:10:03 EDT 2021


On 20/10/2021 23:35, Vanshika Sadhwani wrote:

> So I did do most of the coding for the assignment, however 
> whenever I execute it, it doesn’t give me the output I need. 

It is always good to tell us what it does produce and what
you expected. However...


> This is for code_check:
> def basic_code(a):
>     a = list(map(int, a.strip()))
>     total = sum(a)
>     valid_code = total % 10
>     check_digit = a[+1]

You don't need the plus sign in the index.
Also are you sure it is 1 you want to use?
That will give you the second digit in a...

>     if valid_code == check_digit:
>         return True
>     else:
>         return False

You could replace that if/else with

return valid_code == check_digit

> def positional_code(a):
>     total = 0
>     a = list(map(int, a.strip()))
>     for i in range(0, len(a)):
>         total += a[i]

Why not just use sum() as you did above?

Also in Python we try not to use index based loops.
It would be better to just write:

for n in a:
    total += n

And total = sum(a)

is better still.


>     valid_code = total % 10
>     check_digit = a[+1]
>     if valid_code == check_digit:
>         return True
>     else:
>         return False

This looks to be doing the same as the previous function?

> def UPC(a):
>     total = 0
>     a = list(map(int, a.strip()))
>     for i in range(0, len(a)):
>         if i % 2 == 1:
>             total += 3 * a[i]
>     else:
>         total += a[i]
>     valid_code = total % 10
>     if valid_code == 0:
>         valid_code = 10 - valid_code

You don;t need the subtraction since you've already
established that valid_code is zero.

>     check_digit = a[+1]
>     if valid_code == check_digit:
>         return True
>     else:
>         return False

> This is for Assign2:
> from code_check import*
> 
> codes = []
> valid_basic = []
> valid_positional = []
> valid_UPC = []
> none = []
> 
> while True:
>     code = input("Please enter code (digits only) (enter 0 to quit): ")
>     if code == '0':
>         break
>     codes.append(code)

I suspect the while loop should end here?

>     for code in codes:
>         if basic_code(code) is True:
>             valid_basic.append(code)
>         elif positional_code(code) is True:
>             valid_positional.append(code)
>         elif UPC(code) is True:
>             valid_UPC.append(code)
>         else:
>             none.append(code)
> 
> print("Summary")
> print("Basic :" + ''.join(valid_basic))
> print("Position :" + ''.join(valid_positional))
> print("UPC :" + ''.join(valid_UPC))
> print("None :" + ''.join(none))
> This is what I am getting when I run the code

Nothing here...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list