Skip to content

Instantly share code, notes, and snippets.

@sahilsinha
Last active October 3, 2017 20:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sahilsinha/8218a4a3c1a004f824b9 to your computer and use it in GitHub Desktop.
Save sahilsinha/8218a4a3c1a004f824b9 to your computer and use it in GitHub Desktop.

Cheat Sheet

Variables

Variables are just boxes that you can put other things into. You can put numbers, words, other variables, and any value you can think of inside a variable. A variable is a box for stuff!

Today we will be working only with strings and ints.

Strings are words that are enclosed in either “” or ”

Ints are whole numbers

a = 2

# a is now 2

b = 3

#b is now 3

c = a + b

#c is now 5

d = a + 5

#d is now 7

a = d

#a is now 7

my_string = "a string here"
my_other_string = 'a string here'


a = '4'
b = int(a)
b == 4

a = 4 
b = str(a)
b == '4'

Input and Output

Getting Input From Our Program

We can use variables to store things we ask our user. Our input is normally a string!

name = input("What is your name? ")
age = int(input("How old are you? "))

Writing to Our Console

# You can print words

print ("This will write words out to our console")

# You can print variables
a = 5
print(a)
#The above will print 5 to our console

Putting it all together

print ("A program to add up some ages")

name = input("What is your name? ")

age1 = int(input("How old are you? "))
age2 = int(input("How old is your partner? "))

print ("Between you,",name,", you are",age1+age2,"years old")

Math

We can do Math with our programs

  • a+b addition
  • a-b subtraction
  • a*b multiplication
  • a/b division (see note below)
  • a//b floor division (e.g. 5//2=2)
  • a%b modulo (return the remainder)
  • -a negation
  • abs(a) absolute value
  • a**b exponent

True/False/None

We can test for truth in if and while statements

Remember any real value is considered True. We can also say the word True

truth = True

Any of the following will be False:

a = None
b = False
c = 0
d = ''

Comparisons

We can compare values to each other with special notation

  • < strictly less than
  • <= less than or equal
  • > strictly greater than
  • >= greater than or equal
  • == equal
  • != not equal
a = 1
b = 2

c = a < b
# c is now True
d = a > b
# d is now False

Boolean Statements

We can combine with boolean statements:

  • and
  • or
  • not
a = 1
b = 2

a == 1 and b == 1 # Will give us false

a == 1 or b == 1 # Will give us true

not (a == 1 or b == 1) # Will give us false

b > a and a > 0 and a != b and not b >= 5 # Will give us true

for loops

This is simply repeating things a number of times

REMEMBER COUNTING STARTS AT 0!

for i in range(3):
   print(i)

#This will print 
#0
#1
#2

for i in range(1,3):
   print(i)

#This will print 

#1
#2

Remember you always have access to the variable i!

Boolean/Comparisons/Truth/

We use logic all over in our programs. We use it to compare things and make decisions with conditions.

if else elif

This is where you get to make decisions and use things like comparisons boolean statements, and Truths.

test_score = 80
if test_score >= 90:
    letter = 'A'
elif test_score >= 80:
    letter = 'B'
elif test_score >= 70:
    letter = 'C'
elif test_score >= 60:
    letter = 'D'
else:
    letter = 'F'

print(letter)

while loops

While loops keep doing things as long as a boolean expression is True

count = 0
while (count < 9):
   print ('The count is:', count)
   count = count + 1

Be careful of infinite loops

x = 1
while True:
    print ("To infinity and beyond!", count)
    x += 1
# Note the x+=1 this means that x = x+1

Lists

Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name.

list1 = ['a','b','c']

list2 = [3,4,5]

list3 = [] #You can have empty lists

Reading lists

Remember lists start at 0

list1[0]

will give you ‘a’

list1.index('b') 

will return the index of an element in this case 1

Adding to lists

list1.append('d')

This will add ‘d’ to the end of your list

Removing from lists

You can remove elements from a list

.pop removes the element via index and returns it

list1.pop(1)

.remove removes the element via the actual item

list1.remove('c')

Slicing lists

You can get part of a list

list1[0:2]

Given a list1=[‘a’,’b’,’c’,’d’] this will return [‘a’,’b’]

Dictionaries

A dictionary is like a list but instead of indices we have keys and values.

Creating a dictionary

my_dict = {'key1' : 1, 'key2' : 2, 'key3' : 3}

my_dict2 = {} #You can have empty dictionaries too

Accessing dictionary values

