Python 101

A concise tutorial to a concise language

PyLadies Amsterdam

♡2022 by Bhoomika Agarwal. Copying is an act of love. Love is not subject to law. Please copy.

Contents

  1. Background
  2. Python Variables, Types & Lists
  3. Basic Operators
  4. String Formatting & Operations
  5. Conditions & loops
  6. Functions
  7. Dictionaries, tuples

A quick background

  • Multipurpose
    • Data analysis, Web, GUI, Scripting
  • Object oriented
  • Interpreted
  • Focus on readability & productivity

Is Python used enough?

Hello World!


print("Hello  World!")

hello.py

Variables & Types

  • Numbers
    • Integers
    • Float
  • Strings
  • Null
one = 1
two = 2
three = one + two

hello = "hello"
world = "world"
helloworld = hello + world

print(three)
print(helloworld)

Mixing operators between numbers and strings is not supported

Lists

  • Similar to arrays, but heterogeneous
  • Appending to a list
  • Extending a list
  • Accessing list items
  • Python is 0-indexed
mylist = []
mylist.append(1)
mylist.append("hello") 

print(mylist[1])

colors = ['red', 'brown', 'blue', 'green', 'white']

colors[1]
#brown

colors[2:4]
#['blue', 'green']

Basic Operators

  • Addition, multiplication,
  • Subtraction, division
  • Modulus (%)
  • Power operator
  • Strings with operators
  • Lists with operators
number = 1 + 2 * 10 / 5.0

remainder = 11 % 5

squared = 5 ** 2
cubed = 5 ** 3

#string operations
helloworld = "hello" + "world"
lotsofhellos = "hello" * 10 

#list operations
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers

print([1,2,3] * 3)

Exercise

The Meal

You've finished eating at a restaurant, and received this bill:

  • Cost of meal: $44.50

  • Restaurant tax: 6.75%

  • Tip: 15%

You'll apply the tip to the overall cost of the meal (including tax). Display the tip calculated.

Solution

Text

cost = 44.5
tax = 0.0675 * 44.5
total_cost = cost + tax
tip = 0.15 * total_cost
print(tip) # tip = 7.13
print(tip+total_cost) #overall cost = 54.63

String formatting

  • C style formatting
  • The % operator
  • () parenthesis
  • Argument specifiers:
    • %s - Strings
    • %f - floating point
    • %d - integers
    • %.<digits>f - Floating point number with fixed digits
name = "John"
age = 23
print("%s is %d years old." % (name, age))
# John is 23 years old


# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)

String Operations

  • Wide variety of operations like:
    • len
    • index
    • count
    • slicing
    • reverse
    • [start:stop:step]
    • upper/lower
    • split
s = "Hey there! what should this string be?"
print("Length of s = %d" % len(s))

print("The first occurrence of the letter a = %d" % s.index("a"))

print("a occurs %d times" % s.count("a"))

# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The twelfth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s' " %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end

# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())

# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())

# Check how a string starts
if s.startswith("Hey"):
    print("String starts with 'Hey'. Good!")

# Check how a string ends
if s.endswith("ome!"):
    print("String ends with 'ome!'. Good!")

# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))

Exercise

You will need to write a format string which prints out the data using the following syntax:

Hello John Doe! Your total bill amount is 54.63$.

Solution

Text

cost = 44.5
tax = 0.0675 * 44.5
total_cost = cost + tax
tip = 0.15 * total_cost
print(tip) # tip = 7.13
name = "Bhoomika"
print ("Hello %s! Your total bill amount is %.2f$" %(name, tip+total_cost))
  • Boolean values True and False
  • Conditions help us select from options
  • if, elif, else
  • == and !=
  • The in operator
  • The is operator v/s == operator
  • The not operator
  • Indentation
name = "Ram"
if name in ["Ram", "Bharat"]:
    print("Your name is either Ram or Bharat.")

people = 30
cars = 40

if cars > people:
    print("We should take the cars.")
elif cars < people:
    print("We should not take the cars.")
else:
    print("We can't decide.")

print(not False) # Prints out True

Conditions

Loops

  • Loops help us iterate over a piece of code
    • for loop
    • while loop
  • Iterating over a list of items
  • Iterating over a sequence of numbers
