List, Dictionaries and Iteration
This is my list, dictionaries and iteration Hack
QuizDb = []
# Dhruva's Info
QuizDb.append({
"Firstname": "Nikhil",
"Lastname": "Chakravarthula",
"Age": "15",
"Height": "74 inches"
})
# Tejas Info
QuizDb.append({
"Firstname": "Tejas",
"Lastname": "Chakravarthula",
"Age": "11",
"Weight": "130 pounds"
})
In this I created a function which asks questions like a test using dictionaries. This will take each dictionary and convert it into a list of questions.
# This cell defines a function that I will use to execute the quiz
def ask_questions(QDb):
correct_cnt = 0
total_cnt = 0
for dict_item in QDb:
person_name = dict_item['Firstname']
for key in dict_item:
if key == 'Firstname':
continue
else:
question = "what is " + person_name + "'s " + key
correct_answer = dict_item[key]
user_answer = input(question)
if user_answer == "exit":
break
total_cnt += 1
if correct_answer == user_answer:
correct_cnt += 1
print("Your answer is correct")
else:
print("Your answer is incorrect")
if user_answer == "exit":
print("Bye!")
break
print('you answered: ', correct_cnt, '/', total_cnt, "Correct")
ask_questions(QuizDb)
# This cell has a while loop
def list_num_inclusive(x,y):
x = int(x)
y = int(y)
if x >= y:
print("ERROR!!! Starting value must be less than ending value. Please try again.")
else:
print("Here are your numbers!!!")
while x <= y:
print(x)
x += 1
starting_value = input("What is the starting value? (Inclusive")
ending_value = input("What is the ending value? (Inclusive")
list_num_inclusive(starting_value, ending_value)
This function below uses a recursive loop and this loop can repeat itself untill a specific condition is met and in this case takes the dictionary value and increments itself while adding to a sum. It is exactly like a factorial
def example_recursive(x):
x = int(x)
if x < 10:
x += 1
x=example_recursive(x)
else:
print("End of recursive loop")
return x
def example_recursive_dict(dict_obj, NN):
#dict_obj['val'] = int(dict_obj['val'])
print('inside example_recursive_dict, val is: ',dict_obj['val'])
if dict_obj['val'] < NN:
dict_obj['val'] += 1
dict_obj['sum'] += dict_obj['val']
#print('inside if')
example_recursive_dict(dict_obj, NN)
else:
print("End of recursive loop")
#recursive_var = input("What number should we start with?")
#recursive_var=example_recursive(recursive_var)
#print(recursive_var)
def example_by_reference(dict_obj):
dict_obj['val'] += 1
dict_test = {'val': 2, 'sum': 0}
print(dict_test['val'])
example_by_reference(dict_test)
print(dict_test['val'])
example_by_reference(dict_test)
print(dict_test['val'])
dict_test['val'] = 0
dict_test['sum'] = 0
example_recursive_dict(dict_test, 5)
print('summation is done, value is: ', dict_test['sum'])