|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Learning How to program with Python.
#18815414 - 09/08/13 02:18 PM (10 years, 5 months ago) |
|
|
I'm taking Computer Science now and we starting programming with Python. I am going to post some of the code that we design so that if anyone else is interested in learning to program they can have some information about it.
Python is free to download here:
http://www.python.org/getit/
Here is the basic format that I have learned so far.
""" Header the tripple quotes allow you to type comments that wont execute, on multiple lines and the # is used for commenting on a single line
"""
# Listed below are the modules to be loaded.
# Listed below are the constants in all capital letters.
# Listed below are the strings and inputs.
# Listed below is the total.
# Listed below is the printed results.
Below are posted 2 codes including their descriptions, (No modules are loaded in these)
Dr. Ozzie Motto would like a gas mileage calculator to determine the gas mileage of various vehicles, and I have been contracted to write a program that will do exactly that. The first thing I will need to do after writing the header explaining the program, is to ask the user to input the starting and ending mileage of the car as well as the amount of gas consumed by the car while identifying the inputs as integers. Then I will take the ending reading of the odometer and subtract it from the beginning value of the odometer and divide it by the amount of gas consumed in the total column. After that I will print the total results and quit the program.
""" Title: Gas Mileage Calculator Author: teknix Description: This program has been designed to calculate the gas mileage of a vehicle. """
# Listed below are the strings and inputs.
startString=input("What is the starting mileage of the vehicle? ") startInteger=int(startString)
endString=input("What is the ending mileage of the vehicle? ") endInteger=int(endString)
gasString=input("How many gallons of gas was consumed? ") gasInteger=int(gasString)
# Listed below is the calculated total.
total=((endInteger - startInteger) / gasInteger)
# Listed below is the printed results.
print("The total gas mileage for this vehicle is " + str(total))
quit=input("Press enter to quit. ") Customer Request #2 (time.py)
Dr. Mill Secs contracted me to write a program to calculate the amount of milliseconds for a given amount of time including days, hours, minutes and seconds. The first thing I will do after identifying the program in the header is define the constants of the desired variables in milliseconds. Then I will create the strings and inputs for each of the previously defined variables asking for the user to input the amount to be calculated while only allowing for integers. After that I multiple the integers given by the constants and add them all together in the total column. Finally I will print the total results for the user to view the input data in milliseconds and exit the program. """ Title: Millisecond Calculator Author: teknix Description: This program has been designed to compute a given amount of time into milliseconds.
"""
# Listed below are the constants in all capital letters.
DAY_AMOUNT = 86400000 HOUR_AMOUNT = 3600000 MINUTE_AMOUNT = 60000 SECOND_AMOUNT = 1000
# Listed below are the strings and inputs.
daysString=input("How many days? ") daysInteger=int(daysString)
hoursString=input("How many hours? ") hoursInteger=int(hoursString)
minutesString=input("How many minutes? ") minutesInteger=int(minutesString)
secondsString=input("How many seconds? ") secondsInteger=int(secondsString)
# Listed below is the calculated total.
total=(DAY_AMOUNT * daysInteger + HOUR_AMOUNT * hoursInteger +MINUTE_AMOUNT * \ minutesInteger + SECOND_AMOUNT * secondsInteger)
# Listed below is the printed results.
print("The total amount of milliseconds is for the given time is: " + str(total))
quit=input("Press enter to quit. ")
Edited by teknix (10/11/13 12:01 PM)
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: teknix]
#18815424 - 09/08/13 02:21 PM (10 years, 5 months ago) |
|
|
#Below is the input string requesting user input.
secondsString=input("How many seconds? ")
#Below the input string is defined as an integer, allowing only integers to be entered by the user.
secondsInteger=int(secondsString)
#This isn't how I would personally write it, but I'm following the format as #instructed by the teacher.
#I would personally write it like:
seconds_str=input("How many seconds? ")
seconds=int(seconds_str)
#notice that the seconds is connected to seconds_str now but seconds only allow for integers and seconds_str by itself would limit input. (so you have to define the type of input requested below the string.
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: teknix]
#18815470 - 09/08/13 02:37 PM (10 years, 5 months ago) |
|
|
Here a module is loaded and used; import math allows for use of math.pi, which is used the irrational number pi for the multiplication.
# Listed below are the modules to be loaded.
import math
# Listed below are the strings and inputs
radiusString = input ("Enter the radius of your circle:") radiusInteger = int(radiusString)
# Listed below is the total.
circumference = 2 * math.pi * radiusInteger area = math.pi * (radiusInteger ** 2)
# Listed below is the printed results.
print ("The circumference is:",circumference) print ("The area is:",area)
quit=input("Press enter to quit. ")
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: teknix]
#18815527 - 09/08/13 02:55 PM (10 years, 5 months ago) |
|
|
To get python to let you program, you have to open idle, IE; after you install it, type in Idle in the start/run menu (Search) and open it, then go to options and click on "Configure IDLE" then go to the General tab and change the startup preferences under at start up to "Open Edit Window".
Or click on "open New window" each time.
|
PsilliCoder
xXxXxXx

