In: Computer Science
Hands-On Assignments are designed to foster independent thinking and problem solving programming skills. This activity is closely guided by the course instructor. Students are encourages to ask instructor any questions related to this challenge. Similar to the course Exercises, this activity also has a Base Code.
The initially given Base Code to Start with this exercise:
--------------Start----------------
guess.py (also, see starters in the course FILES/StudentFiles/Exercise Starter Files)
--------------End ----------------
Prompt
Task to Accomplish
Tips:
You will need to use “nested loops”
Some useful resources:
https://www.tutorialspoint.com/python/python_nested_loops.htm (Links to an external site.)
https://www.quora.com/What-are-the-best-examples-of-a-Nested-Loops-for-Python (Links to an external site.)
https://www.youtube.com/watch?v=HfzCpDilEVM
Here is the complete code for the following code, To make it simple i have taken a lottery number between 1 to 20, you change it to other values as well
Code:
import random #we are limiting the range from 1 to 20 #generating 5 random numbers between 1 to 20 lottery_number = random.sample(range(1, 20), 5) chances_per_lottery = 10 guessing_num = 0 correct_guesses = [] #this list contain the correct numbers guess by user correct_guesses_count = 0 #outer loop for number in lottery_number: guessing_num = guessing_num + 1 print("Guessing lottery: ", guessing_num) #inner loop while(chances_per_lottery > 0): print("Remaining chances left: ", chances_per_lottery) num = input("Guess lottery number: ") if num == number: correct_guesses.append(num) correct_guesses_count = correct_guesses_count + 1 print() break chances_per_lottery = chances_per_lottery - 1 if chances_per_lottery == 0 and guessing_num != 5: print("Chances Over, Now try to guess the next number\n") chances_per_lottery = 10 print("Total correct guesses: ", correct_guesses_count) print("Numbers are: ", correct_guesses) Output:
Output:
I have set the guess count 2 but asked for 10 because i do not want very long output. However i have changed this value in code. So just copy and run it