Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50654 views
1
# CoCalc Examples Documentation File
2
# Copyright: CoCalc Authors, 2015
3
# License: Creative Commons: Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)
4
---
5
language: python
6
category: Language / Tutorial
7
---
8
title: Hello World
9
descr: The "Hello World" program
10
code: print("Hello World")
11
---
12
title: Objects/Instances
13
descr: >
14
One of the most fundamental building blocks of a Python program are "Objects".
15
They are concrete "instances" of a certain type.
16
As a real-world analogue, you can think of a pair of shoes as a type,
17
and the specific example of shoes you are wearing right now as an instance of that type.
18
Your specific shoes also have certain properties, like a specific size, a color, a make, maybe even a serial number, etc.
19
The type "shoe" would only describe these properties, while a specific pair has concrete values.
20
More about this at a later point.
21
code: |
22
"hello" # creates an object of type "string" with the value "hello"
23
5.5 # the floating point number 5.5
24
---
25
title: Variables
26
descr: >
27
A variable is a name for an object.
28
It is done via this syntax:
29
30
```
31
variablename = object
32
```
33
34
`print` is a function to show the object as a string.
35
code: |
36
x = 1
37
y = x + 1
38
print(x)
39
print(y)
40
---
41
title: Print Data
42
descr: The "Hello World" program printing some values.
43
code: |
44
x = "Hello"
45
y = 2.123456789
46
print("%s World, y = %f" % (x, y))
47
print("x={x}, y={y:.3f}".format(**locals()))
48
---
49
title: Expressions
50
descr: >
51
Expressions are constructued by combining several object.
52
Usually, they can be evaluated, because operators and functions are used to build the expression.
53
54
Furthermore, use parenthesis to control the order of the evaluation!
55
code: |
56
print((5 + 6) * 11)
57
z = 3 # assign a variable, then use it in an expression
58
print((1 + z)**2)
59
from math import sqrt
60
print(sqrt(z))
61
---
62
title: Functions
63
descr: >
64
A function call is one of the most basic levels of abstraction.
65
A common subroutine of evaluations is run with varying initial arguments.
66
The `return` statement is very important: data flows back to where the functions has been called.
67
code: |
68
def function1(x, y):
69
z = 10 * x + y
70
return z
71
72
print(function1(4, 5))
73
print(function1(1,-1))
74
---
75
title: Functions (nested)
76
descr: >
77
It is fine to nest functions in more complex expressions.
78
code: |
79
def foo(x):
80
return 2*x+1
81
print(foo(1 + foo(3)) - 2)
82
---
83
title: "Data Structure: List"
84
descr: >
85
To organize information in a program, data structures are here to help.
86
A very basic one is an ordered collection of arbitrary objects.
87
Such a `list` object is constructed by listing objects between `[ ... ]` delimited by a commas `,`.
88
code: |
89
x = [42, "Hello", [1,2,3]]
90
print(x)
91
x.append("World")
92
print(x)
93
---
94
title: "List access"
95
descr: >
96
To access elements at a specific location, use `[]` brackets with the index number.
97
Counting starts at zero and negative values index in the other direction from the end.
98
99
Also be aware, that like with functions lists might also be nested.
100
code: |
101
l = [4, 5, -1, 2]
102
print(l[1])
103
print(l[-1])
104
print(l[0] + 2 * l[1])
105
---
106
title: "Control Structure: if/else"
107
descr: >
108
Code is executed line by line, but it can be directed to flow in more complex ways.
109
An `if` decides if a block of code is executed, or – together with `else` – decides between two blocks.
110
111
In Python, blocks are indented by spaces (usually two or four) from the beginning for the line.
112
Nested blocks are indented multiple times (4 or 8 times, etc.).
113
code: |
114
x = -8
115
print('x is %s' % x)
116
if x > 0: # note the colon!
117
print('x is positive')
118
else:
119
print('x is not positive')
120
print('this line is always executed!')
121
122
# TODO: change the -8 to a positive value and see how the flow changes
123
---
124
title: "Control Structure: for"
125
descr: >
126
A `for`-loop repeates a block of code by consecutively assigning a local variable with values from a list or iterator.
127
code: |
128
for i in ['a', 'c', 'abc', 'x']:
129
print("variable i is %s" % i)
130
for j in range(3):
131
for k in range(5):
132
print("j: {} + k: {} = {}".format(j, k, j+k))
133
---
134
title: "Data Structure: Dict(ionary)"
135
descr: >
136
A dictionary is an mapping of (immutable) objects to arbitrary objects.
137
The immutable objects are called "keys" and are most commonly numbers, strings or tuples.
138
139
To set a key in a dictionary, assign it like this: `var["x"] = 42`.
140
141
Later, accessing a dictionary is similar to a list:
142
`var["x"]` retrieves the entry with the name `"x"` from the dictionary referenced by the variable `var`.
143
As by the assignment above, the retrived object is the number `42`.
144
code: |
145
d = dict()
146
d[42] = "The Answer"
147
d["what"] = ["this", "and", "that"]
148
d[(4, 2)] = 99
149
print(d[42])
150
print(d[(4,2)])
151
print(d.keys())
152
print(42 in d)
153
---
154
title: "Classes"
155
descr: >
156
A `class` is the usual way how someone can define a custom `type`.
157
We define a class `Shoe` with a specific color and size.
158
Under the hood, a class is like a dictionary but with some extras and an enhanced syntax.
159
Additionally, "methods" are functions in a class.
160
They are used to compute a derived value from the data of an instantiated object.
161
The method `__init__` is special: it is called upon instantiation and used to set the values of the object.
162
code: |
163
class Shoe(object):
164
def __init__(self, size, color):
165
self.size = size
166
self.color = color
167
def double(self):
168
"""return twice the size of the shoe"""
169
return 2 * self.size
170
171
# instantiation:
172
s1 = Shoe(40, "green")
173
s2 = Shoe(43, "black")
174
print(s1.color)
175
print(s2.double())
176
print(type(s2)) # the type of the object referenced by s1 is "Shoe"
177