Python From Scratch
Python From Scratch
Bu problemi aradan qaldırmaq üçün, veriləni qəbul edən kimi integrə çevirmək lazımdır.
age = int(input("How old are you?:"))
age += 1
print(age)
Aşağıda isə yenə xəta alacağıq, bunun səbəbi isə print yerində ancaq stringlər toplusu ola bilər, ageni isə biz
üzərində hesab əməli apardığımız üçün intergerə çevirmişdik.
import math
pi = 3.14
print(round(pi))
Ceil (siıl) is rounded the number up to the nearest number. First of all we have to call the math function like below:
import math
pi = 3.14
#print(round(pi))
print(math.ceil(pi))
Floor is rounded the number to the down nearest number.
import math
pi = 3.14
#print(round(pi))
#print(math.ceil(pi))
print(math.floor(pi))
abs= absolute value (modul)
import math
pi = -3.14
#print(round(pi))
#print(math.ceil(pi))
#print(math.floor(pi))
print(abs(pi))
Pow is used to raise to power
import math
number = 2
pi = -3.14
#print(round(pi))
#print(math.ceil(pi))
#print(math.floor(pi))
#print(abs(pi))
print(pow(number, 10))
Square root of number
import math
number = 16
pi = -3.14
#print(round(pi))
#print(math.ceil(pi))
#print(math.floor(pi))
#print(abs(pi))
#print(pow(number, 10))
print(math.sqrt(number))
Indexing[] [start:stop:step]
The first index is inclusive and the stopping index is exclusive. Burada əslində adım beş hərflidir amma ki, stopping
son dəyişəni almır ona görə bir rəqəm çox yazmaq lazımdır.
web_page = "https://www.google.com/"
formula_for_short_name = slice(12,-5)
print(web_page[name_of_web_page])
Burada eyni strukturlu saytların əsil adını götürmək üçün kod yazdıq.
web_page = "https://www.google.com/"
web_page2 = "https://www.wikipedia.org/"
formula_for_short_name = slice(12,-5)
print(web_page[formula_for_short_name])
print(web_page2[formula_for_short_name])
If statement
Logical operator
While loop is a statement that will execute its block of code as long as its condition remains true.
while 1 == 1:
print("Help: I'm stuck in a loop!")
Here if we must write a condition, I we don’t then it keep print.
name = ""
while len(name) == 0:
name = input("Please, enter your name: ")
print("Hello " + name)
Another way to execute this code
name = None
while not name:
name = input("enter your name please: ")
print("Hello " + name + " how's life treating you today?")
For loop
For loop is a statement that will execute it’s block of code a limited amount of time
for i in range(10):
print(i +1)
We can execute certain amount of number like this.
for i in range(23,100):
print(i)
We can do also like this
import time
for timer in range(10,0,-1):
print(timer)
time.sleep(1)
print("Happy New Year")
List
List- used to store multiple items in a single variable
meal = ["Dolma", "Ash", "Doner"]
print(meal)
We can execute whatever we want through using their index. Note: index starts from scratch
meal = ["Dolma", "Ash", "Polov", "Doner"]
print(meal[2])
We can also replace any item in the list whenever we want.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal[1]= "levengi"
print(meal)
if we want to print every item in the list we can use for loop.
meal = ["Dolma", "Ash", "Polov", "Doner"]
for x in meal:
print(x)
If we want to add anything to the list, we can do it through using append function.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal.append("Baliq")
print(meal)
We can also remove any item in the list through using remove function.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal.remove("Ash")
print(meal)
There is another function to remove the last item in the list, it’s pop function.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal.pop()
print(meal)
So, if we want to add a new element to the list very specific index we can use insert function.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal.insert(2, "Kabab")
print(meal)
Through using sort function, we can sort our list alphabetically.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal.sort()
print(meal)
We can also clear all of item from the list through using clear function.
meal = ["Dolma", "Ash", "Polov", "Doner"]
meal.clear()
print(meal)
2D list
2D list- a list of lists.
drinks = ["Cola", "Fanta", "Cappy", "Sprite"]
Foods = ["Ash", "Doner", "Kabab", "Dolma"]
Desser = ["Tort", "Paxlava", "Sekerbura", "Keks"]
all_of_lists = [drinks, Foods, Desser]
print(all_of_lists)
If I want to access one of these lists, I can do it through using their own index.
drinks = ["Cola", "Fanta", "Cappy", "Sprite"]
Foods = ["Ash", "Doner", "Kabab", "Dolma"]
Desser = ["Tort", "Paxlava", "Sekerbura", "Keks"]
all_of_lists = [drinks, Foods, Desser]
print(all_of_lists[1])
So let's say if I want to execute this specific item in the list I can do it through this way.
drinks = ["Cola", "Fanta", "Cappy", "Sprite"]
Foods = ["Ash", "Doner", "Kabab", "Dolma"]
Desser = ["Tort", "Paxlava", "Sekerbura", "Keks"]
all_of_lists = [drinks, Foods, Desser]
print(all_of_lists[0][1])
Tuples
Tuples- collection which is ordered and unchangeable. They are used to group together related data.
car = ("Nissan", 2003, "x7", 2003, 2003)
print(car.count(2003))
like list we can also find any items index in the tuple.
car = ("Nissan", 2003, "x7", 2003, 2003)
print(car.index("Nissan"))
We can also check whether the certain item is in the list or not.
car = ("Nissan", 2003, "x7", 2003, 2003)
if "Nissan" in car:
print("Nissan is here")
Set
Set- collection, which is unordered, unindexed. No duplicate values.
It doesn't matter how much we have the same value when we exclude it, it's going to be one of them.
cars = {"nissan","bogati", "ferrari", "lamborgini"}
for c in cars:
print(c)
We can add an item in the set through using the add function.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
cars.add("mazda")
for c in cars:
print(c)
We can also remove the element from set through using remove function.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
cars.remove("ferrari")
for c in cars:
print(c)
We can also clear the list through using clear function.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
cars.clear()
for c in cars:
print(c)
We can add one set to another through using update function.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
vehicles = {"cars", "ships", "planes", "motorcycles"}
cars.update(vehicles)
for c in cars:
print(c)
So, we can do the same thing through using union function.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
vehicles = {"cars", "ships", "planes", "motorcycles"}
all_of_them = cars.union(vehicles)
for a in all_of_them:
print(a)
We can also compare sets with different methods. This code shows us what cars have, vehicles don’t.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
vehicles = {"cars", "ships", "planes","lamborgini", "motorcycles"}
print(cars.difference(vehicles))
We can also print the common element in the sets through using intersection function.
cars = {"nissan","bogati", "ferrari", "lamborgini", "Lada", "RR", "ferrari"}
vehicles = {"cars", "ships", "planes","lamborgini", "motorcycles"}
print(cars.intersection(vehicles))
Dictionary
Dictionary- A changeable, unordered collection of unique key: value pairs fast because they use hashing,
allow us to access a value quickly.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
print(capital['Russia'])
Let’s say we input a key which we don’t have in the code. In this situation we’re going to have the error.
To prevent this, we could use get function.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
print(capital.get('Azerbaijan'))
Index operator
Index operator []- they gives access to a sequence’s element (str, list, tuples)
name = "vusal Farzullazada"
if(name[0].islower()):
name = name.capitalize()
print(name)
We can access everything in the string through this method. Here 0 isn't necessary we can remove it from
the code, that'll be handier.
name = "vusal Farzullazada"
first_name = name[0:5].upper()
print(first_name)
So, we could do the same for the end of the string I mean we don't have to use the last character’s index,
we could let their blank.
name = "vusal Farzullazada"
surname = name[6:]
print(surname)
We also can access the last character in the string through using this code.
name = "vusal Farzullazada"
last_character = name[-1]
print(last_character)
Function
Function- is a block of code which is executed only when it is called.
Here is some notes about functions
1. Functions are always end with parentheses.
2. The program only excluded then we call the function.
def hello():
print("You called the function")
hello()
We also can give some parameters to the functions and we also can exclude whatever you want.
def hello(name):
print("hello " + name)
print("Good morining " + name)
hello("Vusal")
hello("Ilkin")
Our parameter and our functions must match with each other.
def hello(name, age):
print("What is your name, "+name, "How old are you "+ str(age))
hello("Vusal",21)
another example:
def hello(age):
print("You are "+ str(age)+ " year old")
hello(23)
Keyword arguments
Keyword arguments: arguments preceded by an identifier when we pass them to a function the order of
the arguments doesn’t matter, unlike positional arguments. Python knows the names of the arguments that
our function receives.
def names_order(givenname, middle, surname):
print("Hello " + givenname + " " + middle + " " + surname)
names_order(givenname="Vusal", surname="Farzullazada", middle="Əxi")
str format
str format- optional method that gives users more control when displaying output.
print("Hello, How are you {}, did you go to the {} today?".format("Vusal",
"school"))
we can replace string with valuable like this:
name = "Vusal"
place = "school"
print("Hello, How are you {}, did you go to the {} today?".format(name,place))
we can do the same thing with other way:
name = "Vusal"
place = "school"
print("Hello, How are you {1}, did you go to the {0}
today?".format("practice","Ilkin"))
we can also input the variables into the print function, the we aren’t going to need them anymore.
print("Hello, How are you {name}, did you go to the {place}
today?".format(name="Ilkin", place="university"))
We can also print this code with more elegant way.
article = "{} is my best friend. We met with him in the {}"
print(article.format("Ilkin", "high school"))
Random
We can get random number in the certain range through using randint function.
import random
x = random.randint(1,20)
print(x)
We can also generate floating number between 0-1 through using random function.
import random
x = random.random()
print(x)
We can generate random choice from the list through using choice function. So here the example of rock,
paper, and scissors.
import random
list = ["Rock", "Paper", "Scissors"]
z = random.choice(list)
print(z)
We can also use the shuffle method of random functions to shuffle lists or input.
import random
adlar = ["Ilkin", "Vusal", "Valid", "Farid", "Zeka", "Ahliman"]
random.shuffle(adlar)
print(adlar)
Exception
Exception- events detected during execution that interrupt the flow of a program.
try:
num1 = int(input("enter your first number pls:"))
num2 = int(input("enter your second number pls:"))
code = num1/num2
print(code)
except:
print("ops, something went wrong:(")
it had better if we want to catch specific error, so we must give specific exception, in order to let the user
know what is wrong:
try:
num1 = int(input("enter your first number pls:"))
num2 = int(input("enter your second number pls:"))
code = num1/num2
print(code)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input, please just enter number")