Registered: 12/10/09
Posts: 764
|
Re: Learning How to program with Python. [Re: teknix]
#18823691 - 09/10/13 02:42 PM (10 years, 5 months ago) |
|
|
I've never coded in python, but i've heard it's an easy language to start with. It seems a bit outdated and redundant though imo. I've been using java mostly lately..But it's not really the best language imo.
--------------------
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: PsilliCoder]
#18825904 - 09/10/13 11:28 PM (10 years, 5 months ago) |
|
|
Yeah, Python is pretty straight forward, and pretty forgiving compared to some. I can't wait to learn java!
Here is a recent programs using if/and/else:
""" Title: Admittance Determinant Author: teknix Description: This program is designed to tell a student if he or she can get into a university if the requirements of a 1.75 gpa and act of 23. Deadline: ~ """
#Below are the inputs, asking user for scores.
actStr=input("What was your score on the ACT exam? ") gpaStr=input("What was your high school GPA? ")
#Below the strings converted to floating integers or just floats. (Can use decimals)
act=float(actStr) gpa=float(gpaStr)
#Below are listed the conditionals.
if act>=23 and gpa>=1.75: print ("You can attend the university! ")
else: print ("You need a better score to attend the university. ")
quit=input("Press enter to exit")
|
Dawks
Jolly African Potato


Registered: 06/09/10
Posts: 4,935
|
Re: Learning How to program with Python. [Re: PsilliCoder]
#18831208 - 09/12/13 05:17 AM (10 years, 5 months ago) |
|
|
Quote:
PsilliCoder said: It seems a bit outdated and redundant though imo.
Explain.
--------------------
date ; unzip ; strip ; touch ; grep ; finger ; mount ; fsck ; more ; yes ; umount ; sleep
|
bryguy27007
Cosmonaut



Registered: 01/26/08
Posts: 10,525
Loc:
|
Re: Learning How to program with Python. [Re: Dawks]
#18840686 - 09/14/13 10:55 AM (10 years, 5 months ago) |
|
|
I started taking an online class in Python (through Coursera) but didn't have the time to finish it. I'm excited for when I finally have the time to learn Python though. Good luck on your journey and I'll be keeping tuned for your updates!
|
PsilliCoder
xXxXxXx

