0% found this document useful (0 votes)
22 views

002 Programming-in-Python

The document introduces Python as a programming language that is syntactically simple, capable of powerful expression, fast for computation, popular, mature, and has lots of support libraries. It describes Python as an interpreted language where scripts are executed sequentially by the Python interpreter. The document also outlines some of Python's basic data types like integers, floats, booleans, and strings, and how variables can be assigned and values converted between types.

Uploaded by

Bhavesh Jha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

002 Programming-in-Python

The document introduces Python as a programming language that is syntactically simple, capable of powerful expression, fast for computation, popular, mature, and has lots of support libraries. It describes Python as an interpreted language where scripts are executed sequentially by the Python interpreter. The document also outlines some of Python's basic data types like integers, floats, booleans, and strings, and how variables can be assigned and values converted between types.

Uploaded by

Bhavesh Jha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Python

Let’s Start Programming


Why Python
NB:
Programming is introduced in UK primary Schools
From about age 8
• Syntactically Simple Many use Python

• Capable of powerful expression


• Fast for computation
• Popular, Mature
• Lots of support, Libraries etc (Ecosystem)
Python Interpreter
• A Python Script is a file named *.py
“Hello World”
• Executed in sequence by the Python Interpreter The simplest first program
• Allows the creation of more complex algorithms
• Python can also be directly entered into the interpreter:

Type our expression


Outputs the result
Awaits next instruction
print( "------------------------" )
What does it look like?
print( "Testing all compilers..." )
print( "------------------------\n" )
for compiler in compilers:

# Try to extract student name from compiler path if we can


searchStr = "08348 Compilers Assessment"
nameIndex = compiler.find(searchStr)
prelen = len(searchStr)
studentName = ""
if nameIndex > 0:
# Get the path and print the name
studentName = compiler[nameIndex + prelen + 1:compiler.find(S, nameIndex + prelen + 2)]
reportEntry(report, studentName)

reportEntry(report, str_join( "Testing compiler: ", compiler) )


if not os.access(compiler, os.X_OK):
reportEntry(report, str_join( "Cannot find compiler: ", compiler) )
continue # Skip it
# Check for plain localname, make relative path for shell
if os.path.basename(compiler) == compiler:
compiler = str_join(".", S, compiler)

# Test function
passed = 0

# Run all tests


numExecutedTests = 0
for f in testSPLfiles:
result = runTest(compiler, f, report)
if result > 0:
passed += 1
if result == 2:
numExecutedTests += 1

# Output summary
if studentName != "":
reportEntry(report, studentName + "'s compiler ")
percent = passed * 100 / len(testSPLfiles)
reportEntry(report, str_join("Passed ", passed, " tests out of ", len(testSPLfiles), " (", percent, "%)") )
#reportEntry(report, "Executed " + numExecutedTests + " test programs successfully")
compilersTested += 1
Python Types

• Python Object have types


• Called classes
• Type => the nature of the thing to be stored
• The type determines what can be done with an object
• There are basic “built-in” classes
• Can build own object classes from these
Basic Classes

• int – whole numbers: -2, -1, 0, 1, 2


• float – “real” numbers: 1.412, 0.32 (also complex)
• bool – true or false
• str – “Brian”, “Hello World”
• NoneType – None : a special type for nothing!
What class am I?
• This is useful for to determine if a calculation didn’t provide output
• To interrogate what type an object has, we can use type() on it.

What type(5) is evaluated as.


Type Conversion

• We can convert from one type of object to another by casting


• float(5) converts an integer, 5, to the float 5.0.
• int(3.141) converts the float, 3.141, to the integer 3.
• We can also do stranger casting to.
• Caution: Some casts don’t make sense! (Semantics)
• E.g. int(“bob”) → The interpreter will error and say ValueError!
• E.g. int(“5”) → Converts the string “5” to the integer 5.
Operators

• With these types we can do things.


• +, -, *, / operators for plus, minus, multiply, and divide.
• **, % operators for exponent , and modulo (The remainder of division)
• Examples:
A / B → Division A % B → Remainder
• A + B → Summation Outputs float A ** B → AB
• A – B → Minus
• A * B → Product
• Integer yields integer, float yields float.
Operator precedence

• From School: BODMAS or PEMDAS


• Calculate 3 * 4 ** 2 : is it 144 or 48?

• Calculate 6 - 4 / 2 : is it 1 or 4?

• Use parentheses for clarity 6 – ( 4/ 2)


Variable Assignment

• We can store results in named variables (memory of the computer)


pi = 3.14159265358979
pi =
Variable name Value
79
tau
tau == pi
pi **2 2
Some more operations
• Comparison
• <, >, ==, !=, >=, <= (deliver True or False)
• For completeness
• Bitwise ~ (negation), & (and), | (or), ^ (xor), <<, >> (bit shift)
• For Boolean logic a b not b a and b a or b
• and, or, not
True True False True True
• Details in the documentation True False True False True
False True False False True
False False True False False
Choosing Variable Names

• Choose a name that describes the result


• Helps the human understand the program
• Python has a list of protected keywords which we can’t name variables
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while
Warning to Mathematicians

• The = symbol is not


• Denoting equivalence
• Denoting equality
• Denoting Identity
• It is not an equation to be solved
• It is just copying a value into memory
• That value can be overwritten later
X 10

Variable Assignment “bob”

• We can re-use the variable name for another assignment operation.


• Rebind the variable to a new value.
• Old one still exists in computer memory
• May get cleaned up later (Garbage Collected)
• Rebinding of variable doesn’t have to be of the same type.
• Usually advised, otherwise you could run into semantics issues
(“But I thought x was an int!”)
X = 10 X = “bob”
Known as Dynamic Typing
Two commands

• The python function: print


• Use it to output the result
• Use input to get values from keyboard
>>> print(True and True)
True
>>> print(True or False)
True
>>> print(1|2)
3
So now go program

You might also like