Thursday, May 28, 2020

Functions

 Functions


The function has an optional return value; it's None by default. Just use the equal sign with a variable to its left to receive the return value from the function.


night_owl = "no"


def my_night():

     awake = "yes"
     return awake

night_owl = my_night()

print(night_owl)

# the result to the screen is

yes

If you don't know how many arguments are going to be passed in at any point in time on a function call, define the function for arbitrary arguments by just putting an asterisk to the left of the parameter. That will render the parameter to be of type tuple


def eating(*food):

  x = len(food)

  print(x)

  for i in food:

  print(i)

    

eating("cake", "steak")

# results in

2

cake

steak


You can define an empty tuple variable in advance and pass it in with some actual values.


people = tuple()


def house(*people):

    print(people)


house(("me", "her")) # notice double parentheses pairs - creating the tuple on the fly.


# output, the trailing commas indicates an arbitrary list ready to take more values if passed in.

# result is:

(('me', 'her'),)


Python will error check for duplicate parameters; it also traps for repeated keywords. 


first = "steak"

second = "cake"


def eating(*food):

  x = len(food)

  print(x)

  for i in food:

   print(i)

eating(first, first) # error 

eating(first, second) # valid

eating(second, first) # also valid

# output, note this prints the variable names and not their respective values

# In the "cake" and "steak" example before, the parameters of the function eating were explicit strings. Here they are the python variable names.

first

second


If you don't know how many key-value pairs are incoming as arguments at any point in time, you can define the key-value pairs as arbitrary. They'll be treated as a dictionary. If you don't know how many keyword value pairs in advance use a double asterisks to the left of the parameter name. 


first = "steak"

second = "cake"


def eating(**food):


  x = len(food)


  print(x)


  for i in food:

   print(i)

   print(food[i])

 # first and second are the actual index values!!


eating(first = "salad", first = "bread") # error


eating(first = "salad", second = "bread") # valid


# the result is

2

first

salad

second

bread

# because you need two asterisks for arbitrary key-value pairs


Python permits global variables to have the same name as a function parameter without error or cross-referencing.


first = "soup"

second = "tuna"


def eating(**food):

  x = len(food)

  print(x)

  for i in food:

   print(i)

# first can be both a global variable and a 

# function keyword parameter


eating(first = "carrot", next = second) # valid


However, you cannot mix global variables and key-value pairs in the syntax in a given function call. That is regardless of whether you use *, ** or exactly specify the parameters,


def eating(f,s):

def eating(*food):

def eating(**food):


eating(first = "carrot", second) # disallowed mixed syntax of strings with variables

 # error for each of the 3 cases.


In order to help with avoiding run-time errors you can specify a key value pair in the function definition. In fact, you can have multiple ones and they'll all be treated as defaults. They will be lined up left to right as you pass in actual values from the calling function. This is useful when the calling function has fewer arguments then the function's inherent parameters.


def eating(f = "onion", s = "garlic"):

    print("hard to eat " + f + " and " + s)


eating()


# results in 

hard to eat onion and garlic


compare the example above to:

eating("mustard")

# results in 

hard to eat mustard and garlic


The pass keyword is allowed in functions; if you happen to include the pass keyword and actually have some commands inside the function the pass keyword is ignored. 


You cannot utilize variables that are dependent upon recursive functions until the recursion is complete otherwise you will get a "local variable referenced before assignment error".


def recur(round):

  if round == 4: result = 99999

  if(round > 0):

    print(result)

    result = round + recur(round - 1)

  else:

    result = 0

  return result


# -----------  program really starts here first ----------

round = 4

print("math results")

recur(round)


# output

math results

99999

error: "local variable 'result' referenced before assignment error"


-----------------------------------


Now move the print command until AFTER all possible recursive iterations are complete.


def recur(round):

    if round == 4: result = 99999 # this is "fool you" as the variable: result does not equal 99999 very long as it replaced by the recursion

    if(round > 0):

        result = round + recur(round - 1)
   
        # calls itself based on def, the print command below # now waits until recursion is complete, i.e., round = 0

        print(result)

    else:

        result = 0

    return result # note that return has to line up with the first if

iterations = 4

print("math results")

last_return = recur(iterations)
print(last_return)


------------------------

# output

math results

1

3

6

10