Registered: 12/10/09
Posts: 764
|
Re: Learning How to program with Python. [Re: Dawks]
#18841565 - 09/14/13 04:23 PM (10 years, 5 months ago) |
|
|
Quote:
Dawks said:
Quote:
PsilliCoder said: It seems a bit outdated and redundant though imo.
Explain.
It really just depends on what you want to do with it. I do, however, agree that it's a language that every programmer should know...(Sadly, I don't.) I just never had a reason to learn it. I do plan to learn it in the future. But really, anything you can do with python, you can do with another language and most of the time better.
Maybe, when I get bored with Java, i'll play around with Python.
--------------------
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: bryguy27007]
#18842859 - 09/14/13 11:16 PM (10 years, 5 months ago) |
|
|
Quote:
bryguy27007 said: I started taking an online class in Python (through Coursera) but didn't have the time to finish it. I'm excited for when I finally have the time to learn Python though. Good luck on your journey and I'll be keeping tuned for your updates!
Thanks bryguy! Hows things been?
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: teknix]
#18848516 - 09/16/13 10:58 AM (10 years, 5 months ago) |
|
|
I'll post some more progs I put together, not going to explain them right now because I'm tired and need a nap:
""" guesser """
import random number= random.randint(0,100) print("Hi-Lo Number Guessing Game: between 0 and 100 inclusive.") print()
guess_str = input("guess a number: ") guess = int(guess_str)
while 0<= guess <= 100: if guess < number: print("Guessed too low") elif guess > number: print("guessed too high") else: print("Your guessed it. The number was:",number) break
guess_str=input("guess a number") guess = int(guess_str)
else: print("you quit early,the number was:",number)
-------------------------------------------------------------- """ triangles
"""
#First I will ask for the user to input the data in sequential order and identify the data as a float.
sideAstring=input("What is the length of the shortest side of the triangle? ") sideAfloat=float(sideAstring)
sideBstring=input("What is the length of the middle side of the triangle? ") sideBfloat=float(sideBstring)
sideCstring=input("What is the length of the longest side of the triangle? ") sideCfloat=float(sideCstring)
#Second I will use conditionals to determine if any of the side listed is greated than the previous one if any of them are greater I will tell the user that they input invalid data and exit.
if (sideAfloat > sideBfloat) or (sideBfloat > sideCfloat) or (sideAfloat > sideCfloat) : print("Improper order of sides input, restart the program and try again.") quit=input("Press enter to exit the program.")
#Third I will use a conditional to determine if the sum of the first two sides are less than the third side if not I will display that the data entered doesn't make a triangle.
#Elif is else if, which it is referring to the if, and it only executes if the previous if or elif didn't.
elif sideCfloat >= (sideBfloat + sideAfloat) or (sideAfloat==sideCfloat) or (sideBfloat==sideCfloat) : print("Those sides do not create a proper triangle.") quit=input("Press enter to exit the program.") #Fourth I will confirm that those will make a triangle, assuring the same number wasn't entered 3 times and display that info.
elif sideCfloat<(sideBfloat+sideAfloat) and not (sideAfloat ** 2 + sideBfloat ** 2 == sideCfloat**2) and not (sideBfloat==sideCfloat): print("Those sides will make a triangle.") quit=input("Press enter to exit the program.")
#Fifth I will determine if the side are a right triangle using the Pythagorean theorem and display that info.
elif (sideAfloat ** 2 + sideBfloat ** 2 == sideCfloat**2) and not(sideAfloat ** 2 + sideBfloat ** 2 ==0): print("Those sides will make a triangle.") print("Those sides will also make a right triangle.") quit=input("Press enter to exit the program.")
--------------------------------------------------------------------------- """ Body Mass Index """
#First I will list the constants, converting inches to meters and pounds to kilograms.
METER_AMOUNT= .0254 KILO_AMOUNT = .453592
#Second I will list the strings and define the strings as floats, asking for user input of inches and pounds.
inchString=input("How tall are you in inches? ") inchFloat=float(inchString)
# While is a loop, monitoring the input of the user to prevent crash if a 0 is input it changes it to a 1,(can't divide by zero) will use is.digit in the future.
while inchFloat == 0 or inchFloat <= -.00001: inchFloat=1 print("Your are lieing to me.")
poundString=input("How much do you weigh in pounds? ") poundFloat=float(poundString)
while poundFloat == 0 or poundFloat <= -.00001: poundFloat == 1 print("You lied to me twice now . . .") break
#Third I will convert inches to meters and pounds to kilograms.
heightTotal=(inchFloat * METER_AMOUNT) weightTotal=(poundFloat * KILO_AMOUNT)
#Fourth I will use the converted data in the BMI formula. bmiTotal=( weightTotal/heightTotal**2) bmiDisplay=int(bmiTotal)
#Fifth I will list the results and determine the status of the input data using conditionals. if bmiTotal == 0 or bmiTotal < -1: print("No BMI for you, because you lied!") if bmiTotal < 18.5 and not (bmiTotal==0) and not (bmiTotal <-1): print ("Your BMI is",bmiDisplay," and your weight status is underweight.") if bmiTotal >= 18.5 and bmiTotal < 25 : print ("Your BMI is",bmiDisplay,"and your weight status is normal.") if bmiTotal >= 25 and bmiTotal < 30 : print ("Your BMI is",bmiDisplay,"and your weight status is overweight.") if bmiTotal > 30 and not bmiTotal > 100: print ("Your BMI is",bmiDisplay,"and your weight status is obese.") if bmiTotal > 100 : print ("I think you are lieing, enter realistic numbers next time, no BMI for you!")
quit=input("Press enter to exit")
------------------------------------------------------------------------
Edited by teknix (10/11/13 12:00 PM)
|
Labs4858


