Python Tutorial

Created by Oliver King with the help of Think Python

Download Python

Download and install the latest version of Python from www.python.org/downloads/

Or use repl.it

What is Python?

“Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.”

Open source and was made to be easily readable
Fastest growing programming language

Popularly used in

  • Scripting
  • Math (and Data Science)
  • Web and Software Development
  • Machine Learning

Print and Comments

			  
				  print('Hello World!')			# This is a comment

This is how you use the print function in Python
# are comments in Python

Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (divides then returns the remainder)
** Exponent

              print(1 + 2)						# 3
              print(5 - 4)						# 1
              print(6 * 3)						# 18
              print(9 / 3)						# 3.0
              print(10 % 3)						# 1
              print(2**3)						# 8
              print((10 % 4) * 5)					# 10
            

There is an order of operations
Parenthesis > Exponents > Multiplication / Division > Addition / Subtraction

Variables and Types


              age = 20				   # Integer
              exact_age = 20.25		 	   # Float
              first_name = 'Oliver'		 	   # String
              last_name = "King"			   # Also a String
              awesome = True				   # Boolean
              age = age + 1
              age += 1
              age *= 2
              full_name = first_name + ' ' + last_name   # String concatenation
	        	

These are assignment statements in Python
Variables are dynamically typed

Variable names can only contain letters, numbers, and underscores
The first character cannot be a number
Keywords cannot be used as variable names

Input and Converting Type


            name = input()
            age = input("What's your age?\n")
            age_as_int = int(age)
            age_as_float = float(age)
            age_as_string = str(age_as_int)
            gpa = float(input("What's your GPA? "))
          

Input assumes you are passing in a String

Challenge: Ask the User for a Radius then Compute and Output the Volume of a Sphere with that Radius

Use the formula 4⁄3πr3


              radius = float(input("Enter the radius: "))
              volume = (4/3) * (3.14) * (radius ** 3)
              print('The volume of the sphere with that radius is', volume)
			      

Arithmetic Operators

Operator Description
== Equal
!= Not equal
> Greater than
< Less than
>= and <= Greater (or less) than or equal to

              print(1 == 1)						# True
              print("a" == "a")					# True
              print(1 != 1)						# False
              print(5 > 6)						# False
              print(5 < 6)						# True
              print(5 >= 5)						# True
              print(5 <= 4)						# False
					  

Logical Operators

Operator
and
or
not

              print(True and True)					# True
              print(True and False)					# False
              print(False or True)					# True
              print(False or False)					# False
              print(not (True and False))				# True
              print(not (5 < 6))					# False
			      

Function Definitions and Calls


            def print_lyrics():
              print("I'm a lumberjack, and I'm okay.")
              print("I sleep all night and I work all day.")

            def repeat(lyric1, lyric2):
              print(lyric1)
              print(lyric2)
              print(lyric1)
              print(lyric2)
              print_lyrics()

            # Function calls
            print_lyrics()
            repeat('Wooooooooo', 'Ahhhhhhhh')
			    

Indents are what seperates the header from the body

Challenge: Write a Nested Function that prints a grid like the following

+ - - - - + - - - - +
|           |           |
+ - - - - + - - - - +
|           |           |
+ - - - - + - - - - +


            def draw_line():
              print("+ - - - - + - - - - +")
        
            def draw_connectors():
              print("|         |         |")
        
            def draw_grid():
              draw_line()
              draw_connectors()
              draw_line()
              draw_connectors()
              draw_line()

            draw_grid()
				    

Imports


          import math
          from random import randint

          log = 10 * math.log10(40)
          sine = math.sin(.556)
          real_pi = math.pi
          random = randint(0, 9)
		      

Conditionals


            x = 10

            if x < 10:
              print('Less than 10')
            elif x > 10:
              print('Greater than 10')
            else:
              print('Equal to 10')
          

You can have as many elif statements as you want in a chained conditional

While Loops


            while True:
              line = input('> ')
              if line == 'exit':
                print('Exiting terminal')
                break
              elif line == 'ls':
                print('You have no files here')
              else:
                print('Command not recognized')
          

The break statement jumps out of the loop

Challenge: Print the numbers from 1 to 100

For multiples of three print “Fizz” instead of the number and for multiples of five print “Buzz”. For multiples of both three and five print “FizzBuzz".


            count = 0
            while count <= 100:
              if count % 15 == 0:
                print('FizzBuzz')
              elif count % 5 == 0:
                print('Buzz')
              elif count % 3 == 0:
                print('Fizz')
              else:
                print(count)
              count += 1
				    

For Loops


          for i in range(10):
            print(i)
          
          for i in range(2, 5):
            print(i)

          for i in range(0, 10, 2):
            print(i)

          print(range(10))
          

For loops behave differently from Java
range(start, stop, step)

Lists


          colors = ['Blue', 'Red', 'White', 1, True]
          print(colors[2])
          colors[2] = 'Green'
          print(colors)
          del colors[2]
          print(colors)
          colors.append('Black')
          print(colors)
          colors.insert(1, 'Brown')
          print(colors)
          numbers = list()
          numbers.append(1)
          print(numbers)
          print(len(colors))
          

len() prints the length

For Loops (Again)


          numbers = [1, 5, 7, -100]
          for i in numbers:
            print(i)

          things = input().split()
          for thing in things:
            print(thing)
          

