پایتون مقدماتی

Variables
ID() function  ==> return variable memory address
in Python we don't have block level scope !
#############################
s  = "this is a string"  
print(  type(s) )
output==>
<class 'str'>
##################################
Multiple_Line_String = """    #use triple quote """ 
Multiple
Line
String
"""
##################################
x, y = 1, 2    #it is equal to x=1   and y=1 in sperate lines
##################################
first = "Ali"
last = "Mostofi"

full = f"{first}    {last}"
print(full)

output ==>
Ali Mostofi
#######################
name = '  Ahmad Ali Mostofi'

print(name)
print(name.upper())
print(name.lower())
print(name.title())
print(name.strip())
print(name.lstrip())
print(name.rstrip())
print(name.find("Mos"))
print(name.find("mos"))
print(name.split(" "))
print(name.split())
print(name.replace("i", "-"))
print("Ali" in name)
output ==>
 Ahmad Ali Mostofi
  AHMAD ALI MOSTOFI
  ahmad ali mostofi
  Ahmad Ali Mostofi
Ahmad Ali Mostofi
Ahmad Ali Mostofi
  Ahmad Ali Mostofi
12
-1
['', '', 'Ahmad', 'Ali', 'Mostofi']
['Ahmad', 'Ali', 'Mostofi']
  Ahmad Al- Mostof-
True
#######################
# valid variable definition
X = Y = 1

print(X, Y)
##################################
a = [1, 2, 3]
print(  type(a) )
output==>
<class 'list'>
##################################
a = [1, 2, 3, 'str']
print (a[0])
output==>
1
##################################
s = "Ali"
print (s[0])
output==>
A
##################################
s = "Ali Mostofi"
print (s[-2])
output==>
f
##################################
s = "Ali Mostofi"
print (s[-2:0])
output==>
f
##################################
s = "Ali Mostofi"
print (s[1:7])
output==>    #  note:  location 7 does not exists in result
li Mos
##################################
s = "Ali Mostofi"
print (s[-4:-2:])
output==>    #note: s is equal to   [-4:-2:1], the default step is 1
to
##################################
s = "Ali Mostofi"
print (s[-2:-4:-1])
output==>  
fo
##################################
dic = {"Ali": 20, "Ahmad": 25}
print (dic["Ahmad"])
dic["Ahmad"] = "30"
print (dic["Ahmad"])

dic["Amir"] = "35"
dic["Amir"] = "40"

print (dic)

output==>  
25 30 {'Ali': 20, 'Ahmad': '30', 'Amir': '40'}
################################
list1 = [1, 2, "Ali"]
list1.append("Ahmad")
list1.insert(0, "Amir")
list1.remove(1)
list1.reverse() #reverse item indexs

print (list1)

list2 = [999, 1000]
list1.extend(list2) #append list2 to list1

print (list1)

list1.pop() #drop last element

print (list1)

output==>
['Ahmad', 'Ali', 2, 'Amir'] ['Ahmad', 'Ali', 2, 'Amir', 999, 1000] ['Ahmad', 'Ali', 2, 'Amir', 999]
Operators
i = 10
j = 3
print (i / j)
output==>  
3.3333333333333335
##################################
i = 10
j = 3
print (i // j)
output==>      # returns only integer part
3
##################################
i: int
j: int

i = int( input("i :"))
j = float( input("j :") )

print (i // j)
output==>      #  convert str to int then ................
3
conditions
if not (2 == 2 or 1 == 1) :
    print ( True)

elif 9 == 8:
    print (False)
else:
    print ("else block")
  
output==>    
else block
##################################
Valid_Names = ['Ali', 'Ahmad']

if not input("Enter valid name: ") in Valid_Names :    
    print ("it is not a valid name")
else
print ("it is a valid name")

output==>    # if Ali entered as input
it is a valid name
output==>    # if Hassan entered as input
it is not a valid name
output==>    # if ali entered as input   #it is case sensitive
it is not a valid name
##################################
# valid condition
age = 22
if 18 <= age < 65:
######################
# immedate if
age = 22

message = "ok" if age > 18 else "not ok"
print(message)
Loops
Valid_Names = ['Ali', 'Ahmad']

for name in Valid_Names :  
    print ( name )

output==> 
Ali
Ahmad
##################################
i = 0
while i < 4 :
    print ( i )
    i += 1 #similiar to i = i + 1

output==> 
0
1
2
3
done
##################################
for i in range(1, 6): #
    if i == 3:
        continue  # Skip iteration if i equals 3
    print("Iteration:", i)
##################################
#for .............. else
l = ["Ahmad", "AAli"]
for x in l:
    if x == "Ali":
        print("Ali Found")
        break
else:
    print("No Ali Found")

output ==>
No Ali Found
Functions
def seach_cutomers(customer_code):
    customer_list = ['1001', '1002', '1003', '1010']
    if  (customer_code in customer_list):
        return True
    else:
        return False

s = input("input number: ")
if not seach_cutomers(s):
    print("customer not found!")
#################################
def seach_cutomers(customer_code, type='t'):
    customer_list = ['1001', '1002', '1003', '1010']
    if  (customer_code in customer_list):
        return True
    else:
        return False

s = input("input number: ")
if not seach_cutomers(type='X', customer_code='alfa'):
    print("customer not found!")
##################################
#function return tuple,
def increment(value: int, by: int = 1) -> tuple:
    return (value, value + by)

print(increment(1, 3))

output ==>
(1, 4)
###################################
#list of parameters, not an array
def multiply(*list):
    total = 1
    for x in list:
        total = int(x) * total
    return total

print(multiply(1, 2, 3, 4))

output ==>
24
###################################
#  list of parameters complex !   **
def concatinate(*list, **arg):
    total = ''
    for x in list:
        total = total + x + arg["sep"]
    return total + arg["other"]


print(concatinate("My", "name", "is", "Ali", sep="!", other="?"))

output ==>
My!name!is!Ali!?
###################################
# message variable acts as local variable inside greet function
message = "a"

def greet():
    message = "b"

greet()
print(message)

output ==>
a
###################################
message = "a"

def greet():
    global message
    message = "b"

greet()
print(message)

output ==>
b
###################################
String Functions
print  ("*" * 100)   #it will print * 100 times

Class & Objects
class Label:
    def __init__(self, text):
        self._text = text
    def set_text(self, value):
        self._text = value
    def get_text(self):
        return self._text
   
mylabel = Label('Ali')
print (mylabel.get_text())

mylabel.set_text('Ahmad')
print (mylabel.get_text())
output ==>
Ali Ahmad
##################################
Rock Paper Scissors
import random as rn

SystemChoice = rn.randrange(0, 3)
UserChoice = int(input("your choose: 1-Sang  2-Kaghaz  3-Gheychi")) - 1

if UserChoice in [0, 1, 2]:
    choice = ["Sang", "Kaghaz", "Gheychi"]
    matrix =  [
            ["nothing", "Failed", "Won"] ,
            ["Won", "nothing", "Failed"] ,
            ["Failed", "Won", "nothing"] ]

    print ("User: " + choice[UserChoice])        
    print ("System: " + choice[SystemChoice])
    print ("Result: User " + matrix[Us
##################################
Create Acronym From Statement
IgnoreList = ['a', 'to', 'by', 'the']
MyStr = input("Enter statement to create acronym")
MyStrArray = MyStr.split(sep=' ')

Result = ''
for Word in MyStrArray:
    if not Word in IgnoreList:
        Result = Result + Word[0]

print(Result)
###################################
File
import os

current_directory = os.getcwd()
f = open(current_directory+"/libs/mycalculator.py", "r")

# while s != '':
#     s = f.readline()
#     print(s)

for x in f:
    print (x)

f.close()