Python snippets

From ZENotes
(Difference between revisions)
Jump to: navigation, search
(Meet Miss Turtle)
 
(40 intermediate revisions by one user not shown)
Line 1: Line 1:
Hello World
+
From http://interactivepython.org, follows snippets (very short bits of code you do as try outs)
 +
 
 +
=Hello World=
  
<syntaxhighlight lang="Python">
 
 
     #---------------------------------------------------
 
     #---------------------------------------------------
 
     # This demo program shows off how elegant Python is!     
 
     # This demo program shows off how elegant Python is!     
Line 9: Line 10:
 
      
 
      
 
     print("Hello, World!")    # Isn't this easy!
 
     print("Hello, World!")    # Isn't this easy!
</syntaxhighlight>
 
  
  
If you are not sure what class a value falls into, Python has a function called '''type''' which can tell you.
+
(this should work with [[Syntax Highlighting]])
  
<syntaxhighlight lang="Python">
+
=="Oh no", she exclaimed, "Ben's bike is broken!"==
    print(type("Hello, World!"))
+
    print(type(17))
+
    print("Hello, World")
+
</syntaxhighlight>
+
  
  
'''"Oh no", she exclaimed, "Ben's bike is broken!"'''
 
 
<syntaxhighlight lang="Python">
 
 
     print(<nowiki>'''"Oh no", she exclaimed, "Ben's bike is broken!"'''</nowiki>)
 
     print(<nowiki>'''"Oh no", she exclaimed, "Ben's bike is broken!"'''</nowiki>)
</syntaxhighlight>
 
  
 +
==This message will span several lines of text==
  
This message will span several lines of text
 
  
<syntaxhighlight lang="Python">
 
 
     message = """This message will
 
     message = """This message will
 
     span several
 
     span several
Line 39: Line 30:
 
     several lines
 
     several lines
 
     of the text.""")   
 
     of the text.""")   
</syntaxhighlight>
 
  
 +
=If you are not sure what class a value falls into,=
 +
 +
Python has a function called '''type''' which can tell you.
  
Variables
+
    print(type("Hello, World!"))
 +
    print(type(17))
 +
    print("Hello, World")
 +
 
 +
=Variables=
  
 
  message = "What's up, Doc?"
 
  message = "What's up, Doc?"
Line 52: Line 49:
 
  print(pi)
 
  print(pi)
 
   
 
   
How many ?
+
==How many ?==
  
 
  minutes = 645
 
  minutes = 645
Line 58: Line 55:
 
  print(hours)
 
  print(hours)
  
 +
==This / and that //==
  
 
In the previous example, what we might have wanted to know was how many whole hours there are, and how many minutes remain.  
 
In the previous example, what we might have wanted to know was how many whole hours there are, and how many minutes remain.  
Line 71: Line 69:
 
   
 
   
  
 +
===Actual output in hours and minutes===
 +
 +
#!/usr/bin/env python
 +
 +
minutes = 645                                                                      # Variable 1: total number of minutes
 +
hours = minutes // 60                                                              # variable 2 uses a // division, takes the smaller integer.
 +
rem=(minutes-(hours*60))                                                            # variable 3 gathers how many minutes where left out
 +
print((minutes),("minutes"),("make"),(hours),("hours"),("and"),(rem),("minutes"))  # result in -h format
 +
 +
 +
===Both ways, the Math Way and the Py way===
 +
 +
#!/usr/bin/env python
 +
 
 +
# Define some Variables:
 +
m = 1645
 +
h = m // 60
 +
d = h // 24
 +
 
 +
  # The math Way:
 +
rm = (m-(h*60))
 +
 +
  #The Py Way:
 +
rp = m % 60
 +
 +
print((m),("min"),("="),(d),("d."),(h),(":"),(rm),("with maths."))
 +
print((m),("min"),("="),(d),("d."),(h),(":"),(rp),("with py."))
 +
 +
 +
