Python Forum
Variable is not defined error when trying to use my custom function code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Variable is not defined error when trying to use my custom function code (/thread-41181.html)



Variable is not defined error when trying to use my custom function code - fnafgamer239 - Nov-23-2023

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.


RE: Variable is not defined error when trying to use my custom function code - menator01 - Nov-23-2023

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



RE: Variable is not defined error when trying to use my custom function code - fnafgamer239 - Nov-23-2023

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.


RE: Variable is not defined error when trying to use my custom function code - deanhystad - Nov-23-2023

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.


RE: Variable is not defined error when trying to use my custom function code - rob101 - Nov-23-2023

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