tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
#!/usr/bin/python
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"
if 2 + 2 == 4:
print "2 and 2 is 4"
print "Arithmetic works."
else:
print "2 and 2 is not 4"
print "Big Brother wins."
#--------------------------------------------------------------
num = 15
if num < 10:
print "number is less than 10"
elif num > 10:
print "number is greater than 10"
else:
print "number is equal to 10"
#--------------------------------------------------------------
if 1 < 2:
print "1 is less than 2"
elif 3 < 4:
print "3 is less than 4"
else:
print "Who moved my cheese?"
#--------------------------------------------------------------
want_cake = "yes"
have_cake = "no"
if want_cake == "yes":
print "We want cake..."
if have_cake =="no":
print "But we don't have any cake"
elif have_cake == "yes":
print "And it's our lucky day"
else:
print "The cake is a lie."
#------------------------------------------------------------
phrase = "it marks the spot"
for letter in phrase:
if letter == "X":
break
else:
print("There was no 'X' in the phrase")
#---------------------------------------------------------------
tries = 0
while tries < 3:
password = input("Password: ")
if password == "I<3Bieber":
break
else:
tries = tries + 1
else:
print("Suspicious activity. The authorities have been alerted.")
#---------------------------------------------------------------
if age > 18:
print "adult person"
for i in range(5):
print i
#---------------------------------------------------------------
age = 17
if age > 18:
print "Driving licence issued"
else:
print "Driving licence not permitted"
#---------------------------------------------------------------
name = "Luke"
if name == "Jack":
print "Hello Jack!"
elif name == "John":
print "Hello John!"
elif name == "Luke":
print "Hello Luke!" # Hello Luke!
else:
print "Hello there!"
#---------------------------------------------------------------
grades = ["A", "B", "C", "D", "E", "F"]
grade = "L"
if grade not in grades:
print "unknown grade" # unknown grade
#---------------------------------------------------------------
sex = "M"
age = 26
if age < 55 and sex == "M":
print "a young male" # a young male
#---------------------------------------------------------------
name = "Jack"
if ( name == "Robert" or name == "Frank" or name == "Jack"
or name == "George" or name == "Luke"):
print "This is a male"
#---------------------------------------------------------------
x = 10
y = 0
if (y != 0 and x/y < 100):
print "a small value"
#---------------------------------------------------------------
x,y =10,40
if(x < y):
st= "x is less than y"
else:
st= "x is greater than y"
print (st)
#---------------------------------------------------------------
total = 500
#country = "US"
country = "AU"
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
if country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")
#---------------------------------------------------------------
a = 100
b = 100
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
#---------------------------------------------------------------
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
#---------------------------------------------------------------
a = 6
b = 5
# Basic comparisons
if a < b:
print("a is less than b")
if a > b:
print("a is greater than b")
print("Done")
from __future__ import division # So that 8/3 will be 2.6666 and not 2
import wx
from math import * # So we can evaluate "sqrt(8)"
class Calculator(wx.Dialog):
'''Main calculator dialog'''
def __init__(self):
wx.Dialog.__init__(self, None, -1, "Calculator")
sizer = wx.BoxSizer(wx.VERTICAL) # Main vertical sizer
# ____________v
self.display = wx.ComboBox(self, -1) # Current calculation
sizer.Add(self.display, 0, wx.EXPAND) # Add to main sizer
# [7][8][9][/]
# [4][5][6][*]
# [1][2][3][-]
# [0][.][C][+]
gsizer = wx.GridSizer(4, 4)
for row in (("7", "8", "9", "/"),
("4", "5", "6", "*"),
("1", "2", "3", "-"),
("0", ".", "C", "+")):
for label in row:
b = wx.Button(self, -1, label)
gsizer.Add(b)
self.Bind(wx.EVT_BUTTON, self.OnButton, b)
sizer.Add(gsizer, 1, wx.EXPAND)
# [ = ]
b = wx.Button(self, -1, "=")
self.Bind(wx.EVT_BUTTON, self.OnButton, b)
sizer.Add(b, 0, wx.EXPAND)
self.equal = b
# Set sizer and center
self.SetSizer(sizer)
sizer.Fit(self)
self.CenterOnScreen()
def OnButton(self, evt):
'''Handle button click event'''
# Get title of clicked button
label = evt.GetEventObject().GetLabel()
if label == "=": # Calculate
try:
compute = self.display.GetValue()
# Ignore empty calculation
if not compute.strip():
return
# Calculate result
result = eval(compute)
# Add to history
self.display.Insert(compute, 0)
# Show result
self.display.SetValue(str(result))
except Exception, e:
wx.LogError(str(e))
return
elif label == "C": # Clear
self.display.SetValue("")
else: # Just add button text to current calculation
self.display.SetValue(self.display.GetValue() + label)
self.equal.SetFocus() # Set the [=] button in focus
if __name__ == "__main__":
# Run the application
app = wx.App()
dlg = Calculator()
dlg.ShowModal()
dlg.Destroy()
The wx.GridSizer lays out widgets in two dimensional table. Each cell within the table has the same size.
wx.GridSizer(int rows=1, int cols=0, int vgap=0, int hgap=0)
#!/usr/bin/python
#A function is created with the def keyword
def function():
pass
#-------------------------------------------------------
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#-------------------------------------------------------
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
#-------------------------------------------------------
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#-------------------------------------------------------
print "1 + 1 =", 1 + 1
print "2 * (2 + 3) =", 2 * (2+3)
print "1.2 / 0.3 =", 1.2 / 0.3
print "5 / 2 =", 5 / 2
# 1 + 1 = 2
# 2 * (2 + 3) = 10
# 1.2 / 0.3 = 4.0
# 5 / 2 = 2
#functions
def square(number):
sqr_num = number **2
return sqr_num
input_num = 5
output_num = square(input_num)
print "print output", output_num
#function morethan one input
def returnDifference(n1, n2):
"""Return the difference between two numbers.
Subtracts n2 from n1."""
return n1 - n2
print "print output", returnDifference(1,1)
def add_two_numbers(num1, num2):
sum = num1 + num2
return sum
print "print output", add_two_numbers(1,1)
print "print output", add_two_numbers(1,2)
#loop
n = 1
while (n < 5):
print "n =", n
n = n +1
print "Loop finished "
for n in range(1, 5):
print"n =", n
print "Loop finished "
for i in range(0, 4):
if i == 2:
break
print i
print "Finished with i = ", str(i)
phrase = "it marks the spot"
for letter in phrase:
if letter == "ks":
print "yes ks"
break
else:
print "There was no 'X' in the phrase"
tries = 0
while tries < 3:
password = raw_input("Password: ")
if password == "ednalan":
break
else:
tries = tries +1
else:
print "Suspicious activity. The authorities have been alerted."
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
#-------------------------------------------------------------------
def add_two_numbers(num1, num2):
sum = num1 + num2
return sum
print(add_two_numbers(1,1)) #2
#---------------------------------------------------------------------
n = 1
while (n < 5):
print("n =", n)
n = n + 1
print("Loop finished")
#---------------------------------------------------------------------
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
i -= 1
sum = sum + numbers[i]
print "The sum is: ", sum
#---------------------------------------------------------------------
import random
while (True):
val = random.randint(1, 30)
print val, # 14 14 30 16 16 20 23 15 17 22
if (val == 22):
break
#---------------------------------------------------------------------
import random
num = 0
while (num < 1000):
num = num + 1
if (num % 2) == 0:
continue
print num,
#---------------------------------------------------------------------
import random as rnd
for i in range(10):
print rnd.randint(1, 10), # 1 2 5 10 10 8 2 9 7 2
def root(x):
return x * x
#---------------------------------------------------------------------
def root(x):
return x * x
a = root(2)
b = root(15)
print a, b
#---------------------------------------------------------------------
x = 15
def function():
global x
x = 45
function()
print x # 45
#---------------------------------------------------------------------
print 4 in (2, 3, 5, 6)
for i in range(25):
print i, # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#---------------------------------------------------------------------
def gen():
x = 11
yield x
it = gen()
print it.next() # 11
#---------------------------------------------------------------------
def showModuleName():
print __doc__
def getModuleFile():
return __file__
a = showModuleName()
b = getModuleFile()
print a, b
#---------------------------------------------------------------------
def f():
"""This function prints a message """
print "Today it is a cloudy day"
print isinstance(f, object) # True
print id(f) # 3077407212
print f.func_doc # This function prints a message
print f.func_name # f
#---------------------------------------------------------------------
from math import sqrt
def cube(x):
return x * x * x
print abs(-1)
print cube(9)
print sqrt(81)
#---------------------------------------------------------------------
def showMessage(msg):
print msg
def cube(x):
return x * x * x
x = cube(3)
print x # 27
showMessage("Computation finished.") # Computation finished.
print showMessage("Ready.") # Ready.
#---------------------------------------------------------------------
n = [1, 2, 3, 4, 5]
def stats(x):
mx = max(x)
mn = min(x)
ln = len(x)
sm = sum(x)
return mx, mn, ln, sm
mx, mn, ln, sm = stats(n)
print stats(n) # (5, 1, 5, 15)
print mx, mn, ln, sm # 5 1 5 15
#---------------------------------------------------------------------
def C2F(c):
return c * 9/5 + 32
print C2F(100) # 212
print C2F(0) # 32
print C2F(30) # 86
#---------------------------------------------------------------------
def power(x, y=2):
r = 1
for i in range(y):
r = r * x
return r
print power(3) # 9
print power(3, 3) #27
print power(5, 5) # 3125
#---------------------------------------------------------------------
def display(name, age, sex):
print "Name: ", name
print "Age: ", age
print "Sex: ", sex
display("Lary", 43, "M") # Name: Lary Age: 43 Sex: M
display("Joan", 24, "F") # Name: Joan Age: 24 Sex: F