It is always interesting for beginners in programming to input the values to variables through interactive method. It will be truly interactive if the screen prompts for the required input. This article describes the commonly employed method to achieve this in Python 3. There are some points to remember while using this.
1. Assign the data type.
2. Properly structure the 'prompt'.
With the following example, the implementation in Python 3 can be seen line by line.
first_name=input("Please enter your first name?")
second_name=input("Please enter your second name?")
This portion can be embedded in a loop to repeat required number of times. Adding a few more fields and writing the data to an external file, one can easily collect large amount of data, well organised (eg: details of all the students in a class or like that). The following is the piece of working code in Python 3 for that.
The code is a simple data base builder. The respective fields can be customised to suit the need.
#Initializing the data file with write permission
#Initialising the list of fields
#The main loop of data base builder
for i in range(0,1000,1):
first_name = str(input("Please enter your first name.. "))
second_name = str(input("Please enter your second name.. "))
print("Carefully enter the details in the following fields.")
rc=str(input("Proceed? Y or N?"))
#Structured so that the rest of the code runs based on the input at this step
if rc == "n" or rc == "N":
break #breaks the loop if the response in NO
# collecting the rest of the data with nested input method in list appending step
all_ages.append(str(input("Please enter your age. ")))
all_DOB.append(str(input("Please enter your Date of Birth. ")))
all_emailids.append(str(input("Please enter your email id. ")))
all_cell.append(str(input("Please enter your cell phone number. ")))
data_file=open("ALL_DATA.DB",'a') #Data base file is opening with append permission
#Writing to file as per the format. %s means the string data type. \n will make the successive data to go to the new line
data_file.write("%s; %s; %s; %s; %s; %s\n" % (all_first_names[i],all_second_names[i],all_ages[i],all_DOB[i],all_emailids[i],all_cell[i]))
data_file.close() #Closing the file without data corruption
print("Thank you. Data updated successfully.")
Found helpful, share it with friends and Like the page.
Post a Comment