Python Basics
Contents
Python Basics#
Python is ** dynamically typed**
Type given at the time of assignment
Python is strongly typed
You can’t change the type
You can use the variable name for a different type of object.
Variables#
a = [1]
b = a
print(b) # [1]
b.append(2)
print(a) # [1,2]
[1]
[1, 2]
test = "Hello"
print(test)
test = 123
print(test)
Hello
123
test = "3"
print(test) # 3 IT IS CLASSED AS AN INT
test2 = str("3")
print(test2) # 3 IT IS CLASSED AS A STRING
3
3
Data Structures#
nested_tuple = (1,2,3),(4,5,6)
# Cool loops
[x[1] for x in nested_tuple]
[2, 5]
YOU CAN DO THE OBJECT ASSIGNING THINGY IN PYTHON
normal_tuple = 1,2,3
a,b,c = normal_tuple
print(a, b, c)
1 2 3
this_is_a_list = list([1,2,3,4,5])
this_is_a_list.extend([7,8,9])
this_is_a_list
[1, 2, 3, 4, 5, 7, 8, 9]
a_tuple = (1,2,3,4,5)
tuple_into_list = list(a_tuple)
tuple_into_list
[1, 2, 3, 4, 5]
string = """Like an echo in the forest
The day will come back around
As if nothing happened
Yeah, life goes on
Like an arrow in the blue sky
Another day flying by
On my pillow, on my table
Yeah, life goes on
Like this again"""
string_as_list = string.split()
string_as_list.sort(key=len)
string_as_list
['an',
'in',
'As',
'if',
'on',
'an',
'in',
'by',
'On',
'my',
'on',
'my',
'on',
'the',
'The',
'day',
'the',
'sky',
'day',
'Like',
'echo',
'will',
'come',
'back',
'life',
'goes',
'Like',
'blue',
'life',
'goes',
'Like',
'this',
'Yeah,',
'arrow',
'table',
'Yeah,',
'again',
'forest',
'around',
'flying',
'nothing',
'Another',
'pillow,',
'happened']
Loops#
i = 0
while i < 10:
print(i)
i +=1
0
1
2
3
4
5
6
7
8
9
a_list = ['my','stomach','hurts']
for x in a_list:
print(x)
my
stomach
hurts
for x in range(0,11):
print(x)
0
1
2
3
4
5
6
7
8
9
10
Functions#
def a_function(text):
print("This function takes in the parameter " + text)
a_function("meep")
This function takes in the parameter meep
Files#
f = open("testfile.txt", "r") # read
#a - append
#w - write
#x - create new data file, if exists then error
#t - text file
#b - binary data
data = f.read()
f.close()
words = data.split(" ")
words
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[13], line 1
----> 1 f = open("testfile.txt", "r") # read
2 #a - append
3 #w - write
4 #x - create new data file, if exists then error
5 #t - text file
6 #b - binary data
8 data = f.read()
File /opt/hostedtoolcache/Python/3.8.14/x64/lib/python3.8/site-packages/IPython/core/interactiveshell.py:282, in _modified_open(file, *args, **kwargs)
275 if file in {0, 1, 2}:
276 raise ValueError(
277 f"IPython won't let you open fd={file} by default "
278 "as it is likely to crash IPython. If you know what you are doing, "
279 "you can use builtins' open."
280 )
--> 282 return io_open(file, *args, **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: 'testfile.txt'