In: Computer Science
0) Explain (with a non-trivial example that uses start, stop, and increment) the similarity between the range() function and slicing.
1) Convert:
for i in range(2, 12, 3): print(i)
into a while loop.
2) Explain the circumstances where a for loop makes more sense versus when a while loop makes more sense.
3) What is your favorite movie? (There should be one easy question, right?)
4) How do you create an empty tuple?
5) What is the difference between the string methods find and index?
Question 0: similarity between range() and slicing()
Solution:
range() and slice() both takes three arguments.
for ex: range(0,5,1) and slice(0,5,1)
0 -> start index
5 -> end index
1 -> increment
range() and slice() both works as (end index - 1)
if end index is 5, but it takes till index 4 and eliminates index 5.
Question 1: Convert for loop to while
for i in range(2, 12, 3): print(i)
Solution:
i = 2 // Start
while (i<12): // if i greater than 12, goes inside loop
i += 3 // Increment
Output:
2
5
8
11
Question 2: when to use for and while loop
solution:
For loop:
1) use when you already know the number of execution
2) It's faster than while loop
While Loop:
1) Use when number of execution not known exactly
2) Use when asking for user input
Question 4: Create Empty Tuple
Solution:
Tuple - Immutable(once created, we can't modify data later) and ordered
You can create Empty typle object by giving no elements in parentheses() or you can also create using python built-in function without giving any arguments.
Example,
1) tup_var =()
print (tup_var)
output -> ()
2) tup_var = tuple()
print (tup_var)
output -> ()
Question 5: difference between string method find() and index()
solution:
index() - find 1st occurance of specified value, if specified value not found, raise exception
For ex:
str = "hello, world"
str_find = str.index("world")
print(str_find)
output -> 7 ( H E L L O ,(space) W O R L D)
0 1 2 3 4 5 6 7
here, index 5 is for comma and index 6 is for white space
if the specifed value ( world) is not found, it raise exception.
Find() - works same as index, the only difference is, if the specified word not found in string
return -1.
1) for ex:
str = "hello, world"
str_find = str.find("world")
print(str_find)
output -> 7 ( H E L L O ,(space) W O R L D)
0 1 2 3 4 5 6 7
2) ex:
str = "hello, world"
str_find = str.find("hi")
print(str_find)
output -> -1 (because, hi not found in string)