Python is a bit different to other intepreter languages as its made up of sequence of logical lines, each made up of one or more physical lines, each pyhsical line may end with a comment. Python does not use the traditional semi-colon as a line terminator, instead you indent the line if its part of the code block, A block is a contiguous sequence of logical lines, all indented by the same amount; a logical line with less indentation ends the block. All statements in a block must have the same indentation, as must all clauses in a compound statement. this will be become more clearer with some examples.
Standard Python style is to use four spaces (never tabs) per indentation level. In v3, Python does not allow mixing tabs and spaces for indentation. So if you do use a professional IDE make sure it uses 4 space indentation, which most do by default.
Example Python program | # This is Python code # Python uses the hash symbol (#) for comments a = 5 b = 1 while a > 0: # notice that some code does use termination b = b * a # 4 spaces for indentation a = a - 1 |
As I mentioned in the introduction page you can use the interactive shell for quick testing or exploring as per below example
The aim of Java this Python web tutorial is to have a quick kinda cheatsheet on the various topics of Python, covering version 3, its going to be a goto place to refresh your memory and to brush up if you don't use Python for a period of time, so think of it as a Python in a Nutshell.
Python has a number of built-in data types scalars (numbers and boolerans) and complex data structures like lists, dictionaries and files.
Integers | 1, –3, 43, 356, 888888888888, –777777666 Note: integers aren’t limited in size except by available memory |
Floats | 3.0, 32e11, –7e-4 |
Compex Numbers | 3 + 4j, –4 - 2k, 4.3 + 6.3q |
Strings | "A string in double quotes can contain 'single quote' characters." 'A string in single quotes can contain "double quote" characters.' '''\tA string which starts with a tab; ends with a newline character.\n''' """This is a triple double quoted string, the only kind that can contain real newlines.""" |
Lists | [] [1] [1, 2, 3, 4, 5, 6, 7, 8, 12] [1, "two", 3, 4.0, ["a", "b"], (5,6)] |
Tuples | () (1,) (1, 2, 3, 4, 5, 6, 7, 8, 12) (1, "two", 3L, 4.0, ["a", "b"], (5, 6)) |
Dictionaries | x = {1: "one", 2: "two"} x["first"] = "one" x[("Delorme", "Ryan", 1995)] = (1, 2, 3) |
Sets | x = set([1, 2, 3, 1, 3, 5]) |
File Objects | f = open("myfile", "w") f.write("First line with necessary newline character\n") f.write("Second line to write to the file\n") f.close() |
Pass Statement | does nothing (see below) |
In Python you will see the pass statement, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future
As with other programming languages variables are used to store data, you use the equal smybol (=) to assign data to a variable, you don't need a end of line terminater. Variables can be set to any object, remember that Python is dynamically typed. Variable names are case-sensitive and can include any alphanumeric character as well as underscores but must start with a letter or underscore.
Variable and assignment examples | greeting = "Paul" _myName = "Paul" Paul99 = "Good" Paul_was_here = "Good" Greeting = "Hello" print(Greeting + ' ' + greeting) ## below will cause an error int and String mix # age = 24 # print(age) # print(greeting + age) a = 12 b = 3 c = 12.45 print(a.__class__) print(b.__class__) print(c.__class__) print(greeting.__class__) print(a + b) print(a - b) print(a * b) print(a / b) # divide returns a float print(a // b) # double slash means divide but return a int print(a % b) print(a + b / 3 - 4 * 12) print((((a + b) / 3) - 4) * 12) # correct answer = 12 parrot = "Norwegian Blue" print(parrot[3]) # start at zero print(parrot[-1]) # start at end of string print(parrot[0:6]) # get a range, don't include 6 print(parrot[:6]) # start at beginning to 6 print(parrot[6:]) # start at 6 until end print(parrot[0:6:2]) # start at 0 up to 6 skip 2 print("1, 2, 3, 4, 5, 6, 7"[0::3]) # print just the numbers string1 = "he's " string2 = "probably" print(string1 + string2) print("hello " * 5) today = "Friday" print("day" in today) # returns boolean print("parrot" in today) # returns boolean # use a slash to split a line input_prompt2 = "this is a very long sentence to be used in a user prompt and" \ "will probably be flagged by Pycharm, so we can use two different method as below" # the preferred way is to use brackets input_prompt3 = ("this is a very long sentence to be used in a user prompt and" "will probably be flagged by Pycharm, so we can use two different method as below") |
Python has various arithmetic and similar expressions, again these are common across most programming languages. A sequence of operands and operators, like a + b - 5, is called an expression. Python supports many operators for combining data objects into expressions. Precedence ius apply and i will talk about this more in the operators session. You can use numbers, strings, booleans values and other object types in expressions.
Expression examples | a = 12 b = 3 x = (a + b / 3 - 4 * 12) x = (((a + b) / 3) - 4) * 12) # using brackets to make use predence is correct, correct answer = 12 myAge = 21 age = 'You will be ' + str(int(myAge) + 1) + ' next year.' # you can use expressions in strings |
Some of the examples above have already used, I have also added some examples of the format() method which formats the specified value(s) and insert them inside the string's placeholder. I have also shown some examples of version 2 just for reference, use the new way going forward.
Printing examples | print('Hello World') print(1 + 2) print(7 * 6) print() print("The End") print("Python's strings are easy to use") print('We can even include "quotes" in strings') print("hello" + " world") # using variables greeting = "Hello" name = "Paul" print(greeting + name) print(greeting + ' ' + name) #greeting = 'Hello' #name = input("Please enter your name: ") #print(greeting + ' ' + name) splitString = "\tThis string has been \nsplit over\n several \nlines" print(splitString) print('The pet shop owner said "No, no \'e\'s uh,...he\'s resting"') print("The pet shop owner said \"No, no 'e's uh,...he's resting\"") print('''The pet shop owner said "No, no 'e's uh,...he's resting"''') print("""The pet shop owner said "No, no 'e's uh,...he's resting" """) # notice the space anotherSplitString = """This string has been split over several lines""" print(anotherSplitString) |
String formatting examples | age = 24 print("My age is " + str(age) + " years") print("My age is {0} years".format(age)) city = "Milton Keynes" print("My age is {0} years and lives in {1}".format(age, city)) # age = {0} and city = {1} # Old way and no longer used depreciated - Python 2 print("My age is %d years and lives in %s" % (age, city)) for i in range(1, 12): print("No, %2d squared is %d and cubed is %d" % (i, i ** 2, i ** 3)) print("PI is approx %12f" % (22 / 7)) print("PI is approx %12.50f" % (22 / 7)) # the new way and should use going forward for i in range(1, 12): print("No, {0:2} squared is {1:<4} and cubed is {2:<4}".format(i, i ** 2, i ** 3)) print("PI is approx {0:12}".format(22 / 7)) print("PI is approx {0:12.50}".format(22 / 7)) |
Booleans are straight forward, you only have true or False, and are use mainly in control flow (IF, where, etc)
Boolean examples | print("True = {0}".format(True)) print("False = {0}".format(False)) print("not True = {0}".format(not True)) print("not False = {0}".format(not False)) print("0 = {0}".format(bool(0))) print("1 = {0}".format(bool(1))) print("0.0 = {0}".format(bool(0.0))) print("0.1 = {0}".format(bool(0.1))) print("1.0 = {0}".format(bool(1.0))) print("\"hello\" = {0}".format(bool("Hello"))) print("\'hello\' = {0}".format(bool('Hello'))) |
Python is used in many data science areas there are a number of built-in numeric functions plus you have the option of importing numeric modules from pypi.
Python has a special basic data type that defines a single special data object called None. As the name suggests, None is used to represent an empty value.
None example | x = None print(x) if x: print("Do you think None is True") else: print("None is not True...") |