You are on page 1of 13

1.

An expression is a combination of values (or variables, operators,


calls to functions - you will learn about them soon) which evaluates to a
value, e.g., 1 + 2.

2. Operators are special symbols or keywords which are able to operate


on the values and perform (mathematical) operations, e.g.,
the * operator multiplies two values: x * y.

3. Arithmetic operators in
Python: + (addition), - (subtraction), * (multiplication), / (classic
division - always returns a float), % (modulus - divides left operand by
right operand and returns the remainder of the operation, e.g., 5 % 2 =
1), ** (exponentiation - left operand raised to the power of right
operand, e.g., 2 ** 3 = 2 * 2 * 2 = 8), // (floor/integer
division - returns a number resulting from division, but rounded down to
the nearest whole number, e.g., 3 // 2.0 = 1.0)

4. A unary operator is an operator with only one operand, e.g., -1,


or +3.

5. A binary operator is an operator with two operands, e.g., 4 + 5,


or 12 % 5.

6. Some operators act before others - the hierarchy of priorities:

 unary + and - have the highest priority


 then: **, then: *, /, and %, and then the lowest priority:
binary + and -.

7. Subexpressions in parentheses are always calculated first, e.g., 15 -


1 * (5 * (1 + 2)) = 0.

8. The exponentiation operator uses right-sided binding, e.g., 2 **


2 ** 3 = 256.
a = 10
b = "string"
c = [1,2,3,4]
d = [[1,2], [3,4], [5,6]]

print(a)
print(b[0])
print(c)
print(d)

# int
a = 10
print(type(a))

# float
b = 9.87
print(type(b))

# str
c = "string"
print(type(c))

# list
d = [1, 2, 3, 4, 5]
print(type(d))

# bool
e = True
print(type(e))

# tuple
f = (1, "A", [1, 1, 1])
print(type(f))

# set
g = {1, 2, 2, 3, 3, 4, 5}
print(g) # doesn't show duplicates
# set ex: 1
countries = ["MD", "MD", "RO", "RU", "RO"]
countriesSet = set(countries)
countries = list(countriesSet)
print(countries)

# dict
person = {
"name": "Elena",
"age": 21
}

print(type(person))
print(person)
print(person['name'])

# None
A = None
print(type(A))
# we do not type null

CODE = "123"
print(CODE)
CODE = "1"
print(CODE)
# write a variable with uppercase it will mean constant

# if
if 2 > 0 and (3 > 0 or 1 == 1):
# if 1 > 0:
print("ok")
print("ok")
print("ok")

A = 10
if A is not None:
print("A: ", A)
X = 100
if X > 50:
print(f"X is {X}")

name = input("Enter your name:")


age = int(input("Enter your age: "))
b = bool(input("->")) # 1 -> True 0 -> False

if age > 25:


print(f"{name} is an adult")
elif age > 16:
print(f"{name} is a youngster")
else:
print(f"{name} is a child")

# exercise

clientName = input("Enter your name")


clientRate = int("Enter your rate")

if clientRate > 1:
print(f"{clientName} is a first buyer")
elif clientRate > 2:
print(f"{clientName} is a tactic buyer")
else:
print(f"{clientName} is an elit buyer")

myName = "Elena"
print(len(myName))

print(myName.upper())
print(myName.lower())

myCity = " Athens"


print(myCity.strip()) # takes off space
answers = "Chisinau,Moldova,Iasi,Comrat,Cahul"
answersArr = answers.split(",")
print(answersArr)

cars = ["Honda", "Audi", "Toyota"]


carsStr = "-".join(cars)
print(carsStr)

text = "the apple is green, the apple was green, the apple will always be
green"
print(text.count("apple"))

texts = ["green apple", "red apple", "yellow apple is the green basket" "the
apples are on 24/24"]
for text in texts:
if text.count("green") > 0:
print(text)

myHouse = "London, str. Queens avenue"


print(myHouse.replace("London", "Athens"))
print(myHouse.find("London")) # it also counts the tabs,

print(myHouse.find("Londons")) # it goes -1 when something doesn't exist in


the string

import numpy as np

arr = np.array([1, 2, 3])


print(arr)

zeros_arr = np.zeros(10)
print(zeros_arr)

ones_arr = np.ones((2, 10))


print(ones_arr)

# arrange(startIdx, endIdx, step)


range_arr = np.arange(1, 10, 2)
print(range_arr)
lin_space_arr = np.linspace(0, 1, 5)
print(lin_space_arr)

rand_arr = np.random.rand(2, 2)
print(rand_arr)
# [[0.32634963 0.3499444 ]
# [0.52672999 0.80529246]]

# de la 0 pana la
rand_n_arr = np.random.randn(10)
print(rand_n_arr)

random_arr = np.random.uniform(1, 10, 5)


print(random_arr)

random_arr_int = np.random.randint(1, 10, 5)


print(random_arr_int)

random_arr_int2 = np.random.randint(1, 10, (10, 10))


print(random_arr_int2)

reshaped_arr = np.reshape(random_arr_int2, (4, 25))


print(reshaped_arr)

sum_arr = np.sum(reshaped_arr)
print(sum_arr)

# media aritmetica
mean_arr = np.mean(reshaped_arr)
print(mean_arr)

min_val = np.min(reshaped_arr)
print(min_val)

max_val = np.max(reshaped_arr)
print(max_val)

min_idx = np.argmin(reshaped_arr)
print(min_idx)

max_idx = np.argmax(reshaped_arr)
print(max_idx)

# unirea a doua tablouri:


a = [1, 2, 3]
b = [4, 5, 6]
c = np.concatenate((a, b,[1, 0, 1]))
print(c)

# x = [1, 1, 1, 2, 3, 3, 4, 5, 5, 5]
# uniqueX = np.unique(x)
# print(uniqueX)
x = [1, 1, 1, 2, 3, 3, 4, 5, 5, 5]
uniqueX, counts = np.unique(x, return_counts=True)
print(uniqueX)
print(counts)

is_present = np.isin(3, x)
print(is_present)

myArr = np.array((10, 21, 21, 16, 19))


where1 = np.where(myArr > 10, myArr, 0) # 0 = element default
print(where1)

# FILTRU obisnuit:
xArr = [1, 2, 3, 4, 5]
oddNumbers = [a for a in xArr if a % 2 == 1]
print(oddNumbers)

evenNumbers = list(filter(lambda n: n % 2 == 0, xArr))


print(evenNumbers)

class Person:
def __init__(self, name, lastname, birthYear, email, country):
self.name = name
self.lastname = lastname
self.birthYear = birthYear
self.email = email
self.country = country
class Student(Person):
def __init__(self, name, lastname, birthYear, email, country, school, grade,
friends):
super().__init__(name, lastname, birthYear, email, country)
self.school = school
self.grade = grade
self.friends = friends

def __str__(self):
return f"Student: {self.name} {self.lastname}\nBirth Year:
{self.birthYear}\nEmail: {self.email}\nCountry: {self.country}\nSchool:
{self.school}\nGrade: {self.grade}\nFriends: {', '.join(self.friends)}"

students = [
Student("Name", "Lastname", 2000, "email@gmail.com", "country",
"school", 9.99, ["Friend1", "Friend2"]),
Student("Ion", "Bors", 2004, "ionbors@mail.ru", "Moldova", "Best school",
5.55, []),
Student("Fang", "Ai", 1999, "fangaichinese@chinese.cn", "China", "China
school", 10,
["Mao Zedong", "Other chinese friend"]),
Student("John", "Doe", 2000, "john.doe@example.com", "USA", "Example
School", 10, ["Kim Chen", "American friend"]),
Student("Alice", "Smith", 1999, "alice.smith@example.com", "USA",
"School2", 9, ["Kim", "Fang Ai", "Ion Bors"]),
Student("Bob", "Johnson", 2001, "bob.johnson@example.com", "USA",
"School3", 7, ["Name Lastname"]),
Student("Eva", "Williams", 2002, "eva.williams@example.com", "USA",
"School4", 9.43, ["Friend1", "other friend"]),
Student("Emma", "Brown", 1998, "emma.brown@example.com", "USA",
"School5", 10, ["Italian Friend", "Adolph"]),
Student("Michael", "Davis", 2003, "michael.davis@example.com", "USA",
"School6", 9.7,
["Chinese Friend", "Friend3 with no name", "Friend4"]),
Student("Sophia", "Johnson", 2001, "sophia.johnson@example.com",
"USA", "School7", 8.34, ["Friend1"]),
Student("Liam", "Miller", 2000, "liam.miller@example.com", "USA",
"School8", 9.75,
["Emma Brown", "Sophia", "friend", "Last friend"])
# map (fun, array)
studentsNames = list(map(lambda student: student.name + "avich",
students))
print(studentsNames)

studentEmails = list(
map(lambda student: student.email + ' ' + student.name if
student.email.endswith(
"@gmail.com") else "Maybe fake email " + student.email, students))
print(studentEmails)

def lowerMarck(student):
student.grade = student.grade - 1
return student

newStudents = list(map(lambda student: lowerMarck(student), students))


for student in newStudents:
print(student)

smartStudents = list(filter(lambda student: student.grade > 8, students))


for student in smartStudents:
print(student)

class Car:
def __init__(self, mark, model, year):
self.mark = mark
self.model = model
self.year = year

cars = [
Car("Toyota", "Yaris", 2009),
Car("Toyota", "Camry", 2019),
Car("Audi", "Q5", 2023)
]
toyotaCars = list(filter(lambda c: c.mark == "Toyota", cars))
for car in toyotaCars:
print(f"Mark: {car.mark}, Model: {car.model}, Year: {car.year}")
# -> Mark: Toyota, Model: Yaris, Year: 2009
# -> Mark: Toyota, Model: Camry, Year: 2019

lessThan2019 = list(filter(lambda c: c.year < 2019, cars))


for car in lessThan2019:
print(f"Mark: {car.mark}, Model: {car.model}, Year: {car.year}") # -> Mark:
Toyota, Model: Yaris, Year: 2009

myFilters = list(
filter(lambda c:
(c.mark == "Toyota"
or c.mark == "Audi")
and c.year >= 2019, cars)
)
for car in myFilters:
print(f"Mark: {car.mark}, Model: {car.model}, Year: {car.year}")
# -> Mark: Toyota, Model: Camry, Year: 2019
# -> Mark: Audi, Model: Q5, Year: 2023

# ---- MAP: --------------


def changeYear(c):
c.year = 100
return c

newCars = list(map(lambda c: changeYear(c), cars))

for car in newCars:


print(f"{car.mark} {car.model} {car.year}")
# -> Toyota Yaris 100
# -> Toyota Camry 100
# -> Audi Q5 100

from functools import reduce

numbers = [1, 2, 3, 4, 5]
def sum(a, b):
return a + b

result = reduce(sum, numbers) # adauga cu vecinii, rez final


print(result) # -> 15

from functools import reduce

class Product:
def __init__(self, title, price):
self.title = title
self.price = price

products = [
Product("Banana", 25),
Product("Mere", 10),
Product("Rosii", 30)
]

total = reduce(lambda s, p: s + p.price, products, 0) # initial value is set to 0


print(total) # -> 65

sortedProducts = sorted(products, key=lambda p: p.price, reverse=True)

for p in sortedProducts:
print(f"{p.title} {p.price}")
# -> Rosii 30
# -> Banana 25
# -> Mere 10

ages = [100, 23, 35, 12, 52]


sortedAges = sorted(ages, reverse=True)
print(sortedAges) # -> [100, 52, 35, 23, 12]
anyExpensive = any(p.price > 1000 for p in products)
print(anyExpensive) # -> False

numbers = [1, 2, 3, 4, 5]
anyEven = any(n % 7 == 0 for n in numbers)
print(anyEven) # -> False

numbers = [-1, 1, 2, 3, 4, 5]
anyEven = any(n % 7 == 0 for n in numbers)
print(anyEven) # -> False

allGreaterThan0 = all(n > 0 for n in numbers)


print(allGreaterThan0) # -> False

allCheapProducts = all(p.price < 100 for p in products)


print(allCheapProducts) # -> True

students = ["Natalia", "Bogdan", "Igor", "Mihaela", "Marian"]

ages = [20, 17, 18, 18, 60]

for i, s in enumerate(students):
print(f"{i} {s}")
# -> 0 Natalia
# -> 1 Bogdan
# -> 2 Igor
# -> 3 Mihaela
# -> 4 Marian

# combines 2 tables:
newDict = list(zip(students, ages))

for i, (s, age) in enumerate(newDict):


print(f"index:{i} {s} age: {age}")
# -> index:0 Natalia age: 20
# -> index:1 Bogdan age: 17
# -> index:2 Igor age: 18
# -> index:3 Mihaela age: 18
# -> index:4 Marian age: 60

You might also like