Archive for April, 2011

Python String Methods

# Example of string methods using a quote from Manny Pacquiao.

quote = “Nothing personal, I\’m just doing my job.”

print(“In uppercase:”)
print(quote.upper())

print(“\nIn lowercase:”)
print(quote.lower())

print(“\nAs a title:”)
print(quote.title())

# The value of quote is unchange
print(“\nOriginal quote:”)
print(quote)

## Output ##
In uppercase:
NOTHING PERSONAL, I’M JUST DOING MY JOB.

In lowercase:
nothing personal, i’m just doing my job.

As a title:
Nothing Personal, I’m Just Doing My Job.

Original quote:
Nothing personal, I’m just doing my job.

 

Be the first to comment  Posted by Ferdy - April 20, 2011

Categories: Python   Tags:

Python if else and elif

# If condition is true, execute block, otherwise skip.
if condition:
     block

# if statement with else clause.
# If condition_1 is true, block_1 is executed; otherwise     block_2 is executed
if condition_1:
     block_1
else:
     block_2

# if statement with elif clause and optinal final else claue.
# The block of the first true condition is executed.
# If no condition is true, the optional else block_N+1 is executed.
if condition_1:
     block_1
elif condition_2:
     block_2
elif condition_3:
     block_3
.
.
.
elif condition_N:
     block_N
else:
     block_N+1

# Comparison Operators use in evaluating condition.
  ==   equal to
  !=   not equal to
  >   greater than
  <   less than
  >=   greater than or equal to
  <=   less than or equal to

 

Be the first to comment  Posted by Ferdy -

Categories: Python   Tags:

Python Random Module

The random module contains the functions randint() and randrange().

Usage example (Dice):

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

import random

# Generate random numbers from 1 to 6 for each die
# using both randint() and randrange() functions.
die1 = random.randint(1, 6)
die2 = random.randrange(6) + 1

total = die1 + die2

print(“You rolled a”, die1, “and a” die2)
print(“for a total of” total)

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

randint() requires two integer argument values and returns a random interger between those two values including the argument values.

randrange() returns a random interger ranging from 0 up the (argument value – 1).
So random.randrange(6) has a total of 6 posible values (0 to 5, Add 1 to make 1 to 6).

 

Be the first to comment  Posted by Ferdy - April 19, 2011

Categories: Python   Tags:

Next Page »