Registered: 04/20/13
Posts: 484
Loc: Colorado
Last seen: 4 years, 5 months
|
Re: Learning How to program with Python. [Re: teknix]
#18855383 - 09/17/13 08:35 PM (10 years, 5 months ago) |
|
|
This is very similar to MATLAB(which i use.) Awesome stuff. I like how you coded it to print out a string if the user doesn't use the program correctly. I'll be up for hours in the night just trying to figure out how to make something work and why i'm getting those errors. Just sitting there with a rockstar just 
(edit)
just so you can see the similarity, here's an example of a MATLAB program that will calculate in kilograms the amount of fuel needed for certain detentions (input by user) of a SRB(solid rocket booster).
Code:
% -------------------------------------------------------------- % Program: SRB01 % Submitted by: % Submitted on: 9/16/2013 % By submitting this with my name, I affirm that the creaton and % modification of this program is primarily my own work. %--------------------------------------------------------------- clear; clc;
%given: current booster: 149.16ft long 12.17ft in diameter %assume SRB is a perfect cylinder %---------------------------------------------------------------
%convert current weight to kg %LBS/2.2 = Kg Currentweight = (1100000/2.2); %find the area of SRB9 Area = (2*pi)*(6.085^2) + (149.16)*(2*pi)*(6.085); %find how much weight per LBS WeightperLBS = Currentweight/Area; %ask for the length of the rocket Length = input('What is the length of the rocket?: '); %ask for the radius of the rocket Diameter = input('What is the diameter of the rocket?: '); %determine radius Radius = Diameter/2; %determine the new area Newarea = (2*pi)*(Radius^2)+(Length)*(2*pi)*(Radius); %set equation for new weight Newweight = WeightperLBS*Newarea; %add some style fprintf('---------------------------------------------------------\n') %print answer using placeholders fprintf('The revised SRB structure named My New SRB Design\nhas a length of %-.2f feet and a diameter of %-.2f feet,\nand requires %-.2f kg of propellant.\n',Length,Diameter,Newweight) %add some style fprintf('---------------------------------------------------------\n')
--------------------
Edited by Labs4858 (09/17/13 08:41 PM)
|
deadwk
00101011