Nicer Output:
 +
 +
#!/usr/bin/env python
 +
# An hour/minutes counter, since you cant divide 1645 by 60 and have
 +
# a meaningful answer.
 +
 +
# Define some Variables:
 +
m = 1645
 +
h = m // 60
 +
d = h // 24
 +
 +
# 1645 doesn't divide by 60, how do we get the right answer:
 +
# some more variables; there are here 2 ways of doing that:
 +
 +
# The math Way:
 +
rm = (m-(h*60))
 +
 +
  #The Py Way:
 +
rp = m % 60
 +
 +
print()
 +
print((" How much"),(m),("minutes make in days, hours, minutes?"))
 +
print()
 +
print(("    "),(d),("d"),(h),("h"),(rm),("m"),("with maths."))
 +
print(("    "),(d),("d"),(h),("h"),(rp),("m"),("with py."))
 +
print()
 +
 +
# Easy no ?
 +
 +
Outputs in:
 +
 +
[jph@1215s bin]$ python pstuff.py
 +
 +
  How much 1645 minutes make in days, hours, minutes?
 +
 +
    1 d 27 h 25 m with maths.
 +
    1 d 27 h 25 m with py.
 +
 +
 +
 +
=Get Some Input=
 +
 +
Same, with input at the prompt AND lots unnecessary variables: one can just define by 24 or 60,
 +
no need to first define the 24 factor, much less to pass it as an integer as a new factor...
 +
 +
#!/usr/bin/env python
 +
#
 +
# An hour/minutes calculator, taking input from the prompt.
 +
# Define the Input Variable:
 +
 +
'''minutes_from_input = input("Enter how many minutes: ")'''
 +
 +
# At this stage, the input is just a string, can't do anything with it!
 +
# One MUST convert it to an integer to perform maths on:
 +
'''minutes = int(minutes_from_input)'''
 +
 +
# Following not necessary, actually snobbish:
 +
'''factorhourday = 24'''
 +
'''factorhourminute = 60'''
 +
'''factordh= int(factorhourday)'''
 +
'''factorhm = int(factorhourminute) '''
 +
 +
# Variables declarations and some basic maths:
 +
'''hours = minutes // factorhm'''
 +
'''days = hours // factordh'''
 +
 +
#Let's solve the problem!
 +
  # The math Way:
 +
'''hours_remain_in_math = (hours-(days*24))'''
 +
'''minutes_remain_in_math = (minutes-(hours*60))'''
 +
  #The Py Way:
 +
'''hours_remain_with_py = hours % 24'''
 +
'''minutes_remain_with_py = minutes % 60'''
 +
 +
# And get the answer out there.
 +
'''print()
 +
print((" How much"),(minutes),("minutes make in days, hours, minutes?"))
 +
print()
 +
print(("    "),(days),("d"),(hours_remain_in_math),("h"),(minutes_remain_in_math),("m"),("with maths."))
 +
print(("    "),(days),("d"),(hours_remain_with_py),("h"),(minutes_remain_with_py),("m"),("with py."))
 +
print()'''
 +
 +
 +
Outputs in:
 +
 +
[jph@1215s bin]$ python pstuff.py
 +
Enter how many minutes: 12745
 +
 +
  How much 12745 minutes make in days, hours, minutes?
 +
 +
      8 d 20 h 25 m with maths.
 +
      8 d 20 h 25 m with py.
 +
 +
[jph@1215s bin]$
 +
 +
==More clockwork==
 +
 +
Derived, refined from ''You look at the clock and it is exactly 2pm. You set an alarm to go off in 51 hours. At what time does the alarm go off?''
 +
 +
now = input("What time, rouned in hours, is it? ")
 +
nowint =int(now)
 +
 +
test = input("how many hours to wake-up? ")
 +
testint = int(test)
 +
 +
ipt = testint % 24
 +
days = testint // 24
 +
time = nowint + ipt
 +
 +