10


Program logic goes like this and is easier to understand using the Cntl-F5 "nicer" debugger of Thonny and using F7 to "Step In" each line of code.


Here is a step-by-step run through of how recursive function calls work in this example:

1. In the main section round = 4 and recur() is called for the first time.

2. Inside the recur function, result is set to 99999 as round =4 only at this recursion level.

3. result  then relies on a recursive call to recur() with argument 3 to be added to the value of round at this level, which is 4.

4. Since at this inner level round is 3, it goes right on to the next update to the value of result by calling recur(2) to be added to the value of round at this level, which is 3.

5. result  then relies on a recursive call to recur with argument 2 to be added to the value of round at this level, which is 3.

6. Since at this inner level round is 2, it goes right on to the next update to the value of result by calling recur(1) to be added to the value of round at this level, which is 2.

7. result  then relies on a recursive call to recur() with argument 1 to be added to the value of round at this level, which is 2

8. Since at this inner level round is 1, it goes right on to the next update to the value of result by calling recur(0) to be added to the value of round at this level, which is 1.

9. At this deepest/innermost recursion level of the recur function, the if conditional fails since round = 0, and therefore the else clause kicks in so that result = 0. That value of result is then returned to the next instance upwards of the recur function. The print command is unreachable in the innermost function call (when round = 0).

10. Now back up to where the local variable for round is 1, the print command is reached for the first time, and prints the value of result which is 0 + 1 = 1.Then return result=1 to the next level up in function calls, when round =2.

11. In that function's local variable space round=2 and result gets that 2 added to the return value from the function nested underneath it with a value of 1. So result is 2+1 =3. That value of 3 is printed. and returned up the function recursion ladder again to where round = 3 locally there. round=3 + the return value of result =3 gives 6 and 6 is printed.

12. Finally, we backtrack all the way up to the top calling function of recur() by returning result=6 to its local variable space. Here round = 4. result is then 4 + 6 = 10 and gets printed. Remember, just like all the inner recur() function calls, this top level recur() still is obligated to return the value of result to the main program. So it does that with value 10, which gets printed once again to prove it.

END





Wednesday, May 27, 2020

For Loops

For loops


for loops in Python are more general in that the lower and upper bounds are not explicitly specified in the for line. The break and continue keywords are available with for loops, just like in while loops.



trees = ["oak", "maple", "pine", "cherry"]

for x in trees:

    print(x)


# the result is that all four tree names are printed, even though the command never said start at integer 1 and end at integer 4. Again, this reads more like it is English than code.


It turns out that the loop dummy variable in a for loop has global scope, meaning, you can use it and modify it even after the for loop is done.


trees = ["oak", "maple", "pine", "cherry"]

for x in trees:

    print(x)

print(x)


# will print cherry twice in a row.


If you look closely though and try to use a for loop variable in an unorthodox way, it is subject to a counting process and ordering (ranking) from left to right. It is almost like behind the scenes it is progressing through an integer count from the number 0 to the number of items in the list. There's a rank from left to right.


animals = ["cat""sheep""lion"]
for x in animals:
  if x"sheep":
    continue
  print(x)


# the loop above will skip printing lion because lion is to the

# right of sheep, and thus is considered of a higher rank, or

# greater than sheep!!


If you prefer to have start and stop numbers in the for loop, use the range keyword.


trees = ["oak", "maple", "pine", "cherry"]

for x in range(0,4):

    print(trees[x]) # here is an index, rather than the list element


# will print all the four trees


You can also use range with just one argument. In that case it assumes you want to start at 0.


range(3) covers 0 1 2


Also, a third argument to range tells it the step size between elements as the for loop iterates.


range(3,4,13) covers 3 7 11


In either case, remember that the right side argument is NOT included in the loop iteration:


range(0,7) covers 0 1 2 3 4 5 6


Much like in a while loop the else clause and the pass keywords are available.



Monday, May 25, 2020

While loops

While Loop

The format is: 

while x op y:
    commands
    iterating command on either x or y
    optional break to exit loop forcibly
    optional continue to go to next iteration at top of loop; it is essentially a go-to statement.
else:
    commands that execute only once, if at all.

where op is:       ==   !=  <  >  <=  >=  

What happens here?