primes = [2, 3, 5, 7]
for prime in primes:
    print(prime) #prime acts as iterator

# we can also build lists, first start with an empty one
elements = []

for i in range(0, 6):
    elements.append(i)

for x in range(3, 6):
    print(x)

Loops - while

  • Repeats as long as a certain Boolean condition is met
  • break
  • continue
  • The else part for loops
count = 0
while count < 5:
    print(count)
    count += 1  

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)

Console Input

#Works for all data types

username = input("What is your name? ")
myage = input("What is your age? ")

Exercise - Pig Latin

In this exercise, you have to write a Pig Latin translator.

Pig Latin is a language game, where you move the first letter of the word to the end and add "ay."  If a word begins with a vowel (a,e,i,o,u), just add “way” in the end. So "Python" becomes "ythonpay." “object” becomes “objectway”, and so on.

To write a Pig Latin translator in Python, here are the steps we'll need to take:

  1. Ask the user to input a word in English.

  2. Convert the word from English to Pig Latin.

  3. Display the translation result.

Solution

Text

s = input("Enter a word:")

#check if the first letter is a vowel
if s[0] in ['a', 'e', 'i', 'o', 'u']:
    piglatin = s + "way"
else:
    piglatin = s[1:] + s[0] + "ay"
    
print("Your word in piglatin is", piglatin)

Functions

  • Functions are a convenient way to divide your code into useful blocks
  • Defining a function 
  • Passing arguments 
  • Returning from a function
  • Calling a function
def my_function():
    print("Hello there!")

def sum_two_numbers(a, b):
    return a + b

#Prints "Hello there!"
my_function()

x=sum_two_numbers(10,15)
#x now holds the sum of 10 and 15
print(x)

Exercise - Twin Primes

Twin prime numbers are a pair of prime numbers that have a difference of 2 between them. For example, (3,5), (5,7), (11,13), (29,31), etc.

Given two numbers a and b, check if they are twin primes.
To do the above,

  1. Create a function prime(n) that checks if a number is prime or not

  2. Check if a and b are prime numbers using the created function

  3. Check if a and b are twin primes

Solution

Text

def prime(x):
    #check for all numbers between 2 and x-1
    for i in range(2,x):
        #check for divisibility and return False
        if x%i == 0:
            return False
    #return True if loop is exited
    return True
    
def twin_primes(a, b):
    if prime(a) and prime(b) and abs(a-b)==2:
        return True
    else:
        return False

a = input("Enter the first number:")
b = input("Enter the second number:")
if twin_primes(int(a),int(b)):
    print("The 2 numbers entered are twin primes")
else:
    print("The 2 numbers entered are not twin primes")

Dictionaries 

  • Like arrays, but works with keys and values instead of indexes
  • Creating dictionaries
  • Iterating
  • Removing values
phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781,
    "Jake" : 998833221
}

#Prints all the phone numbers in the dictionary
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))

#Deletes the entries of John and Jake from the phonebook
if "John" not in phonebook:
    print("John is not listed in the phonebook.")
else:
    del phonebook["John"]

phonebook.pop("Jake")






Exercise

Given a list containing the key-words searched on Google by a user, count the number of occurrences of each key-word and display in the form of an array

For example, given this input -

Key_word_list = [‘cricket’, ‘india’, ‘football’, ‘cricket’, ‘yahoo’, ‘google’, ‘india’, ‘cricket’]

We should get this as the output:

cricket - 3, india - 2, football - 1, yahoo - 1, google -1

 

 

Solution

Text

key_word_list = ['cricket', 'india', 'football', 'cricket', 'google','yahoo', 'google', 'india', 'cricket']
my_dict = {}

for key_word in key_word_list:
    if key_word not in my_dict:
        my_dict[key_word] = 1
    else:
        my_dict[key_word] = my_dict[key_word] + 1

print(my_dict)

Tuples

  • Like lists, but cannot be changed
myList = [1,2,3]
myList.append(4)
print(myList)

myTuple = (1,2,3)
print(myTuple)
myTuple.append(4)
#Generates an error!

print(myTuple)

Thank You for your attention!

Made with Slides.com