Exercises Python
Exercises Python
· import socket
° import socket: This line imports the Python socket library, which provides the
necessary functions and methods for network communications.
° s = socket.socket(socket.AF_INET, socket.SOCK_STREAM): Initializes a new socket
instance s. socket.AF_INET indicates the use of IPv4. socket.SOCK_STREAM specifies
that this will be a TCP socket.
° s.settimeout(5): Sets a timeout for the socket operations to 5 seconds. If the
connection attempt takes longer than this, it will be terminated and an
exception will be raised.
° target_ip = "93.184.216.34" and target_port = 80: These lines define the target
IP address and port for the connection attempt. The IP address 93.184.216.34
is used as an example, typically resolving to example.com, and port 80 is the
standard port for HTTP.
° The try block attempts to connect to the specified IP and port using
s.connect((target_ip, target_port)). If successful, it prints a success message
and closes the socket with s.close().
° The except block catches any exceptions during the connection attempt, such
as a timeout or refusal, printing a failure message.
•
· import ftplib
° import ftplib: Imports the ftplib module, which provides the tools needed to
create an FTP client in Python.
° ftp = ftplib.FTP('speedtest.tele2.net'): Establishes an FTP connection to the
server located at speedtest.tele2.net. The FTP object represents this
connection.
° ftp.login(): Performs an anonymous login to the FTP server. Unless specified,
the default anonymous credentials ('anonymous' as the username and '' as the
password) are used.
° print("Directory contents at the root of speedtest.tele2.net:"): Prints a
message to indicate that the script will now display the root directory's
contents.
° ftp.retrlines('LIST'): Retrieves the listing of the root directory on the FTP
server and prints it line by line. The 'LIST' command is sent to the server,
which responds with the directory information.
° ftp.quit(): Properly closes the connection to the FTP server. It's important to
terminate the session cleanly to free up resources and avoid potential issues
on the server side.
•
· import requests
· response = requests.get('http://example.com')
· # Using try to tell python to test if this result does not give a
syntax error, if it does then it will go onto the except part.
· try:
· number = float(input("Enter a number: "))
· result = 100 / number
· print("The result is:", result)
· # If the code above returns an error this code will be executed,
otherwise it won’t
· except ZeroDivisionError:
· print("Cannot divide by zero.")
•
o letmein
•
•
· "Not enough money! You need {the amount that is lacking} dollars."
· # Read input from the user
· budget = int(input()) # Group's budget as an integer
· season = input() # Season as a string (e.g., "Spring", "Summer",
"Autumn", "Winter")
· fishermen = int(input()) # Number of fishermen as an integer
· # Compare the final boat price after discounts with the group's budget
· if budget >= boat_price: # If budget is sufficient, calculate and print
the remaining money
· print(f"Yes! You have {budget - boat_price:.2f} dollars left.")
· # The :.2f format specifier in the string ensures the money
amount is formatted to two decimal places
· else: # If budget is not sufficient, calculate and print the lacking
amount
· print(f"Not enough money! You need {boat_price - budget:.2f}
dollars.")
· # Again, :.2f is used to format the lacking money amount to two
decimal places
•
•
•
· # Read input from the user
· budget = float(input()) # Budget as a real number
· season = input().lower() # Season as a string, converted to lowercase
to handle case sensitivity
•
•
•
· # Read the number of groups from the console
· num_groups = int(input())
· # Loop through each group to get the number of people and allocate them
to peaks
· for _ in range(num_groups):
· group_size = int(input()) # Number of people in the current group
· total_climbers += group_size # Update total climbers