r = 1
s = 1
while r < 10:
r +=1
if r == 7:
# 7 is not included in this running total
continue
if r == 8:
break
# since s is updated only AFTER the break and continue calls, the loop only iterates 5 times, not 6 times.

s += r
print(s)
else:
print(s)  # not reachable

gives

3
6
10
15
21

The else clause is unreachable because break forces an exit before the iterating loop variable can hit the condition for it to quit; a break bypasses any else clause. r only got as far as 7.

Now remove the if - break commands

r = 1
s = 1
while r < 10:
r +=1
if r == 7:
# 7 is not included running total
continue
s += r
print(s)
        y = 999
else:
print(s)  # prints s a second time as r hit 10 so the the while condition failed right then
        print(y)


gives:

3
6
10
15
21
29
38
48
48
999

notice that 7 was not included in the result.

Important: if you use the continue keyword, then make sure that your iterating command comes before continue in the loop. Otherwise an infinite loop will result.

Note that the else keyword is optional, but if used, is considered outside of the loop.  It means that break and continue are invalid in the else and will generate a run-time error. Unexpectedly though, any variable local to the loop will still be in scope in the else portion, as was shown above.



Saturday, May 23, 2020

if elif else


if elif and else


It's permitted to use an elif after another elif,  however, you cannot use any elif or else by itself in its own context. It has to be coupled with an if.

if x op y:
    print("true")
elif x op y:
    print("another")
else:
    print("done.")

where op is:    ==     !=     <     <=     >    >=

If you only have a single command associated with an if you can actually put them all on the same line, but you still need the colon : after the keyword if.

It looks something like command - if - else - command where you leave out the colons after the conditionals. Only leave out the colons when elif or else is used, i.e., a compound conditional one-liner so that it reads like English.

print("finished!") if x op y else print("not finished.")

You can also do a ternary command that would look like:

command - if - else - command - if - else - command.

The middle else-command-if triad behaves like an elif, however, you can not use the elif to shorten it because the interpreter will say "invalid syntax" error.

### note the data type is not considered; it just does the straight math
a = float(777)
b = int(777)

print("a smaller") if a < b else print("a is bigger than b") if a > b  else print("a actually equals b")

# result is
# a actually equals b
# Again we see the power of Python in that it reads just like reading the English language in a normal and natural fashion.

Be careful where you place the colons when using if, elif or else. 

Make sure you put the colons after the conditional part command on the if and elif line, and after the word else by itself.

Another thing is that if elif else must line up with the same indenting or otherwise you get an "unexpected indent" error from the interpreter. 

You can also link conditions by using the or and keywords. 

r = 88
k = 44
d = 88

if r > k and r == d:
    print("true")
else:
    print("false")


If you have a conditional that actually performs no action you need to put pass either on the same line or indented on the following line to prevent an error: "unexpected end-of-file while parsing". The elif and else can also have a pass and they all can also be on the same line (but keep the colons in this situation of using the pass keyword).


##########   this is valid code ################

r = 88
k = 44
d = 88

if r > k:
    pass # do nothing
elif d == k:
    pass # do nothing
else:
    pass # do nothing


# the display screen is blank without errors


##########   this is also valid code and is more compact ################
r = 88
k = 44
d = 88

if r > k: pass # do nothing
elif d == k: pass # do nothing
else: pass # do nothing


# the display screen is blank without errors












Friday, May 22, 2020

Dictionaries

Dictionaries

Dictionaries have key value pairs separated by commas inside a pair of {}.


rooms = {
  "living": "TV",
  "dining": "eat",
  "family": 4
}

In order to get the value associated with the key just call the dictionary with square braces with the key argument or you can use the get() method on the dictionary. Either way if the key is not found the returned value is None.

x = rooms["family"]
print(x)
# result is 4

print(rooms.get("family"))  # gives 4


If duplicate keys exist the most recent down the dictionary listing is recognized and the others are ignored.

rooms = {
  "living": "TV",
  "dining": "eat",
  "dining": 4
} # gives 4

If you want to loop through keys only,  have the loop's index dummy variable going as the argument call to the dictionary variable.

If you want to loop through the values only use the get() values method with no index inside the parentheses.

If you want to loop through both the keys and values use the item() method and 2 dummy loop variables.