Registered: 06/17/09
Posts: 8,890
Loc: Canada, eh?
|
Re: Learning How to program with Python. [Re: Labs4858]
#18857726 - 09/18/13 12:11 PM (10 years, 5 months ago) |
|
|
I'll definitely be checking up on this thread, currently learning Python in a programming class for my sys admin program. The teacher fucking sucks though 
So far we've learned about variables, loops, branch conditions, and that's about it.
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: Labs4858]
#18861397 - 09/19/13 01:54 AM (10 years, 5 months ago) |
|
|
Quote:
Labs4858 said: This is very similar to MATLAB(which i use.) Awesome stuff. I like how you coded it to print out a string if the user doesn't use the program correctly. I'll be up for hours in the night just trying to figure out how to make something work and why i'm getting those errors. Just sitting there with a rockstar just 
(edit)
just so you can see the similarity, here's an example of a MATLAB program that will calculate in kilograms the amount of fuel needed for certain detentions (input by user) of a SRB(solid rocket booster).
Code:
% -------------------------------------------------------------- % Program: SRB01 % Submitted by: % Submitted on: 9/16/2013 % By submitting this with my name, I affirm that the creaton and % modification of this program is primarily my own work. %--------------------------------------------------------------- clear; clc;
%given: current booster: 149.16ft long 12.17ft in diameter %assume SRB is a perfect cylinder %---------------------------------------------------------------
%convert current weight to kg %LBS/2.2 = Kg Currentweight = (1100000/2.2); %find the area of SRB9 Area = (2*pi)*(6.085^2) + (149.16)*(2*pi)*(6.085); %find how much weight per LBS WeightperLBS = Currentweight/Area; %ask for the length of the rocket Length = input('What is the length of the rocket?: '); %ask for the radius of the rocket Diameter = input('What is the diameter of the rocket?: '); %determine radius Radius = Diameter/2; %determine the new area Newarea = (2*pi)*(Radius^2)+(Length)*(2*pi)*(Radius); %set equation for new weight Newweight = WeightperLBS*Newarea; %add some style fprintf('---------------------------------------------------------\n') %print answer using placeholders fprintf('The revised SRB structure named My New SRB Design\nhas a length of %-.2f feet and a diameter of %-.2f feet,\nand requires %-.2f kg of propellant.\n',Length,Diameter,Newweight) %add some style fprintf('---------------------------------------------------------\n')
That's cool bro, I was just messing around trying to watch user input just because, (wasn't part of the assignment), but I could have done it much better and I had extra lines of code I didn't need, the next one will be better ^.^, I'll prob get a redbull and mess with a new one this weekened.
They do seem pretty similar, I think if you learn one really well, the rest of the programming languages will be fairly easy to learn with a few minor adjustments, but I guess I will find out! Feel free to post more if you have time, just nothing too advanced yet. 
We are just now learning for and while in class for loops, and how to count using quotients and remainders, and looping back to input again if it isn't proper.
printf is in linux cshell.
So there is print, printf, and fprintf, lol. Oh and we use the ** for squaring instead of ^.
Edited by teknix (09/19/13 02:01 AM)
|
lessismore
Registered: 02/10/13
Posts: 6,268
|
Re: Learning How to program with Python. [Re: teknix]
#18861417 - 09/19/13 02:01 AM (10 years, 5 months ago) |
|
|
Python is nice
I speak python,c,fortran,php,bash 
(and also visual basic:-D, ''on error resume next'', goto)
python almost writes itself, just like bash , the difference is that python is a programming language, so a bit more powerful/faster/portable ofc
python.org is the only resource I need for learning/writing python, pretty good documentation
python is very good with large numbers... and has many modules, so often easier than fortran to mess with (but fortran is pretty cool too, it's almost like a mix of visual basic and C:-D)
- visual basic programmers never die, they just go sub and never return
Edited by lessismore (09/19/13 02:19 AM)
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: lessismore]
#18861447 - 09/19/13 02:17 AM (10 years, 5 months ago) |
|
|
------------------------------------------------------------------ Here are a couple simple codes using for instead of while:
numberOfQuizzes = int( input("Enter the number of quizzes: "))
total = 0
for quizNumber in range(1,numberOfQuizzes+1): score = int(input("Enter the score on quiz " +str(quizNumber) + "; ")) total = total + score average = total/numberOfQuizzes print("The average quiz score is " +str(average))
-------------------------------------------------------------------
childsAgeStr = input("Enter the child's age: ") childsAge = int(childsAgeStr) childsAgeCount = 0
for childsAgeCount in range (1, childsAge +1): print("Are we there yet?") print(childsAgeCount)
Edited by teknix (10/11/13 12:00 PM)
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: lessismore]
#18861453 - 09/19/13 02:19 AM (10 years, 5 months ago) |
|
|
Quote:
mio said: Python is nice
I speak python,c,fortran,php,bash 
(and also visual basic:-D, ''on error resume next'', goto)
python almost writes itself, just like bash , the difference is that python is a programming language, so a bit more powerful/faster ofc
python.org is the only resource I need for learning/writing python, pretty good documentation
python is very good with large numbers... and has many modules, so often easier than fortran to mess with (but fortran is pretty cool too, it's almost like a mix of visual basic and C:-D)
- visual basic programmers never die, they just go sub and never return
Cool mio, now I know who to hit up for help! You guys! 
I would be interested in seeing one of the above code examples in c!
|
lessismore
Registered: 02/10/13
Posts: 6,268
|
Re: Learning How to program with Python. [Re: teknix]
#18861498 - 09/19/13 02:44 AM (10 years, 5 months ago) |
|
|
#include <stdio.h> int main(void) { long age=0; while (!age) { printf("Enter the child's age: "); scanf(" %2d",&age); if (age==0) printf("Are we there yet?\n"); else if (age==1) printf("YAY!!\n");
}
return 0; }
Now find the bug(s) :-D , it has a bug if you enter a string instead of decimal hehe
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: teknix]
#18861499 - 09/19/13 02:45 AM (10 years, 5 months ago) |
|
|
#Here is a simple while if with a counter, you input child's age and it says are we there yet as many times as you input: childsAge = int(input("Enter the child's age: ")) childsAgeCount = 1
while childsAgeCount <= childsAge: childsAgeCount = childsAgeCount + 1 print("Are we there yet?")
if childsAge == childsAgeCount: print("YAY!!")
Edited by teknix (10/11/13 11:59 AM)
|
teknix
πβπ
’ππ
π°π‘ πΌπ⨻



Registered: 09/16/08
Posts: 11,953
|
Re: Learning How to program with Python. [Re: lessismore]
#18861502 - 09/19/13 02:46 AM (10 years, 5 months ago) |
|
|
Quote:
mio said: #include <stdio.h> int main(void) { long age=0; while (!age) { printf("Enter the child's age: "); scanf(" %2d",&age); if (age==0) printf("Are we there yet?\n"); else if (age==1) printf("YAY!!\n");
}
return 0; }
It uses printf like cshell, but seems harder to me than python.
|
|