split() by default seperates by spaces

Challenge: Input a variable (unspecified) amount of unique numbers

Check if any of the numbers are multiples of eachother. If two numbers are multiples output both numbers.

Bonus: Allow for duplicate numbers


              numbers_str = input('Please input your numbers: ').split()

              # Gets input as int
              numbers_int = list()
              for i in numbers_str:
                numbers_int.append(int(i))
              
              for x in numbers_int:
                for y in numbers_int:
                  if x == y:
                    break
                  elif (x % y == 0) or (y % x == 0):
                    print(x, ' and ', y)
				    

Tuples


          traits = ('Smart', 'Very Smart', 'Extremely Smart')
          print(traits[0])
          for trait in traits:
            print(trait)
          

Ordered and unchangeable

In


          traits_tuple = ('Smart', 'Very Smart', 'Extremely Smart')
          your_trait = input("What's your trait? ") 
          if your_trait in traits_tuple:
            print('You are smart!')
          else:
            print("Wow! That's a great trait!!!")

          traits_list = list()
          while True:
            your_trait = input("What's your trait? ")
            if your_trait in traits_list:
              print('Do you have any other traits?')
            else:
              print("Wow! That's a great trait!!!")
              traits_list.append(your_trait)
          

Dictionaries


          ages = {
            'Oliver': 20,
            'Ben':  15,
            'Reed': 11,
            'Isaac': 17
          }
          print('Ben' in ages)
          print(ages.get('Ben'))
          ages['Tim'] = 30
          ages['Isaac'] = 18
          for key, value in ages.items():
            print(key, ' -> ', value)
          addresses = dict()
          addresses['Oliver'] = 'Redacted'
          

Challenge: Given an array, find if the array contains any duplicates


Bonus Challenge: Given an array of integers, return indices of the two numbers such that they add up to a specific target


              def containsDuplicates(checking):
                seen = list()
                for i in checking:
                  if i in seen: 
                    return True
                  seen.append(i)
                return False
            
              example = [1, 2, 3, 4, 5]
              print(containsDuplicates(example))
          	

Sets


          foods = {'apple', 'orange', 'Kool-Aid'}
          print(foods)
          foods.add('grape')
          print(foods)
          foods.add('apple')
          print(foods)
          

No duplicates

More Strings


          print('hi' in 'highlight')
          print(len('Hello'))
          print('i was lowercase'.upper())
          print('I WAS UPPERCASE'.lower())
          s = 'This is a string'
          print(s[2])
          print(s[-1])
          

No duplicates

Challenge: Given two lists, write a function to compute their intersection


Bonus Challenge: Given a string, find the first non-repeating character in it and return its index


              def getsIntersection(lista, listb):
                seta = set(lista)
                setb = set(listb)
                intersection = set()
                for i in seta:
                  if i in setb:
                    intersection.add(i)
                return intersection

              a = [1, 2, 2, 1]
              b = [2, 3]
              print(getsIntersection(a, b))
          	

Classes


          class Animal:
            pass
          
          class Person:

            legs = 2                             # Class attribute

            def __init__(self, name):
              self.name = name                      # Instance attribute

            def talk(self):
              print('Hi! I am', self.name)

          me = Person('Oliver')
          print(type(me))
          print(me.name)
          print(Person.legs)
          me.talk()
          

pass is a placeholder

Inheritance


          class Animal:
  
            def __init__(self, name, legs):
              self.name = str(name)
              self.legs = str(legs)
          
            def talk(self):
              print('I am', self.name)
          
          class Dog(Animal):
            def bark(self):
              print('Bark bark bark')

            # def talk(self):
            #   print('Bark')
          
          sam = Animal('sam', 3)
          sam.talk()
          tim = Dog('tim', 4)
          tim.bark()
          tim.talk()
          print(tim.legs)
         

Challenge: Create a working Calculator using a Class


Bonus Challenge: Given two strings, write a method to determine if string one is an anagram of string two.


              class Calculator:

              def __init__(self, operation, var1, var2):
                self.operation = operation
                self.var1 = float(var1)
                self.var2 = float(var2)
            
              def calculate(self):
                if self.operation == '+':
                  print(self.add())
                if self.operation == '-':
                  print(self.subtract())
                if self.operation == '*':
                  print(self.multiply())
                if self.operation == '/':
                  print(self.divide())
                if self.operation == '^':
                  print(self.exponent())
            
            
              def add(self):
                return (self.var1 + self.var2)
            
              def subtract(self):
                return (self.var1 - self.var2)
            
              def multiply(self):
                return (self.var1 * self.var2)
            
              def divide(self):
                return (self.var1 / self.var2)
            
              def exponent(self):
                return (self.var1 ** self.var2)
            
            while True:
              params = input('Please enter your calculation: ').split()
              calculator = Calculator(params[1], params[0], params[2])
              calculator.calculate()
            

Try Except


          number = ''
          try:
            number = int(input('Please enter an integer: '))
          except:
            print("That's not a good input")
            number = -1
          finally:
            print('Your number is', number)
         

The finally is optional

What Next?

  • Download Python and an IDE
  • Read Think Python
  • Advanced Python (List Comprehensions, Lambdas, Generators, Magic Methods, etc.)
  • Web Frameworks (Django or Flask)
  • Games (Pygame)
  • Data Science (NumPy, Pandas, and Matplotlib)