Welcome to the first post that summarizes the first few posts. This post will show how loops, if conditions, variables, arrays, and strings, integers, and floats are all used together in a program. A program is basically a set of code that carries out a certain task, whether the task is very simple or very complex.
This program is going to search an array of numbers for a certain number, val.
First we have to define val:
val = 5
Next, we create the array:
nums = [1,2,3,4,5,6,7,9,8,2,3,13,25,62]
Now, we are going to create a variable, found, with a True or False value, which will keep track of whether or not we found val in nums.
found = False
Not the value of found is false. This is because we have no found val yet. Next we will use a for loop to go through nums and check each element to see if it is equal to val. To check each element, we will use an if condition.
for i in nums:
if i == val:
found = True
break
The for loop gets the elements of the array one at a time. The if condition checks whether the element is equal to val. The code inside the if condition sets found as True, because if i is equal to val, then we have found val in nums. The next line inside the if condition says, 'break.' This exits the for loop, because we have found the val in nums.
What if val never occurred in nums? Then the for loop would end without val being found. We need to make sure we know whether val was found of not, so lets add something to out code. Lets add a small if-else that prints, "Found," if val was found, and "Not found," if val was not found.
if found == True:
print("Found!")
else:
print("Not Found!")
Simple. This if condition will go after the for loop. First it checks if found is True. If Found is true, then it means val was found, so it prints, "Found!". Else, it prints, "Not Found!"
This ends the first python program blog. Thank you for reading and please leave any comments or questions in the comments section!
Comments
Post a Comment