Author Topic: [Python]Collection of exercises and my solution to them  (Read 2237 times)

0 Members and 1 Guest are viewing this topic.

Offline khofo

  • EZ's Swashbuckler
  • Knight
  • **
  • Posts: 350
  • Cookies: 25
  • My humor is so black, it could go cotton picking.
    • View Profile
[Python]Collection of exercises and my solution to them
« on: July 01, 2015, 07:44:48 pm »
These are very simple exercises done with Python
Some of them I created myself and others taken from online courses


1. Very Basic function:
 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay()and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use raw_input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly.
( I find this retarded, but may be useful is totally new)


My Solution: ( I had a better version but the autograder would not tak eit, so here is the answer they wanted)
Code: (Python) [Select]

def computepay(h,r):
    over_rate = float(r)*1.5
    over_hours = float(h)-40
    hours = float(h)-over_hours
    if over_hours == 0:
        return hours*float(r)
    else:
        return hours*float(r)+over_hours*over_rate
    print over_hours
h = raw_input("Please enter hours:")
r = raw_input("Please enter rate:")
print computepay(h,r)


2. Make a script that would ask and verify user inputed numbers repeatedly until the user enters 'done'
then print:
The Average
The Sum of all numbers
The number of inputs
The biggest and smallest numbers


My Solution:
Code: (Python) [Select]

#exs
#C:\python27\
#khofo


total = None


while True:                       
    try:                   
       
        num = raw_input("Please enter a number:")
       
        if num == "done":
            break
       
        if total is None:
            average = int(num)
            total_numbers_entered = 0
            total = 0
            maxi = int(num)
            mini = int(num)
       
        total_numbers_entered = total_numbers_entered + 1
        total = total + int(num)
        average = total/total_numbers_entered
       
        if int(num) > maxi:
            maxi = int(num)


           
        elif int(num) < mini:
            mini = int(num)
   
   
   
    except:
       
        print "Please enter a number, when done type in 'done'"




print "Total:", total
print "Average:", average
print "number of inputs:", total_numbers_entered
print "Maximum is:", maxi
print "Minimum is:", mini   


3. Make a script that converts Temperatures from F to C and vice versa: (inspired by John who was doing the same but with C)
Code: (Python) [Select]

#Khofo temp converter






#Functions


               
def convert():
    print "Welcome tp khofo's temperature converter"
    while True:
         
        try:
            temp = int(raw_input("Please choose 1. Celsius to Fahrenheit, or 2. Fahrenheit to Celsius: "))
            if temp == 1:
                cel = float(raw_input("Please enter the temperature in Celsius u wish to convert: "))
                break
            elif temp == 2:
                fah = float(raw_input("Please enter the temperature in Fahrenheit u wish to convert: "))
                break
                   
            else:
                print "Error: Please retry"
                     
        except:
                 
            print "Error: Please retry"
   
   
    if temp == 1:
       
        converted_fah = (cel*float(9/5))+32
        print ("%d C In fahrenheit is: %d F") % (cel, converted_fah)
   
    elif temp == 2:
        converted_cel = float(fah-32)*float(5/9)
        print ("%d F in Celsius is: %d C") % (fah, converted_cel)


def _end_():
   
    print "Thank you for"
    retry = raw_input("To restart type 'restart' to exit press anything: ")
    if retry == "restart":
        convert()
    else:
        print "Bye"
       
def main():
    convert()
    _end_()


#End of Functions


#######################################   


print main()




4. Simple Port Scanner
I did not write this code by myself  I modified ad cleaned a script submitted by Christian25r
Code: (Python) [Select]

#C:\Python27\
#Created by: Christian25r
#Edited by: khofo
#Simple port scanner


#Imports
from socket import *
import re


######################
#Top
print "/////////////Simple port scanner////////////////"
print "                                                "
print "/////////////by: Christian25r///////////////////"
print "-------------edited by: khofo-------------------"
print "                                                "


#get user input and verify


while True:
        address = raw_input("Please Enter Target IPv4 Address (or localhost):")
        if re.match('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$',address):
                break
        print "ERROR:Invalid IPv4 Address Format try again"     #This is regex (regular expressions), it's a cooler way to try the IP,
                                                                #since mistakes in the format can be made, and a traceback is not cool
                                                                #Thanks again HTH




ip = gethostbyname(address)
print address,"has the IP:",ip
while True:
        try:
                min_port = int(raw_input("Port (min):"))
                max_port = int(raw_input("Port (max):"))       #added try to also verify the ports
                break
        except:
                print "Invalid ports"




############################


#Functions


def scanner(ip,min_port, max_port):
        count = 0   
        for ports in range(min_port, max_port):
                try:
                        print "Scanning port :%d" % (ports,)
                        s = socket(AF_INET, SOCK_STREAM)
                        s.settimeout(3)
                        s.connect((ip, ports))
                        s.settimeout(3)
                        print "Port %d: is OPEN" % (ports,)
                        count = count + 1
                except:
                        print "Port %d is CLOSED" % (ports,)
                        s.close()
       
        print "Scanning finished !"
        print ""
        print "Found %d open ports" % (count)         
           
###########################       


#Executions


print "----------------------------------------------------"
print "Proceeding to scan..."
scanner(ip, min_port, max_port)


#End


print "----------------------------------------------------"
print "----------------------Done--------------------------"
raw_input("---------------Press 'Enter' to exit----------------")
print "Goodbye!"


I will add more during my quest  to learn python
These are by no way a professional exercises or answers just a bunch of code I wrote myself (or not).
« Last Edit: July 01, 2015, 07:46:22 pm by Khofo »
Quote from: #Evilzone
<Spacecow18> priests are bad ppl
<Insanity> Holy crap
Of course God isnt dead. He's out there partying with the Easter Bunny, Santa Clause, Tooth Fairy, and the Man on the moon...
Some of my work: Introduction to Physical Security

Offline Trogdor

  • Peasant
  • *
  • Posts: 63
  • Cookies: -12
    • View Profile
Re: [Python]Collection of exercises and my solution to them
« Reply #1 on: July 01, 2015, 08:44:52 pm »
Thanks Khofo this is really helping me learn the basics of Python(yes I'm a n00b).  :P

Offline khofo

  • EZ's Swashbuckler
  • Knight
  • **
  • Posts: 350
  • Cookies: 25
  • My humor is so black, it could go cotton picking.
    • View Profile
Re: [Python]Collection of exercises and my solution to them
« Reply #2 on: July 01, 2015, 09:45:18 pm »
Thanks Khofo this is really helping me learn the basics of Python(yes I'm a n00b).  :P


Well I am glad that I am helping someone
Quote from: #Evilzone
<Spacecow18> priests are bad ppl
<Insanity> Holy crap
Of course God isnt dead. He's out there partying with the Easter Bunny, Santa Clause, Tooth Fairy, and the Man on the moon...
Some of my work: Introduction to Physical Security