I am trying to create a set of the letters from the alphabet and I'm not sure why the code is not working. Python gives me an error saying that the "global name 'a' is not defined." Any ideas? Thank you in advance.
s = set()
s = {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}
Use the ord() Function to Convert Letters to Numbers in Python. The ord() function in Python is utilized to return the Unicode , or in this case, the ASCII value of a given letter of the alphabet. We will apply the ord() function to the letters and subtract 96 to get the accurate ASCII value.
a
, b
, ... on their own are not strings, they are names. Python strings must be enclosed in single quotes ('a'
), double quotes ("a"
) or triple quotes ("""a"""
or '''a'''
). So, the correct version of your code would be:
# s = set() - this is useless, the next line is already creating a set
s = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}
Having said that, a much cleaner way of doing this is to use Python's built-in set and string.ascii_lowercase like so:
import string
s = set(string.ascii_lowercase)
try this
import string
s = set(string.ascii_lowercase)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With