When using 2 dummy loop variables with item() curious things happen if you leave off one of the dummy variables and or choose not to print one of the dummies.

case 1 - provide two dummy variables x,y to loop, print y, but do not print x

rooms = {
  "living": "TV",
  "dining": "eat",
  "family": 4
}
for x, y in rooms.items():
  print(y)

# results in values unquoted on a line by itself

TV
eat
4


case 2 - only one loop variable y and print it

rooms = {
  "living": "TV",
  "dining": "eat",
  "family": 4
}
for y in rooms.items():
  print(y)

# results in key-value tuples, one for each pair. so that a single loop variable forces key-value association to go unbroken.

('living', 'TV')
('dining', 'eat')
('family', '4')

Case 3 - provide two dummy variables x,y to loop, only print x, do not print y

rooms = {
  "living": "TV",
  "dining": "eat",
  "family": 4
}
for x, y in rooms.items():
  print(x)

# results in keys unquoted on a line by itself
living
dining
family


case 4, the normal case

rooms = {
  "living": "TV",
  "dining": "eat",
  "family": 4
}
for x, y in room.items():
  print(x, y)


# results in key-value pairs, each pair unquoted on a line by itself, not as tuples
living TV
dining eat
family 4

Remove an item:  pop(key) or the popitem() will get the rightmost one. You can also use del to remove either one key or the entire dictionary.

Dictionary assignments are by reference, therefore, to make a true copy only use the copy() method or the dictionary Constructor dict. Note when using a dictionary Constructor the keywords are not entered as string literals and an equal sign replaces colons. Another feature of the dict constructor is that it will fail if you have repeated keys. This is unlike constructing a dictionary by hand where duplicate keys are allowed.

rooms = dict(living= "TV", dining= "eat", family= 4)

and make second one as a copy:

newrooms = dict(rooms) # a true copy, with a different memory address

morerooms = newrooms

# NOT a true copy, because newrooms and morerooms share the same memory space. They # connected by reference; a change to one makes the other one change right away the same # way.

Dictionaries can be nested arbitrarily, in fact, you can create separate dictionaries and then place them in yet another dictionary by name. 


jones = {
  "dad" : {
    "name" : "John",
    "year" : 45
  },
  "mom" : {
    "name" : "Sarah",
    "year" : 43
  },
  "son" : {
    "name" : "Justin",
    "year" : 15
  } # notice no comma for the last one
}

or you can create each person as its own separate dictionary, and use those dictionary variables as elements in a new dictionary that holds them all.


dad = {
  "name" : "John",
  "year" : 45
}

mom = {
  "name" : "Sarah",
  "year" : 43
}

son = {
  "name" : "Justin",
  "year" : 15
}

jonesfamily = {
  "father" : dad,
  "mother" : mom,
  "child " : son 
# notice no comma for the last one
}




Thursday, May 21, 2020

Sets

Sets

Again remember that a set cannot be indexed and is denoted by a pair of {}. A set is also unordered so print calls will give a random listing out to your screen. You can only add items to a set, unless you want to subtract items AND you're using the set's remove() or discard() methods. Both of these subtracting methods take one argument.

add() will insert one item; use the update() method along with square braces as part of the argument to add two or more items. Interestingly, if you leave off the square braces in the update method call to a set, the individual characters of a text string are parsed and inserted randomly but not duplicated.

sports = {"baseball", "football", "basketball"}
sports.update(["hockey", "volleyball"])
print(sports)
print(type(sports))
sports.update("skiing", "hiking" )
print(sports)
print(type(sports))

# results in

{'hockey', 'baseball', 'football', 'basketball', 'volleyball'} # random insertion
<class 'set'>
{'i', 'hockey', 'g', 'n', 'h', 'baseball', 's', 'k', 'football', 'basketball', 'volleyball'}
<class 'set'>

# notice how the ing ending of each sport (skiing or hiking) is only shown by one of each of 'i' 'n' 'g'
# same for the k: ski vs hik
# This comes back to the idea that duplication is not allowed in sets, even single character strings

There's a subtle difference between the function of the remove and discard methods, even though they look at the surface to be doing the same thing by a different name.  If you want to try to remove("something") and "something" is not found in a set, the remove method gives you an error called a keyerror. Not the  discard method: if not found you get no error; it'll just returned back the set with no changes.

