Python Forum

Full Version: Variable is not defined error when trying to use my custom function code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi so I recently am transitioning from Snap! to python and im trying to recreate something I did in snap but I am having some problems.

# CONTAINS LETTER BLOCK
def contains_letter(string1,letter):
    for i in len(string1):
        if i==letter:
            print(True)
        else:
            print(False)        

contains_letter(hello,h)
When I put hello and h in it just says undefined variable in the problems section. Also im pretty sure some of that code might not work as well as I was trying to find something that would work with what i want it to do.
Please use bbtags when posting code.

hello is a string and needs to be 'hello' as well as the letter 'h'

Example:
def contains_letter(string, letter):
    for letters in string:
        if letters == letter:
            return True
    return False

print(contains_letter('hello', 'h'))
output
Output:
True
oh okay sorry for not using the bb text I was trying to but I couldn't find the shortcut on the text editor thingy. Also thank you I didn't know that the input had to be in quotations for string inputs. I will also be using the return function lol I didnt know that was a thing in here.
Input does not need to be in quotes, str literals need to be in quotes.

'hello' - makes a str
"hello" - makes a str
hello = "hello" - makes a variable named hello and assignes it to reference a str.

There is no reason to write your function in Python. This code
print("h" in "hello")
Checks if the str "hello" contains the str "h" and prints True if it does. The "in" operator performs the test.
(Nov-23-2023, 08:40 AM)menator01 Wrote: [ -> ]Example:
def contains_letter(string, letter):
    for letters in string:
        if letters == letter:
            return True
    return False

print(contains_letter('hello', 'h'))

You can simply that to:

def contains_letter(string, letter):
    return bool(letter in string)