简体   繁体   中英

Function that changes all lower case letters to uppercase

#!/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?

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!")))

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())

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 (ie the lower case letters). Any other character should be copied unchanged.

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