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

Python - Basics - Dr. CHADI

The document discusses Python basics including data types, built-in functions, and modules. It covers primitive data types like integers, floats, booleans and strings. Built-in data structures include lists, sets, dictionaries and tuples. Strings and tuples are immutable while lists, sets and dictionaries are mutable. Built-in functions like print(), input(), len(), max(), min() and sum() are demonstrated. Popular modules like os, datetime and random are introduced for operating system operations, date/time functions, and random number generation respectively.

Uploaded by

m.shaggyspringer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python - Basics - Dr. CHADI

The document discusses Python basics including data types, built-in functions, and modules. It covers primitive data types like integers, floats, booleans and strings. Built-in data structures include lists, sets, dictionaries and tuples. Strings and tuples are immutable while lists, sets and dictionaries are mutable. Built-in functions like print(), input(), len(), max(), min() and sum() are demonstrated. Popular modules like os, datetime and random are introduced for operating system operations, date/time functions, and random number generation respectively.

Uploaded by

m.shaggyspringer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

10/6/23, 9:07 AM 1.2_python_basics - Dr.

CHADI - Jupyter Notebook

1. About Python (high level, easy, most popular, etc.)

2. Installation (Python.exe and jupyter as IDE)

3. built-in data types


In [17]:  # built-in fcts (fct internes)
print('jezdbihiefv')

jezdbihiefv

In [1]:  # primitive types


'''
int float bool string
'''

a = 1
b = 2.5
c = True
d = 'abc'

In [2]:  type(b)

Out[2]: float

In [3]:  type(d)

Out[3]: str

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 1/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [4]:  # built-in data structures


'''
lists, set, dict = Mutable
string and tuple = immutable
'''

a = [1, 2.5, 3, 'mohamed']
print(type(a))

b = {1, 2, 3, 'mohamed', 2, 3}
print(type(b))

c = {1:'a', 2:'b', 3:'c', 4:'mohamed', 'kkkk': 222, 'mol1': [1, 2, 3, 4]}
print(type(c))

d = (1, 2, 3, 'mohamed')
print(type(d))

<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>

In [5]:  d[0] = 'amine' #error, because it's immutable

-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[5], line 1
----> 1 d[0] = 'amine' #error, because it's immutable

TypeError: 'tuple' object does not support item assignment

In [22]:  e = "ab cdef" #strings are also immutable


e

Out[22]: 'ab cdef'

In [23]:  e[0]

Out[23]: 'a'

In [24]:  e[0] = 'z' #error

-------------------------------------------------------------------------
--
TypeError Traceback (most recent call las
t)
Cell In[24], line 1
----> 1 e[0] = 'z' #error, because it's immutable

TypeError: 'str' object does not support item assignment

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 2/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [6]:  a = "aabcd"

a.replace('a', 'h')

Out[6]: 'hhbcd'

In [28]:  a = 'mundiapolis' #start, end, step (signe = le sens)


a[::-1]

Out[28]: 'silopaidnum'

In [ ]:  ​

In [ ]:  ​

In [ ]:  ​

In [1]:  k = [1, 2, 3, 4, 5]
v = ["a", "b", "c", "d", "e"]

d = dict(zip(k, v))
d

Out[1]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

In [ ]:  ​

4. built-in functions
In [4]:  a = input("entrer la valeur de a:")

entrer la valeur de a:33

In [5]:  a

Out[5]: '33'

In [31]:  a = int(a)
type(a)

Out[31]: int

In [31]:  print("mundiapolis")

mundiapolis

In [1]:  # combine different types inside print


n = 10
print("J'ai eu", n, "sur", n)

J'ai eu 10 sur 10

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 3/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [1]:  mylist = ["a", "b", "c", "z", "d"]


x = len(mylist)
x

Out[1]: 5

In [12]:  sorted(mylist)

Out[12]: ['a', 'b', 'c', 'd', 'z']

In [13]:  round(5.76543, 2)

Out[13]: 5.77

In [2]:  a = [2, 1, 3, 8]

In [3]:  max(a)

Out[3]: 8

In [4]:  min(a)

Out[4]: 1

In [5]:  x = sum(a)
x

Out[5]: 14

In [ ]:  ​

5. built-in modules
see all here: https://docs.python.org/3/py-modindex.html (https://docs.python.org/3/py-
modindex.html)

------------- 5.1 os (operating system)

In [3]:  import os
cwd = os.getcwd()
print("Current working directory:", cwd)

Current working directory: C:\Users\Amine\Desktop\mundiapolis\_les_cours


\S1\Analyses de données et stats\____my_stats_course\séance 2

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 4/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [18]:  import os

path = 'my_dir'

os.makedirs(path, exist_ok=True)

In [19]:  file_name = path + "/" + "example_1.txt"


file_name

Out[19]: 'my_dir/example_1.txt'

In [20]:  with open(file_name, 'w') as file:


file.write(" Hello word 1 \n")
file.write(" Hello word 2 \n")
file.write(" Hello word 3 \n")

file.close()

In [21]:  import os
files = os.listdir(path)
print(files)

['example_1.txt']

In [22]:  fname = path + '/' + files[0]



fname

Out[22]: 'my_dir/example_1.txt'

In [26]:  path = 'mundia_dir' #empty folder



os.rmdir(path) #remove only if it's empty

In [28]:  ## to remove a directory even if it's not empty, use:



import shutil

