Notes

Python Basics

Edit on GitHub

Python
7 minutes

Print is pretty much the same as echo in Bash and PHP and puts in Ruby

1name = "Aamnah Akram"
2print(name)    

Input input()

Function to get information from a user. Always gets a string, even if the content is a number.

1input("How are you today?")

Variables

Variables in Python can not start with a number

1name = "Aamnah"

Save input as variable

1name = input("What is your name? ")
2print(name)

Conditionals (if, else)

1if name == "Aamnah":
2    print(name + " is awesome!")
3else:
4    print(name + " is OK i guess. " + name " is fine!")

Your if statement will work with or without the parentheses ( ) but since 2010, the style guide recommends using them. So if (name == "Aamnah"): is preferred over if name == "Aamnah":

Combining multiple conditions with or and and

Here is an example

1#!/bin/python
2
3answer = raw_input("Are you a dumbo? YES or NO ")
4
5if (answer == 'yes') or (answer == 'y'):
6    print("Of course you are! You're very honest. ")
7
8else:
9    print("Lier Lier! ")

will output ‘Of course you are! You’re very honest.’ if you answer with y or yes. If you answer with anything else, it’ll say Lier Lier!

String Concatenation

1name = input("What's your name? ")
2age = input("What's your age? ")
3print(name + " is " + age " years old.")

String Formatting / Replacement

1name = input("What's your name? ")
2if name == "Aamnah":
3    print("{} is awesome".format(name))
4else:
5    print("{} is OK i guess. {} is fine!".format(name, name))

Another example

1name = "Aamnah"
2age = 25
3city = "Dubai"
4print("{} is {} years old. She lives in {}".format(name, age, city))

Basic Numbers

When you divide two numeric values, you always get a float as result. Floats work mostly how they are supposed to but occasionally you’ll find some odd problems. For example

10.1 + 0.1 + 0.1 - 0.3

should result 0 but gives 5.551115123125783e-17 instead.

Make numbers from strings

1int('55')
2float('2.897')

When you take input in, it always takes it as a string. So you’d have to convert it to an int or float first in order to do any kind of calculation on it.

Convert floats to integers and vice versa

1int('2.2')
2float('2')

Round floats to whole numbers round()

round() rounds a float to the nearest whole number. round(2.4) will become 2 and round(3.9) will become 4.

Exceptions

 1user_string = "What's your word? "
 2user_num = "What's your number? "
 3
 4try:
 5    our_num = int(user_num)
 6except:
 7    our_num = float(user_num)
 8
 9if not '.' in user_num:
10    print(user_string[our_num]
11else:
12    ratio = round(len(user_string)*our_num)
13    print(user_string[ratio])

Containment in, not in

Check if something is in or not in something else. For example, 'a' in 'Aamnah' would return True. 'b' not in 'Aamnah' would return True. 'x' in 'Aamnah' would return False

Lists

Check List’s length len()

1>>> fruits = ['Apple', 'Bannana', 'Mango', 'Cherries', 'Guava']
2>>> len(fruits)
35

Make Lists from String list()

1>>> list('a')
2['a']
1>>> list('hello')
2['h', 'e', 'l', 'l', 'o']

Check if value in List

1>>> fruits = ['Apple', 'Bannana', 'Mango', 'Cherries', 'Guava']
2>>> 'Apple' in fruits
3True
1>>> fruits = ['Apple', 'Bannana', 'Mango', 'Cherries', 'Guava']
2>>> 'Orange' in fruits
3False

Append to list .append()

We can only add lists to other lists. .append() add to the end of a list.

Splitting Strings .split()

Calling .split() on a string breaks the string up on whitespaces. If we had Returns or Tabs, they’d also break.

1>>> sentence = "My name is Aamnah. I am curious!"
2>>> sentence.split()
3['My', 'name', 'is', 'Aamnah.', 'I', 'am', 'curious!']

Join Strings .join()

1>>> sentence = "My name is Aamnah. I am curious!"
2>>> sentence.split()
3['My', 'name', 'is', 'Aamnah.', 'I', 'am', 'curious!']
4>>> sentence_list = sentence.split()
5>>> ' '.join(sentence_list)
6'My name is Aamnah. I am curious!'

You can determine what is used to join the list. In the example above, we used spaces. We can also use _ or - or something else.

1>>> '_'.join(sentence_list)
2'My_name_is_Aamnah._I_am_curious!'

Everything we are joining has to be a string. We can’t join numbers.

Loops

while loops

1count = 0
2while (count < 9):
3    print 'The count is:', count
4    count = count + 1
5
6print "Good bye!"

for loops

1>>> my_list = [1, 2, 3, 4]
2>>>  num  my_list:
3...     print(num)
41
52
63
74    

See More examples

While vs. For

A for loop can only iterate (loop) “over” collections of things. A while loop can do any kind of iteration (looping) you want. However, while loops are harder to get right and you normally can get many things done with for loops.

else in Loops

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.

  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

1#!/usr/bin/python
2
3count = 0
4while count < 5:
5    print count, " is  less than 5"
6    count = count + 1
7else:
8    print count, " is not less than 5"

When the above code is executed, it produces the following result:

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

break and continue

break makes Python stop whatever loop it is in, which works really well with infinite loops. continue let’s us move on to the next step in the loop.

1while True
2    if new_item == 'END':
3        break
4    shopping_list.append(new_item)
5    print("Item added")
6    continue

Opening files open()

open() - Opens a file in Python. This won’t contain the content of the file, it just points to it in memory.

1open("name.txt")

You can also specify encoding

1open("name.txt" encoding="utf-8")

For ease of use, save the file in a varibale

1names_file = open("name.txt" encoding="utf-8")

By open() you don’t get the actual contents of the file, you just get a pointer to the file. To get the contents, you would use read()

Reading files read()

read() gets the contents of a file for you. For ease of use, you can save the content in a variable.

1data = names_file.read()

Closing files close()

Once you have opened the file and read it, you should close it.

1names_file.close()

Closing the file prevents it from taking up memory.

Modules (aka Libraries) and Packages

There are loads of built-in modules available for Python. You can find a list here. You use the keyword import to bring outside libraries into your code.

You load a library/module using import

1import urllib2
2import json
3import re

You can specify multiple modules in one import statement

1import urllib2, json, re

Functions

Functions follow the same naming rules as variables. You can’t start a function name with a number and you can’t put any hyphens or special characters in the name. We use the keyword def for defining every function, like so

1>>> def say_hello():
2...    print("Hello!")
3...
4>>> say_hello()
5Hello!

Taking arguments is also easy

1>>> def say_hello(name):
2...     print("Hello " + name + "!")
3... 
4>>> say_hello("Amna")
5Hello Amna!

Getting back data using return for when you want to get data back from a function and not just print it.

1>>> def square(num):
2...     return num*num
3... 
4>>> square(99)
59801    

Here is an example of a shopping list with a function to add list items, another function to show help, and a function to show list.

 1shopping_list = []
 2
 3def show_help():
 4    print("What should we pick up at the store? ")
 5    print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list")
 6
 7def add_to_list(item):
 8    shopping_list.append(item)
 9    print("Added! List has {} items".format(len(shopping_list)))
10
11def show_list():
12    print("Here is your list:")
13    for item in shopping_list:
14    print(item)
15
16show_help()
17
18while True:
19    new_item = raw.input("> ")
20    if new_item == 'DONE':
21    break
22
23    elif new_item == 'HELP':
24    show_help()
25    continue
26
27    elif new_item == 'SHOW':
28    show_list()
29    continue
30
31    add_to_list(new_item)
32    continue
33
34show_list()

Collections

Collections are variable types that collect different types of data together. They are also called iterables because you iterate or loop through them.

References

Treehouse