res = time % 24
 +
 +
 +
print(("From"),(nowint),("you'll wake up"),(days),("days &"),(ipt),("hours later, at"),(res),("hopefully."))
 +
 +
==Interest compound calculator==
 +
 +
http://en.wikipedia.org/wiki/Compound_interest
 +
 +
pi = input ("How much money Sir? ")
 +
p = int(pi)
 +
 +
n = 12
 +
 +
ri = input ("Interest rate as given to you by the bank Sir? ")
 +
rm = float(ri)
 +
r = (rm/100)
 +
 +
ti = input("How many years Sir? ")
 +
t = int(ti)
 +
 +
Am = p*((1+(r/n))**(n*t))
 +
Ar = Am * 100
 +
Ad = Ar // 1
 +
A = Ad /100
 +
 +
print(p)
 +
print(r)
 +
print(A)
 +
 +
==Radius in any metrics you'd like==
 +
 +
Write a program that will compute the area of a circle. Prompt the user to enter the radius and print a nice message back to the user with the answer.
 +
 +
ri=input("Radius? ")
 +
u=input("Units?")
 +
r=float(ri)
 +
pi=3.14159
 +
print(("your disc has a surface of"),pi*(r**2),(u))
 +
 +
 +
==C / F==
 +
 +
Write a program that will convert degrees celsius to degrees fahrenheit.
 +
 +
# [°F] = [°C] × 9⁄5 + 32
 +
# [°C] = ([°F] − 32)× 5⁄9
 +
 +
ci=input("your input in Celsius (leave blank if Farehneit)")
 +
fi=input("Your input in Farenheit (Leave blank if Celsius)")
 +
 +
c=float(ci)
 +
f=float(fi)
 +
 +
rf=((c*9/5)+32)
 +
rtc=((f-32)*5/9)
 +
 +
#rounding up the C results to 2 decimal paces max.
 +
r100=rtc*100
 +
rdec=r100//1
 +
rc=rdec/100
 +
 +
print((c),("C"),("makes:"),(rf),("F"))
 +
print((f),("F"),("makes:"),(rc),("C"))
 +
 +
=Modules=
 +
 +
==Meet Miss Turtle==
 +
 +
#!/usr/bin/env python
 +
import turtle
 +
 +
wn = turtle.Screen()
 +
 +
wnbgi=input(<nowiki>'''Choose screen color; among acknowledged values are:
 +
-aqua, blue, navy, teal,
 +
-black, gray, silver, white,
 +
-fuchsia,
 +
-green, lime, olive, maroon,
 +
-orange,
 +
-purple,
 +
-red,
 +
-yellow'''</nowiki>)
 +
 +
wn.bgcolor(wnbgi)
 +
 +
tpi=input("pensize, in integer, please")
 +
ps=int(tpi)
 +
 +
tess = turtle.Turtle()
 +
tess.color("blue")              # make tess blue
 +
tess.pensize(ps)                  # set the width of her pen
 +
 +
tess.forward(50)
 +
tess.left(120)
 +
tess.forward(50)
 +
 +
wn.exitonclick()
 +
 +
=Statement "for"=
 +
 +
==For the Spiral==
 +
 +
#!/usr/bin/python
 +
# for w/ spiral
 +
 +
import turtle
 +
wn = turtle.Screen()
 +
alex = turtle.Turtle()
 +
 +
alex.pensize(3)
 +
ls=50
 +
 +
for i in [0,1,2,3,4,6,7,8,9,10,11,12]:     
 +
    alex.left(90)
 +
    alex.forward(ls)
 +
    ls=ls+25
 +
   
 +
wn.exitonclick()
  
 
Back to [[Python]]
 
Back to [[Python]]
 +
 +
[[Python snippets]]
 +
 +
[[Python glossary]]
 +
 +
[[Python modules]]

Latest revision as of 19:55, 5 May 2013

From http://interactivepython.org, follows snippets (very short bits of code you do as try outs)