You cannot use a pair of square braces inside of a remove or discard method call to try and index because again the set is not indexable; you'll get an error that says 'unhashable type list'. The pop() method will return one value which is the subtracted item, however, it's what will be the right most value and it's a random selection so you don't know what you're going to get.

You can join two sets doing using the union() method, however this requires a third variable to accept the result of the joining sets 1 and 2. union will also exclude duplicates.

days = {"Sunday", "Tuesday", "Friday"}
other_days = {"Monday", "Wednesday", "Thursday", "Saturday"}

week = days.union(other_days)
# results in week containing all 7 days but in a random order. The random order however
# remains fixed until another method call is made.

days = {"Sunday", "Tuesday", "Friday"}
other_days = {"Monday", "Wednesday", "Thursday", "Saturday"}

# need new 3rd variable week
week = days.union(other_days)
print(week)
print(week)

# need new 3rd variable all_days
all_days = other_days.union(days)
print(all_days)
print(all_days)

# no 3rd variable with update()
days.update(other_days)
print(days)
print(days)

#######    RESULTS   ###############

{'Monday', 'Tuesday', 'Sunday', 'Saturday', 'Wednesday', 'Friday', 'Thursday'}
{'Monday', 'Tuesday', 'Sunday', 'Saturday', 'Wednesday', 'Friday', 'Thursday'}
{'Tuesday', 'Friday', 'Sunday', 'Saturday', 'Wednesday', 'Monday', 'Thursday'}
{'Tuesday', 'Friday', 'Sunday', 'Saturday', 'Wednesday', 'Monday', 'Thursday'}
{'Monday', 'Tuesday', 'Sunday', 'Saturday', 'Wednesday', 'Friday', 'Thursday'}
{'Monday', 'Tuesday', 'Sunday', 'Saturday', 'Wednesday', 'Friday', 'Thursday'}

#######    RESULTS   ###############


The set data type has a rich number of methods; consult the following link to get more details:





Tuples

Tuples


Tuples and lists can be converted one to the other by invoking their Constructors.


A single item tuple needs a trailing comma to properly set its type. But since you cannot change or add to it, what is the purpose? Actually there are workarounds. First you could fully delete the tuple from memory and start again. Second, you can convert it to a list, make additions or removals and changes, then convert it back to a tuple. Third you can join one tuple "as-is" to another tuple, which is essentially a type of rough add command.

sports = ("baseball", "football", "basketball")

one_sport = ("baseball",) # a tuple
another_sport = ("football") # a string variable
print(type(one_sport)) #
<class: 'tuple'>
print(type(another_sport))  #
<class: 'str'>
print(type(sports)) # <class: 'tuple'>


option 1 to change a tuple


sports = ("baseball", "football", "basketball")
del sports
sports = tuple(("football", "tennis")) # use constructor to create a tuple on the fly


option 2 to change a tuple


sports = ("baseball", "football", "basketball")
sports = list(sports)
sports.insert(0, "hockey")
sports = tuple(sports)
print(sports)
print(type(sports))


# results in 'hockey', 'baseball', 'football', 'basketball'
# <class: 'tuple'>


option 3 to change a tuple


more_sports = ("handball", "bowling")


all_sports = sports + more_sports
# a larger tuple but the additional elements are still
# inserted randomly.



The tuple data type only has two methods: count() and index(), each of which needs only one argument. index() will return the position of the found value in the tuple; if there are multiple matches to the value (duplicates) it will only return the leftmost match.

Compared to the other 3 collection type variables, a tuple is the most restricted in what can be done to it.


Wednesday, May 20, 2020

Lists



Lists


There are 4 data types that represent collections of elements.


They are list, denoted by a pair of square braces []; tuple, which is denoted by a pair of parentheses (); set, which is denoted by a pair of {} with elements separated by commas; dictionary, which is represented by a set of {} with key-value pairs separated by a :.


   collection data type     Ordered   Changeable  IndexedDuplication allowed      
 list [,] YesYes Yes Yes
 tuple (,) Yes No Yes Yes
 set {,} No only subtract and add  No No
 dictionary {:} Yes Yes Yes No


The efficiency and security of your code can depend on the choice of your collection.

It turns out that the members of a list can have individual data member types mixed of, for example, a Boolean, string, or integers all in the same list ... it's valid.