path = 'my_dir'

try:
shutil.rmtree(path)
print(f"Directory '{path}' and its contents have been removed.")
except Exception as e:
print(f"Error: {e}")

Directory 'my_dir' and its contents have been removed.

In [ ]:  ​

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 5/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

-------- 5.2 datetime

In [37]:  from datetime import date



today = date.today()
print("Today is: ", today)

Today is: 2023-10-03

In [38]:  from datetime import date


today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Current year: 2023


Current month: 10
Current day: 3

---------- 5.3 random

In [50]:  import random



print(random.random()) # Random float: 0.0 <=
print(random.uniform(2.5, 10.0)) # Random float: 2.5 <=
print(random.randrange(10)) # Integer from 0 to 9 i
print(random.randrange(0, 101, 2)) # Even integer from 0 t
print(random.choice(['win', 'lose', 'draw'])) # Single random element
print(random.sample([10, 20, 30, 40, 50], k=4)) # Four samples without

0.2653782615653967
9.967925911386839
4
70
draw
[40, 50, 30, 20]

5.4 ----------- zipfile

In [51]:  # make a file first


file_name = "example.txt"
try:
with open(file_name, 'w') as file:
# Write some content to the file
file.write("This is a text file created with Python.\n")
file.write("You can write multiple lines of text here.\n")
file.write("This is the last line of text.")
print(f"Text written to {file_name}")
except IOError: #in case the folder doesn't give access right to modify
print(f"An error occurred while creating/writing to {file_name}")

Text written to example.txt

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 6/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [11]:  from zipfile import ZipFile



# write zipfile
with ZipFile('test.zip', 'w') as myzip:
myzip.write(file_name)

In [16]:  # read zipfile


with ZipFile('test.zip') as myzip:
with myzip.open(file_name) as myfile:
print(myfile.read())

b'This is a text file created with Python.\r\nYou can write multiple line
s of text here.\r\nThis is the last line of text.'

In [17]:  print("aaaa\r\nbbbb") #\r\n next ligne

aaaa
bbbb

6. Conditions (if, try)


In [37]:  # if elif else
a = 1

if a == 0:
print("aaa")
elif a == 1:
print("bbb")
elif a == 2:
print("ccc")
else:
pass

bbb

In [9]:  print(x) # this will not be executed because x is not defined


# if there was no try and except it will give error

-------------------------------------------------------------------------
--
NameError Traceback (most recent call las
t)
Cell In[9], line 1
----> 1 print(x) # this will not be executed because x is not defined
2 # if there was no try and except it will give error

NameError: name 'x' is not defined

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 7/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [13]:  # try and except, program continue even when there are errors
try:
print(x)
except:
print("x is not defined")

x is not defined

7. loops (les boucles)


In [1]:  # x = 1
# while x==1:
# print("aaaaa")

In [39]:  # simple loop


n = 10
for i in range(n):
print(i)

0
1
2
3
4
5
6
7
8
9

In [3]:  # simple loop


for i in range(3, 7):
print(i)

3
4
5
6

In [40]:  mylist = [1, 3, 6, 8, 10]


jj = []
for element in mylist:
hh = element + 8
jj.append(hh)

In [15]:  jj

Out[15]: [9, 11, 14, 16, 18]

In [10]:  mylist = [1, 3, 6, 8, 10]

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 8/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [11]:  for fff, n in enumerate(mylist):


print(fff, n)

0 1
1 3
2 6
3 8
4 10

In [11]:  letters = ['a', 'b', 'c']


numbers = [0, 1, 2]

for l, n in zip(letters, numbers):
print(l, n)

a 0
b 1
c 2

In [ ]:  ​

8. define your function

In [3]:  def myf(x):


y = x+5
return y

t = myf(5)
t

Out[3]: 10

9. Classes
In [31]:  a = [1, 2, 3, 5]
print(type(a))

<class 'list'>

In [ ]:  ​

In [12]:  class user:


def __init__(self, nom, age):
self.color = "rouge"
self.name = nom
self.age = age

def sayhello(self):
print(self.color)
print("hello ", self.name)
print("your age is", self.age)

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 9/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [13]:  Mohamed = user("Mohamed", "20")

In [ ]:  Mohamed. #tabulation pour afficher les attributs et méthodes

In [12]:  Mohamed.sayhello()

rouge
hello Mohamed
your age is 20

In [ ]:  ​

In [37]:  # classes:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Hello my name is John

In [18]:  # héritage:
class Vehicle:
def __init__(self, a, b, c, d, e, f):
self.couleur = a
self.pos = b
self.vitesse = c
self.nbr_portes = d
self.nbr_roues = e
self.taille = f

def transporter(self):
return self.pos + self.vitesse

V = Vehicle("black", 4, 80, 4, 4, 3)
V.transporter()

Out[18]: 84

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 10/11


10/6/23, 9:07 AM 1.2_python_basics - Dr. CHADI - Jupyter Notebook

In [19]:  class Bus(Vehicle):


def __init__(self, a, b, c, d, e, f):
super().__init__(a, b, c, d, e, f)

def transporter(self, stops):


res = self.pos + self.vitesse - stops
return res

B = Bus("yellow", 4, 80, 4, 4, 3, 4)
B.transporter(10)

Out[19]: 74

localhost:8888/notebooks/1.2_python_basics - Dr. CHADI.ipynb 11/11

You might also like