Contents

Hello World

   #---------------------------------------------------
   # This demo program shows off how elegant Python is!    
   # Written by Joe Soap, December 2010.
   # Anyone may freely copy or modify this program.
   #---------------------------------------------------
   
   print("Hello, World!")     # Isn't this easy!


(this should work with Syntax Highlighting)

"Oh no", she exclaimed, "Ben's bike is broken!"

   print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')

This message will span several lines of text

   message = """This message will
   span several
   lines."""
   print(message)
   
   print("""This message will span
   several lines
   of the text.""")   

If you are not sure what class a value falls into,

Python has a function called type which can tell you.

   print(type("Hello, World!"))
   print(type(17))
   print("Hello, World")

Variables

message = "What's up, Doc?"
n = 17
pi = 3.14159

print(message)
print(n)
print(pi)

How many ?

minutes = 645
hours = minutes / 60
print(hours)

This / and that //

In the previous example, what we might have wanted to know was how many whole hours there are, and how many minutes remain. Python gives us two different flavors of the division operator. The second, called integer division, uses the token //. It always truncates its result down to the next smallest integer (to the left on the number line).

print(7 / 4)
print(7 // 4)
minutes = 645
hours = minutes // 60
print(hours)

Actual output in hours and minutes

#!/usr/bin/env python

minutes = 645                                                                       # Variable 1: total number of minutes
hours = minutes // 60                                                               # variable 2 uses a // division, takes the smaller integer.
rem=(minutes-(hours*60))                                                            # variable 3 gathers how many minutes where left out
print((minutes),("minutes"),("make"),(hours),("hours"),("and"),(rem),("minutes"))   # result in -h format

Both ways, the Math Way and the Py way

#!/usr/bin/env python
  
# Define some Variables:
m = 1645
h = m // 60
d = h // 24
 
 # The math Way:
rm = (m-(h*60))

 #The Py Way:
rp = m % 60 

print((m),("min"),("="),(d),("d."),(h),(":"),(rm),("with maths."))
print((m),("min"),("="),(d),("d."),(h),(":"),(rp),("with py."))


Nicer Output:

#!/usr/bin/env python
# An hour/minutes counter, since you cant divide 1645 by 60 and have
# a meaningful answer.

# Define some Variables:
m = 1645
h = m // 60
d = h // 24

# 1645 doesn't divide by 60, how do we get the right answer:
# some more variables; there are here 2 ways of doing that: 

# The math Way:
rm = (m-(h*60))

 #The Py Way:
rp = m % 60

print()
print((" How much"),(m),("minutes make in days, hours, minutes?"))
print()
print(("    "),(d),("d"),(h),("h"),(rm),("m"),("with maths."))
print(("    "),(d),("d"),(h),("h"),(rp),("m"),("with py."))
print()

# Easy no ?

Outputs in:

[jph@1215s bin]$ python pstuff.py

 How much 1645 minutes make in days, hours, minutes?

    1 d 27 h 25 m with maths.
    1 d 27 h 25 m with py.


Get Some Input

Same, with input at the prompt AND lots unnecessary variables: one can just define by 24 or 60, no need to first define the 24 factor, much less to pass it as an integer as a new factor...

#!/usr/bin/env python 
#
# An hour/minutes calculator, taking input from the prompt.
# Define the Input Variable:

minutes_from_input = input("Enter how many minutes: ")

# At this stage, the input is just a string, can't do anything with it!
# One MUST convert it to an integer to perform maths on:
minutes = int(minutes_from_input)

# Following not necessary, actually snobbish:
factorhourday = 24
factorhourminute = 60
factordh= int(factorhourday)
factorhm = int(factorhourminute) 

# Variables declarations and some basic maths:
hours = minutes // factorhm
days = hours // factordh

#Let's solve the problem!
 # The math Way:
hours_remain_in_math = (hours-(days*24)) 
minutes_remain_in_math = (minutes-(hours*60))
 #The Py Way:
hours_remain_with_py = hours % 24
minutes_remain_with_py = minutes % 60

# And get the answer out there.
print()
print((" How much"),(minutes),("minutes make in days, hours, minutes?"))
print()
print(("    "),(days),("d"),(hours_remain_in_math),("h"),(minutes_remain_in_math),("m"),("with maths."))
print(("    "),(days),("d"),(hours_remain_with_py),("h"),(minutes_remain_with_py),("m"),("with py."))
print()


Outputs in:

[jph@1215s bin]$ python pstuff.py
Enter how many minutes: 12745

 How much 12745 minutes make in days, hours, minutes?

     8 d 20 h 25 m with maths.
     8 d 20 h 25 m with py.

[jph@1215s bin]$ 

More clockwork

Derived, refined from You look at the clock and it is exactly 2pm. You set an alarm to go off in 51 hours. At what time does the alarm go off?

now = input("What time, rouned in hours, is it? ")
nowint =int(now)

test = input("how many hours to wake-up? ")
testint = int(test)

ipt = testint % 24
days = testint // 24
time = nowint + ipt

res = time % 24


print(("From"),(nowint),("you'll wake up"),(days),("days &"),(ipt),("hours later, at"),(res),("hopefully."))

Interest compound calculator

http://en.wikipedia.org/wiki/Compound_interest

pi = input ("How much money Sir? ")
p = int(pi)

n = 12

ri = input ("Interest rate as given to you by the bank Sir? ")
rm = float(ri)
r = (rm/100)

ti = input("How many years Sir? ")
t = int(ti) 

Am = p*((1+(r/n))**(n*t))
Ar = Am * 100
Ad = Ar // 1
A = Ad /100

print(p)
print(r)
print(A)

Radius in any metrics you'd like

Write a program that will compute the area of a circle. Prompt the user to enter the radius and print a nice message back to the user with the answer.

ri=input("Radius? ")
u=input("Units?")
r=float(ri)
pi=3.14159
print(("your disc has a surface of"),pi*(r**2),(u))


C / F

Write a program that will convert degrees celsius to degrees fahrenheit.

# [°F] = [°C] × 9⁄5 + 32
# [°C] = ([°F] − 32)× 5⁄9

ci=input("your input in Celsius (leave blank if Farehneit)")
fi=input("Your input in Farenheit (Leave blank if Celsius)") 

c=float(ci)
f=float(fi)

rf=((c*9/5)+32)
rtc=((f-32)*5/9)

#rounding up the C results to 2 decimal paces max.
r100=rtc*100
rdec=r100//1
rc=rdec/100

print((c),("C"),("makes:"),(rf),("F"))
print((f),("F"),("makes:"),(rc),("C"))

Modules

Meet Miss Turtle

#!/usr/bin/env python 
import turtle

wn = turtle.Screen()

wnbgi=input('''Choose screen color; among acknowledged values are:
 -aqua, blue, navy, teal, 
 -black, gray, silver, white,
 -fuchsia, 
 -green, lime, olive, maroon, 
 -orange, 
 -purple, 
 -red, 
 -yellow''')

wn.bgcolor(wnbgi) 

tpi=input("pensize, in integer, please")
ps=int(tpi)

tess = turtle.Turtle()
tess.color("blue")               # make tess blue
tess.pensize(ps)                  # set the width of her pen

tess.forward(50)
tess.left(120)
tess.forward(50)

wn.exitonclick()

Statement "for"

For the Spiral

#!/usr/bin/python
# for w/ spiral

import turtle
wn = turtle.Screen()
alex = turtle.Turtle() 

alex.pensize(3)
ls=50

for i in [0,1,2,3,4,6,7,8,9,10,11,12]:      
    alex.left(90)
    alex.forward(ls)
    ls=ls+25
    
wn.exitonclick()

Back to Python

Python snippets

Python glossary

Python modules

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox