Class 3 Lab 4 ‐ User Dictionary - Justin-Boyd/Python-Class GitHub Wiki
Step 1
- Create a new Python file in PyCharm.
- Right-click the project you created previously, and select New > Python File
Step 2
- Create an empty dictionary.
servicePorts = {}
Step 3
- Create an infinite while loop.
while True:
Step 4
- Create a variable that asks for a service name.
service = input("Please enter a service's name or type '0' to stop: ")
Step 5
- Add an if condition in the while loop to break the loop if the input from the user is 0.
if service == "0":
break
Step 6
- In the while loop, ask for a port number and assign it to the port variable.
port = input("Please enter a port number or type '0' to stop: ")
Step 7
- Add another if condition in the while loop to break the loop if the input from the user is 0.
if port == "0":
break
Step 8
- Insert the data from the service and port variables as key-value pairs, in the empty dictionary created during step 1.
servicePorts[service] = port
Step 9
- When the user decides to quit by pressing 0, print the entire dictionary.
print(servicePorts)
Step 10
- Right click on the filename to open the drop down list and click on Run “Filename.”
Step 11
- Input a service name (DNS) with its proper port number (53) and then end the program (0) which should give you these final results.
Final Code
"""Lab Objective: Understand how to work with user-defined dictionaries to control the program flow."""
servicePorts = {}
while True:
service = input("Please enter a service's name or type '0' to stop: ")
if service == "0":
break
port = input("Please enter a port number or type '0' to stop: ")
if port == "0":
break
servicePorts[service] = port
print(servicePorts)
print(servicePorts["FTP"])
# prevents program from closing upon execution
input("\nPress 'Enter' to exit the program")