0% found this document useful (0 votes)
2 views19 pages

Exercises Python

The document contains a series of Python exercises demonstrating various networking and programming concepts, including socket programming, FTP connections, HTTP requests, input handling, and conditional logic. Key examples include establishing a TCP connection, performing FTP operations, and calculating discounts based on user input. The exercises also cover error handling, string manipulation, and percentage calculations related to climbers on different peaks.

Uploaded by

ericnzenga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Exercises Python

The document contains a series of Python exercises demonstrating various networking and programming concepts, including socket programming, FTP connections, HTTP requests, input handling, and conditional logic. Key examples include establishing a TCP connection, performing FTP operations, and calculating discounts based on user input. The exercises also cover error handling, string manipulation, and percentage calculations related to climbers on different peaks.

Uploaded by

ericnzenga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Python - Command Line Hacker – Exercises

· import socket

· # Initialize socket with IPv4 and TCP parameters


· s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

· # Configure timeout for the socket


· s.settimeout(5)

· # Specify the target IP address and port number


· target_ip = "93.184.216.34" # IP address for example.com
· target_port = 80

· # Execute connection attempt


· try:
· s.connect((target_ip, target_port))
· print("Connection to example.com on port 80 succeeded.")
· s.close()
· except Exception as e:
· print("Connection to example.com on port 80 failed.")

° 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

· # Establish connection to the FTP server


· ftp = ftplib.FTP('speedtest.tele2.net')

· # Perform anonymous login


· ftp.login()

· # Display the root directory's contents


· print("Directory contents at the root of speedtest.tele2.net:")
· ftp.retrlines('LIST')

· # Terminate the connection


· ftp.quit()

° 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.

· pip install requests

· import requests

· response = requests.get('http://example.com')

· print("The HTTP status code is:", response.status_code)


· #Telling python to expect receiving 2 integers, or we can specify them


in python itself, a=5, b=10.
· a = int(input())
· b = int(input())
· # Execute the swap
· a, b = b, a
· print("After swapping - a:", a, ", b:", b)

· #Entering the sentences, or we can tell python to expect receiving a


sentence by instead putting text=input()
· text = "Python is powerful. Python is easy to learn. Python is open."

· # Convert the string to lowercase with .lower() to fix any case


sensitivity issues, and counting the occurrences of 'python' using
.count('strings_you_wish_to_count')
· count = text.lower().count('python')

· print("The word 'Python' appears", count, "times.")


· # 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

o 1234 password admin letmein

· #Telling python to expect receiving a string from the console


· correct_password = input()
· #Telling python to expect receiving a string from the console that he
should then divide(.split) when a space occurs(i.e. “1234 password
admin letmein”-> “1234”…)
· passwords = input().split()
· # Going through each string in the list passwords that we just created,
and checking if any of the occurrences match with the actual password
we specified in the beginning, if it does we print it and stop the for
loop.
· for password in passwords:
· if password == correct_password:
· print("Correct password found:", password)
· break


· "Yes! You have {remaining money} dollars left."

· "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

· # Set the initial boat rental price based on the season


· if season == "Spring":
· boat_price = 3000 # Price in spring
· elif season in ["Summer", "Autumn"]:
· boat_price = 4200 # Price in summer and autumn
· elif season == "Winter":
· boat_price = 2600 # Price in winter

· # Apply discount based on the number of fishermen


· if fishermen <= 6:
· discount = 0.10 # 10% discount for groups up to 6
· elif 7 <= fishermen <= 11:
· discount = 0.15 # 15% discount for groups of 7 to 11
· else:
· discount = 0.25 # 25% discount for groups of 12 or more
· boat_price -= boat_price * discount # Calculate discounted price

· # Apply an additional 5% discount if the number of fishermen is even


and it's not Autumn
· if fishermen % 2 == 0 and season != "Autumn":
· boat_price -= boat_price * 0.05 # Additional 5% discount

· # 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


· "Somewhere in [destination]" among "US", "Americas", and "Europe"


· "{Type of vacation} - {Spent amount}":


· # 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

· # Determine destination and accommodation based on the budget


· if budget <= 100:
· destination = "US"
· expense_percentage = 0.30 if season == "summer" else 0.70 # 30%
for summer (camp), 70% for winter (hotel)
· elif budget <= 1000:
· destination = "Americas"
· expense_percentage = 0.40 if season == "summer" else 0.80 # 40%
for summer (camp), 80% for winter (hotel)
· else:
· destination = "Europe"
· expense_percentage = 0.90 # 90% for any season (hotel)

· # Accommodation type based on season and destination


· if destination == "Europe" or season == "winter":
· accommodation = "Hotel"
· else:
· accommodation = "Camp"

· # Calculate spent amount


· spent_amount = budget * expense_percentage

· # Print destination and spent amount with two decimal places


· print(f"Somewhere in {destination}")
· print(f"{accommodation} - ${spent_amount:.2f}")



· # Read the number of groups from the console
· num_groups = int(input())

· # Initialize counters for each peak


· whitney_count = 0
· rainier_count = 0
· denali_count = 0
· elbert_count = 0
· mckinley_count = 0
· total_climbers = 0 # Total number of climbers

· # 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

· # Allocate group to a peak based on size


· if group_size <= 5:
· whitney_count += group_size
· elif group_size <= 12:
· rainier_count += group_size
· elif group_size <= 25:
· denali_count += group_size
· elif group_size <= 40:
· elbert_count += group_size
· else:
· mckinley_count += group_size

· # Function to calculate percentage


· def calculate_percentage(count, total):
· return count / total * 100 if total > 0 else 0

· # Print the percentage of climbers for each peak


· print(f"{calculate_percentage(whitney_count, total_climbers):.2f}%") #
Mount Whitney
· print(f"{calculate_percentage(rainier_count, total_climbers):.2f}%") #
Mount Rainier
· print(f"{calculate_percentage(denali_count, total_climbers):.2f}%") #
Denali
· print(f"{calculate_percentage(elbert_count, total_climbers):.2f}%") #
Mount Elbert
· print(f"{calculate_percentage(mckinley_count, total_climbers):.2f}%")
# Mount McKinley

You might also like