Programming

Writing a simple program using Python

From this post I am going to  show how  to built a simple program using Python. The task is to write a program for general knowledge quiz, and show how many marks, the user  scored  and print a score report with grade. In here I used one file to write  the questions and another file to write answers, as if questions and answers in the same file may be not a good practice as it is easily hack-able. For this simple project I made 5 simple questions and saved it as “questions.txt” and answers in “answer.txt” file.The most important thing is you have to save  these files in a same folder where you saved the python code.

questions.txt file 

######################################################
Question no 1
What is the Capital of Sri Lanka?
A.Sri Jayawardhanapura Kotte
B.Colombo
C.Kandy
D.Girithale
######################################################
Question no 2
What is the Capital of Japan?
A.Hiroshima
B.Tokio
C.Nagasaki
D.Norisako
######################################################
Question no 3
Who is the caption of T 20 Cricket Team in Sri Lanka?
A.Anjelo Mathews
B.Dinesh Chandimal
C.Lasith Malinga
D.Arjuna Ranathunga
######################################################
Question no 4
Who won 2011 Cricket World Cup?
A.Sri Lanka
B.India
C.Australia
D.West Indees
######################################################
Question no 5
Who is the current President of Sri Lanka?
A.Maithreepala Sirisena
B.Nimal Siripala De Silva
C.Mahinda Rajapaksha
D.Ranil Wickramasinghe
#######################################################

answer.txt file 

Question NO And Answers 
1.A
2.B
3.C
4.B
5.A

The 1st thing is  to do in this task is to open the  file named “questions.txt”. In python open() function can be  used  for this process; and read the file line by line until question number ends. [Here “##’ marks indicates starts and ends a question] So, when counting lines it is easy to use for loop using with in keyword. A question it has 7 lines, lets take line 0 to line 6, and define a variable to count, and using the break keyword we can break for loop when question ends.

questionsFile = open("questions.txt") 
questionsLineNumber = 0
for line in questionsFile:
        print line
        questionsLineNumber = questionsLineNumber+1
        if questionsLineNumber > 6:
            break

The question file has 5 questions, so changing from question to questions we need another loop to operate. I used a while loop for this operation. The whole code can be viewed below.

The Total Code for the Project

questionsFile = open("questions.txt")
questionsLineNumber = 0
questionNumber = '1'
score = 0
while questionNumber < '6': for line in questionsFile: print line questionsLineNumber = questionsLineNumber+1 if questionsLineNumber > 6:
print "[Note:If you want to exit from questions type e]\n\n"
break
answer = raw_input("Enter The Answer :")
answer = answer.upper()
if answer=='E':
exit()
answerFile = open('answer.txt')
for line in answerFile:
line = line.rstrip()
if questionNumber in line:
correctAnswer=line[2:3]
break
if answer == correctAnswer:
print 'Correct!! congratulations..'
score = score + 1
else:
print 'The Answer is wrong the correct answer is',correctAnswer
questionNumber = int(questionNumber)
questionNumber = questionNumber+1
questionsLineNumber = 0
questionNumber = str(questionNumber)
print "\n\n#################################################\n"
print " Score Report\n"
print "###################################################\n"
if score == 5:
print "Wow! you got All Correct answers\n"
print "Your Grade is :A"
elif score > 3:
print "You got",score,"Correct answers\n"
print "Your Grade is :B"
elif score > 2:
print "Hmm You got",score,"Correct answers\n"
print "Your Grade is :C"
else:
print "Sorry Try again,you've got only",score,"Correct answers\n"
print "Your Grade is:F, Try Again"

print "##################################################\n"

In Python, raw_input()  inbuilt function can be  used to get user inputs. In this scenario we need this function where we need to get answers from the user.In here I gave a option to the user by typing “e” to exit from the questions, so I used exit() function for this purpose.When a user inputs a “simple” letter, it creates an exception as in the answer file, the answers are written in capital letters. So the input should be converted in to a capital letter, for that python has a function called upper().

gene

When reading the answers file we need to understand what is a new line here. The real scenario is like this , for each enter mark it writes a new line character. So each line has a newline( “\n” )character. So when we are reading answers from answers file we have to trim the (“\n”) character.In python the function strip() is used in this purpose, when you want to trim left spaces you can use lstrip() function  and rstrip() to trim right spaces.So after striping the answer in answer it has the output of  “[1][.][A]” where 1 is the 0th position in the string and and A in 2nd position.So by using line[2:3] we can get the exact Letter in the answer file. Finally I want to tell that for the while loop I used the variable questionNumber and assign it as a string ‘1’. The reason is when comparing the question no in the line” if questionNumber in line:” we have to match with it a string. So in for loop line give a string and it cannot be matched with a integer, but at the end we need iteration to go to the next question by adding 1, so there I had to convert it as an Integer as questionNumber = int(questionNumber) to do the addition and finally have to convert it as a string for the comparing purpose.So this simple program we can improve it for better user friendly and with using a more no of questions.

projectfinal

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s