animals = {'Whale' : 'mammal', 'Bear' : 'mammal', 'Burmese Python' : 'reptile'}

print animals['Whale']

This will print ‘mammal’

Adding elements to a dictionary

animals = {'Whale' : 'mammal', 'Bear' : 'mammal', 'Burmese Python' : 'reptile'}

# This is how we add an element
animals['Dog'] = 'mammal'

# Your dictionary will now look like:

{'Whale': 'mammal', 'Burmese Python': 'reptile', 'Dog': 'mammal', 'Bear': 'mammal'}

Deleting elements from a dictionary

Deleting elements is easy

animals = {'Whale' : 'mammal', 'Bear' : 'mammal', 'Burmese Python' : 'reptile'}

# This is how we delete an element
del animals['Whale]


# Your dictionary will now look like:
{'Burmese Python': 'reptile', 'Bear': 'mammal'}

Functions

A function is giving a block of code a name so that you can reuse it or simply make your program more organized.

Simple Function

def my_function():
    print ("Hello")

my_function()

Arguments

def print_my_argument(words):
    print(words)

my_argument = "Hello World"
print_my_argument(my_argument)

Returning a value

def add_two_numbers(num1,num2):
    sum = num1 + num2
    return sum

mysum = add_two_numbers(4,4)
mysum == 8

Challenges

Challenge 0: What’s your favorite animal?

Hint: Variables and Input and Output are all you need

Example output:

What is your favorite animal? Dog

My favorite animal is the Dog too!

Challenge 1: Madlibs

Hint: You can ask for multiple variables and use them multiple times. Have fun writing whatever you like with as many blanks as you would like.

Example output:

Give me a noun: monkey

Give me a verb: fly

Give me a noun: koala

When you are programming make sure you bring your monkey and your wits. They will serve you well as you fly the koala.

Challenge 2: Calculate the area of a rectangle

Hint: You just need input/output, variables, and some math. The formula for the area of a rectangle is A = Length X Width

Example output:

What is the length?: 5

What is the width?: 9000

The area is 45000!

Challenge 3: Print every number from 1 to 100

Hint: Use for loops and print()

Example output:

1

2

3

4..

100

Challenge 4: Square all numbers from 1-50 and print the output

Hint: Use for loops, math, and print()

Example output:

1

4

9

16

25…

2500

Challenge 5: Print every letter of your name one per line

Hint: You can loop through a string

Example output: What is your name?London

L

o

n

d

o

n

Challenge 6: Convert feet to inches

Hint: All you need is input/output, variables, and some basic math! 1 ft = 12 in.

Example output:

How many feet? 12

That is 144 inches!

Awesome Bonus Extravaganza Challenge: Give your program your height in feet and inches. Have it tell you your actual height in inches.

Challenge 7: Take a radius as input and return the area and circumference of a circle

Hint: the formula for area is A = pi*r^2, the formula for circumference is C = 2*pi*r

Hint 2: At the top of your file you can add “from math import pi” and then you can use pi like a variable. What is happening here? Or you can just use 3.14!

Example output:

What is the radius of the circle? 5

Your circumference is 31.41592653589793

Your area is 78.53981633974483

Challenge 8: Have a for loop run as many times as you input

Hint: You can use variables as your range variable

Example output:

How many times would you like to loop?:2

This is loop 0

This is loop 1

LOOPS ARE AWESOME!

Challenge 9: Take any Number and Print a Times Tables to Twelve - Or Have Your Computer Do Your Homework

Hint: Use a for loop and some simple math

Example ouput:

What would you like to multiply?:11

11

22

33

44

55

66

77

88

99

110

121

132

Challenge 10: Add up lots of numbers

Take in a number and add up each number as you count to that number Fun Fact: This is called a Gaussian Sum. That’s calculus!

Example output:

What is your number?:22

253

AMAZING BONUS GOODWORK CHALLENGE: Have your program show your work

Challenge 11: Ask the user for two numbers and tell me which one is larger

Example output:

What is your first number? 4

What is your second number? 5

5 is larger than 4

Challenge 12: Make a simple calculator

Create a simple calculator that can add, subtract, multiply, and divide two numbers.

Example output:

What would you like to do(add,subtract,divide, or multiply)? multiply

What is your first number? 20

What is your second number? 10

2000

Challenge 13: FizzBuzz

Create a program that counts to 100.

If the number is divisible by 3 print Fizz

If the number is divisible by 5 print Buzz

If the number is divisible by 3 and 5 print FizzBuzz

If the number is none of the above print the number

Hint: use the % math operator - it gives you the remainder

Example output:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

16

17

Fizz

19

Buzz

Fizz…

Buzz

Challenge 14: Take a word and count the vowels

Hint: you can loop through a string

mystring = 'hello'
for i in mystring:
    print(i)


#This program will output:
# h
# e
# l
# l
# o

Example output:

What word would you like to count the vowels for? orange

orange has 3 vowels

Challenge 15: Temperature Conversion

Write a program that converts from Celsius to Fahrenheit and Fahrenheit to Celsius

Hint: Temp Fahrenheit = Temp Celsius * 9/5 + 32

Hint 2: Temp Celsius = (Temp Fahrenheit - 32) * 5/9

Example output:

Would you like to convert Celsius to Fahrenheit (enter c) or Fahrenheit to Celsius (enter f)? f

What is the temperature in Fahrenheit? 32

That is 0 Celsius

Challenge 16: Give an average

Ask how many numbers the user would like to average, get the numbers and give the average.

Hint: Use a while loop

Example output:

How many numbers would you like to average? 5

What is number 1? 20

What is number 2? 40

What is number 3? 50

What is number 4? 60

What is number 5? 50

The average of those 5 numbers is 44

Challenge 17: Guess a number

Have the computer think of a number. You try to guess the number as the computer gives you hints. Quit when you guess the number and print the number of tries.

Hint 1: We can get a random number by doing the following

import random
secret_number = random.randint(0,100)
# this will give us a random integer between 0-100

Hint 2: Use a while loop

Example output:

I’m thinking of a number between 0 and 100 what do you think it is? 5

Nope higher than 5, guess again: 90

Nope lower than 90, guess again: 80

Nope higher than 80, guess again: 85

Nope higher 85, guess again: 89

You got it! It only took you 5 guesses. Thanks for playing!

Challenge 18: A simple function/Functions are just code

Make a function that prints each letter of the alphabet on a new line

Example output: a

b

c

d…

z

Challenge 19: Happy Birthday

It’s Ralph’s and Rachel’s birthday. Write a function that takes a single name as an argument and “sing” happy birthday.

Sing happy birthday to Ralph and Rachel

Example output:

Happy Birthday to you!

Happy Birthday to you!

Happy Birthday, dear Ralph

Happy Birthday to you!

Happy Birthday to you!

Happy Birthday to you!

Happy Birthday, dear Rachel

Happy Birthday to you!

Challenge 20: Taking multiple arguments

Make a function that takes a name, age, weight, and height and prints a bio.

Example output:

Tell me your name: Joe

Tell me your age: 12

Tell me your weight (in pounds): 100

Tell me your height (in inches): 50

Joe is 12 and weighs 100 pounds and is 50 inches tall.

Challenge 21: Charlie Oscar Oscar Lima

The International Civil Aviation Organization (ICAO) alphabet assigns code words to the letters of the English alphabet acrophonically (Alfa for A, Bravo for B, etc.) so that critical combinations of letters (and numbers) can be pronounced and understood by those who transmit and receive voice messages by radio or telephone regardless of their native language, especially when the safety of navigation or persons is essential.

Write a program that takes a string and returns the ICAO equivalent.

Here is a dictionary of all the equivalents:

d = {'a':'alfa', 'b':'bravo', 'c':'charlie', 'd':'delta', 'e':'echo', 'f':'foxtrot',
     'g':'golf', 'h':'hotel', 'i':'india', 'j':'juliett', 'k':'kilo', 'l':'lima',
     'm':'mike', 'n':'november', 'o':'oscar', 'p':'papa', 'q':'quebec', 'r':'romeo',
     's':'sierra', 't':'tango', 'u':'uniform', 'v':'victor', 'w':'whiskey', 
     'x':'x-ray', 'y':'yankee', 'z':'zulu'}

Example output:

What is your string? Fun

Foxtrot Uniform November

Challenge 22: Letter Frequency

Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary.

Example output:

What is your string? abbabd

{‘a’: 2, ‘b’: 3, ‘d’: 1}

Challenge 23: A simple histogram

Take a list of integers and return a simple visual histogram

Example output:

Given a list of [3,4,6]

Ouput

***

****

******

Challenge 24: Which word is the longest?

Write a function which takes a list of words and tells us which is the longest

Example output:

Given a list [‘word’,’blue’,’yellow’]

yellow is the longest word!

Challenge 25/26/27/28:

  • Sort numbers
  • Determine palindrome
  • Factorial
  • Hanoi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment