Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Python From Scratch

The document discusses Python programming concepts like data types, variables, operators, conditional statements, loops, functions and lists. It provides examples and explanations of string indexing and slicing, basic math functions, if/else statements, logical operators, while and for loops, and how to define and manipulate lists.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python From Scratch

The document discusses Python programming concepts like data types, variables, operators, conditional statements, loops, functions and lists. It provides examples and explanations of string indexing and slicing, basic math functions, if/else statements, logical operators, while and for loops, and how to define and manipulate lists.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Python from scratch

Hashtag (#) it’s used for comment, python ignore it.


For find out date type of the variable:
name = "Vusal"
print(type(name))
String is a series of characters. We can’t use them with math.
Shortcut:
age += 1
Integer is only stored whole integers (numbers)
Float data type is stored whole numbers like 1, 2.3 and so on
We can’t print different data type inside print, they have to be same
Boolean (boliyen) data type. This only store true or false
Multiple assignment = allows us to assign multiple variables at the same time in one line of code. But
they should be in the same order.
name, surname, age = "Vusal", "Farzullazada", 21
print(name)
print(surname)
print(age)
it can be like this as well
valid = ruhid = vusal = 21
print(valid)
print(ruhid)
print(vusal)
to find out how long the variable is we can use len
name = "Vusal"
print(len(name))
if we want to find where our letter is we can use find function
name = "vusal"
print(name.find("u"))
how to capitalize, upper, lower
name = "vusal"
print(name.capitalize())
if you want to check to see your string includes only letters isalpha, when it comes to numbers we can
use isdigit with the same way.
name = "Vusal"
print(name.isalpha())
name = "123"
print(name.isdigit())
we can count how many character are within our string with count function
country = "Azerbaijan"
print(country.count("a"))
We can replace character with something else through using replace
country = "Azerbaijan"
print(country.replace("a", "A"))
there is something like this as well. This is going to print Azerbaijan 4 times.
country = "Azerbaijan"
print(country*4)
Type casting = convert the date type of a value to another data type.
From float and string to integer we use int function
x=7
y = 6.9
z = "4"
print(int(z))
it’s just printed, z didn’t converted permanently, if we want then: it’s the same for string, and float
note: floatı işlədəndə o ədədi bir vahid yuxarl yuvarlaqlaşdırır.
x=7
y = 6.9
z = "4"
z = int(z)
print(type(z))
Bu aşağıdakı kodda, z string oluğu üçün onu 3 ə vurmur, onu 3 dəfə yazır
x=7
y = 6.9
z = "4"
print(z*3)
Input
name = input("What is your name?:")
print("Hello " + name)
Əgər aşağıdakı kodu run eləsək, xəta alarıq, bunun əsas səbəbi isə, biz dəyişəni string olaraq qəbul edib
onun üzərində riyazi əməl həyata keçiririk.
age = input("How old are you?:")
age += 1
print(age)

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.

name = input("What is your name?:")


age = int(input("How old are you?:"))
age += 1
print("Hello" + name + age + "years old")

Bu problem biz ageni təzdən stringə qaytararaq həll edə bilərik.


name = input("What is your name?:")
age = int(input("How old are you?:"))
age += 1
print("Hello " + name +",you are " + str(age) + " years old")
Math module

Round is rounded the number, value to the nearest number

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))

Max is used to determine the biggest number:


x=3
y=4
z=6
print(max(x,y,z))
Slicing = create a substring by extracting elements from another string

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.

name = "Vusal Farzullazada"


first_name = name[0:6]
print(first_name)
Bunu 0 yazmadan da etmək olar, bu zaman python özü bunu 0 kimi qəbul edir

name = "Vusal Farzullazada"


first_name = name[:6]
print(first_name)
Shorthand way of this

full_name = "Vusal Farzullazada"


first_name = full_name[:6]
last_name = full_name[6:]
print(last_name)
Another example, beləcə hər iki sözdən bir yazacaq, yəni steplərin sayı 2 dir.

full_name = "Vusal Farzullazada"


new_name = full_name[0:19:2]
print(new_name)
The short way of writing this leave star and stop empty but be sure you have colons.

full_name = "Vusal Farzullazada"


new_name = full_name[::2]
print(new_name)
If you want to write something reverse (rivörs) you can do it like this

full_name = "Vusal Farzullazada"


new_name = full_name[::-1]
print(new_name)
Slice: bunun da o birindən çoxda fərqi yoxdur

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

If statement = a block of code that will execute if it’s condition true


height = int(input("How tall are you?:"))
if height >= 170:
print("You are tall")
Else

height = int(input("How tall are you?:"))


if height >= 170:
print("You are tall")
else:
print("You are short")
Elif = else + if

height = int(input("How tall are you?:"))


if height >= 170:
print("You are tall")
elif height > 165:
print("You are good")
else:
print("You are short")
Another example

name = input("what is your name?:")


if name == "Vusal":
print("You are my boss")
elif name == "Ilkin":
print("you are my friend")
else:
print("I don't know you")

Logical operator

Logical operator are used to check if two or more conditional statements.

And = both conditions have to be true

temprature = int(input("What is the temprature outside?:"))

if temprature >= 0 and temprature <= 27:


print("Weather is great today, you can go outside.")
Or = one of the condition has to be true.

temprature = int(input("What is the temprature outside?:"))


if temprature >= 0 and temprature <= 27:
print("Weather is great today, you can go outside.")
elif temprature < 0 or temprature >27:
print("Weather is terrible today")
print("You should stay inside")
Not = it’s used to change the meaning of the operator. False to true, true to false.

tem = int(input("What is the temperature outside?:"))


if not tem <= 0 and not tem >= 30:
print("weather is good to go outside today")
else:
print("stay in the home")
While loop

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

for i in range(1,19+1, 2):


print(i)
like this as well

for i in "Vusal Farzullazada":


print(i)
Happy New Year program

import time
for timer in range(10,0,-1):
print(timer)
time.sleep(1)
print("Happy New Year")

Loop control statements


Break- used to terminate the loop entirely
while True:
name = input("Enter your name:")
if name != "":
break
print("your name is " + name )
!= different
Continue- skips to the new iteration of the loop.
phone_number = "123-456-778-4321"
for i in phone_number:
if i == "-":
continue
print(i, end="")
burada end=’dan istifadə etməsək rəqəmlər sütün şəklində print olunacaq.
Pass- do nothingç act as a placeholder.
for i in range(1,75):
if i == 69:
pass
else:
print(i)
burada 1 dən 74 ə qədər rəqəm print edəcək amma 69 etməyəcək. Eyni şeyi continue ilə də edə bilərik
for i in range(1,23):
if i == 7:
continue
print(i)

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'))

If we would execute the keys only, we could be key function.


capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
print(capital.keys())
We could do the same thing with values.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
print(capital.values())
if you want print everything both keys and values, you should use item function.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
print(capital.items())
If you want to print particularly keys we can use for function like this.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
for key in capital:
print(key)
Also, through using this method we could print everything.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
for key, value in capital.items():
print(key, value)
So, let's say if you want to update our dictionary or let's say if you want to add something else in this case
we should follow this structure.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
capital.update({'Egypt':'Cairo'})
for key, value in capital.items():
print(key, value)
Through using the update function, we can update the and the value inside the dictionary.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
capital.update({'Egypt':'Cairo'})
capital.update({'Russia':'Novirisivki'})
for key, value in capital.items():
print(key, value)
So, let's say if we want dictionary we should use pop function, down in order to clean everything up we
should use clean function.
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
capital.pop('Turkey')
for key, value in capital.items():
print(key, value)
Clean
capital = {'Azerbaijan':'Baku',
'Russia':'Moscow',
'Turkey':'Ankara',
'Iran':'Tehran'}
capital.clear()
for key, value in capital.items():
print(key, value)

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")

Nested functions calls


Nested functions: function calls inside other function calls. Innermost function calls are resolved first
returned value is used as argument for the next outer function.
number = input("Please, enter your positive number:")
number = float(number)
number = abs(number)
number = round(number)
print(number)
instead of writing like this, we could do something else like this:
print(round(abs(float(input("Please, enter your positive number:")))))
one single line but does the same thing as before.
*args
*args- parameter that will pack all arguments into a tuple useful so that a function can accept a varying
amount of arguments.
def add(*args):
sum = 0
for i in args:
sum += i
return sum
print(add(1,2,3,4,5,6,7,8,8))

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")

You might also like