mixedlist = [10, "apple", False]  # valid

Other special uses of the colon in list access
These behave in the same way as for strings.

mixedlist[0]   ===> 10
mixedlist[:2]  ===> 10 "apple"
mixedlist[:]    ===> 10, "apple", False
mixedlist[2:]  ===> "apple" False
mixedlist[-2:-1] ===> "apple"
mixedlist[-1] ===> False


Collections have a variety of methods available to them.


The insert() method will put in a string at a given index in the list. The insert method takes two arguments. If the index is -1, the new element will be inserted second from the right in the list.

# put "tree" at the left most position in mixedlist

mixedlist.insert(0, "tree") 
# results in mixedlist = ["tree", 10, "apple", False]

mixedlist.insert(-1, "tree") 
# results in mixedlist = [10, "apple", "tree", False]


The remove() method will take away an element from a list. If a list has duplicates it would only take away one element: the leftmost of those elements in the list.


mixedlist = [10, "apple", 10, "tree", False]

mixedlist.remove(10) # specify by item content, not index.
# results in mixedlist = ["apple",  10, "tree", False]


pop() will also remove an element from the list at a specified index. If you call pop without any index it removes the rightmost element only.

mixedlist = ["apple",  10, "tree", False]
mixedlist.pop(2) # indexing starts at 0
# results in mixedlist = ["apple",  10, False]

veggies = ["carrot", "lettuce", "radish"]
veggies.pop()
# results in veggies = ["carrot", "lettuce"]


del is a keyword, not a method available in Python but it does the same thing as the list pop method. In fact, if you del on a list without giving any index it will remove that variable entirely from memory.

cars = ["sedan", "SUV", "minivan"]
del cars
print(cars)
# results in an error: name 'cars' is not defined.

The clear() method will empty a list as opposed to fully eliminating it like del would; the list still exists although it'll be empty. 

cars = ["sedan", "SUV", "minivan"]
cars.clear() # takes no arguments
print(cars)
# no error
# results in []


Although one can make a true copy of a variable which represents a single element, for example,

 x = 10

(you can make a memory copy of x by saying)

 y = x. 

x and y are treated differently with different locations in memory.

That's not the same with the lists.

 w = ["a", "b"]

 followed by

 v = w

 does not create a new true copy; it instead creates a reference to w such that any changes to w will also be made right way in v because they share the same location in memory.

In order to create two separate list variables use the copy() method; you can also use the python list built-in constructor function. The python list function can also be considered as a constructor where you can use a double (( )) to create a list on the fly without actually making an explicit assignment using an equal sign.

states = ["Alabama", "Virginia", "Florida"]
doublestates = states.copy()
test = states is doublestates
print(test)
# returns False since the two are separate variables in memory.

# notice no use of [] but this is still a Python list
morestates = list(("Alabama", "Virginia", "Florida", "Maryland"))


There are three ways to join lists.

You can use a plus sign +, you can loop over the elements using for in or you can use the extend() method.


option 1
groceries = cars + veggies

# result is 
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish']


option 2 # x is an ordered member of the veggies list
for x in veggies:
    cars.append(x)
    print(cars)

# result is
['sedan', 'SUV', 'minivan', 'carrot']
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce']
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish']


option 3
cars = ["sedan", "SUV", "minivan"]
cars.extend(veggies)
print(cars)

# result is:
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish']

the next option is not the same as the other three

option 4
cars = ["sedan", "SUV", "minivan"]
for x in veggies:
    cars.extend(x)
    print(cars)

# result 
['sedan', 'SUV', 'minivan', 'carrot', 'lettuce', 'radish', 'c', 'a', 'r', 'r', 'o', 't', 'l', 'e', 't', 't', 'u', 'c', 'e', 'r', 'a', 'd', 'i', 's', 'h']

The extend() method sees each character as a string of length 1 and operates accordingly.


Notice that in option 1 you must create a new variable groceries.

If you do not want to create a third variable but still want to use the +, use it as compound assignment operator

cars +=veggies
# cars gets appended by veggies
# the veggies variable does not change in this example


Check for existence of a value in a list:

veggies = ["carrot", "lettuce", "radish"]
if ('carrot') in veggies:
    print("yes")

# result is 
yes