Home > Net >  Function that changes all lower case letters to uppercase
Function that changes all lower case letters to uppercase

Time:08-24

#!/usr/bin/python3
def uppercase(str):
    new = ''
    for i in str:
        if (ord(i) > 96 and ord(i) < 123):
            new = new   chr(ord(i) - 32)
print("{}".format(new))

This is my code, but it does not work. I am new to python, and why is my code not working?

CodePudding user response:

You can use the built-in method upper() Try this:

foo = "hello, world!"
print(foo.upper())

This will uppercase the letters for you (you can use it directly on strings like this):

print("Hello, world!".upper())

If you want to make it by yourself (which is fine to learn) you should use a return statement

def uppercase(msg):
    new = ''
    for i in msg:
        if (ord(i) > 96 and ord(i) < 123):
            new = new   chr(ord(i) - 32)
    return new

print("{}".format(uppercase("Hello, world!")))

CodePudding user response:

You need to change your code by

#!/usr/bin/python3
def uppercase(str):
    new = ''
    for i in str:
        if (ord(i) > 96 and ord(i) < 123):
            new = new   chr(ord(i) - 32)
    return new

print("{}".format(uppercase('SomeThing')))

or use the function upper()

message = 'python is fun'

# convert message to uppercase
print(message.upper())

CodePudding user response:

The problem with your code is that (a) you need to call your function uppercase, like this:

print(uppercase('Hello, world!"))

And second, you only copy characters that need to be uppercased (i.e. the lower case letters). Any other character should be copied unchanged.

  • Related