Python Kill Skills

Table of Contents

1 Python Key Skills

Learn It - convert from number data type to string

myName = "Jack"   # A string
myAge = 5         # A number

# To convert myAge to a string so we can make a longer string to display:
print(myName + " : " + str(myAge))

Learn It - comparing values and comparators

  • Comparators check if a value is (or is not) equal to, greater than (or equal to), or less than (or equal to) another value.
  • The result of comparator operation is always a Boolean vale - True or False
  • Depending on the comparing outcome, the program then decide what to do next.
  • Python has the following comparators:
    • logical operators
      • Equality, ==
      • Not equal, !=
      • Greater Than, >
      • Less Than, <
      • Greater than or equal to, >=
      • Less than or equal to, <=
    • Boolean operators: and, or, not
      • and: evaluates to True when both clauses (expressions) are True
      • or: evaluates to True when either of the expressions are True
      • not: evaluates to True when the expression is False. Evaluates to False when the expression is True.
  • Example usages of comparators
hunger = True
numberOfPizza = 5
drink="fizzyPop"

if numberOfPizza >= 3:
   print("Have some pizza, since we have 3 or more")
else:
   print("You cannot have any pizza")


if hunger == True and numberOfPizza >= 1:
   print("You are hungry, and there is at least one pizza")
else:
   print("Either you are not hungry or the food is not pizza")

if not drink == "fizzyPop":
   print("No drink for me.")

#The above is same as:
if drink != "fizzyPop":
   print("No drink for me.")

Learn It - create an array of numbers or strings

# An array of numbers
testScores = [98, 78, 65, 89, 75]

# An array of strings
names = ['Jack', 'Kerry', 'Julia', 'Matthew', 'David']

Learn It - array index and get an item from an array

  • Each individual data pieces is called an item
  • Each item has a position number called index
  • For the following array, names, "Jack" is at index 0.
  • To get "Jack", you use names[0]
# An array of strings
names = ['Jack', 'Kerry', 'Julia', 'Matthew', 'David']

arrayIndex.png

Learn It - swap the positions of two items in an array

  • Swap the position of "Jack" with "Julia"
    1. Method 1: use a temporary variable
      names = ['Jack', 'Kerry', 'Julia', 'Matthew', 'David']
      
      temp = names[0]
      names[0] = names[2]
      names[2] = temp
      
    2. Method 2: in place swap
      names = ['Jack', 'Kerry', 'Julia', 'Matthew', 'David']
      
      names[0],names[2] = names[2],names[0]