بازارسال شده از 100241-Python
تمرین ۴۲نمایش الگوrows = 5for i in range(0, rows): for j in range(0, i + 1): print("*", end=' ') print("\r")
for i in range(rows, 0, -1): for j in range(0, i - 1): print("*", end=' ') print("\r")
for i in range(rows, 0, -1): for j in range(0, i - 1): print("*", end=' ') print("\r")
۱:۳۷
بازارسال شده از 100241-Python
تمرینات بخش چهارمتابعتمرین ۴۳# demo is the function namedef demo(name, age): # print value print(name, age)
# call functiondemo("Ben", 25)
# call functiondemo("Ben", 25)
۱:۳۷
بازارسال شده از 100241-Python
تمرین ۴۴تابع با طول آرگومان های متغیرdef func1(*args): for i in args: print(i)
func1(20, 40, 60)func1(80, 100)
func1(20, 40, 60)func1(80, 100)
۱:۳۷
بازارسال شده از 100241-Python
تمرین ۱۲محاسبه مالیات بردرآمد باتوجه به جدول زیر:Taxable Income Rate (in%)First $10,000 0Next $10,000 10The remaining 20_income = 45000tax_payable = 0print("Given income", income)
if income <= 10000: tax_payable = 0elif income <= 20000: # no tax on first 10,000 x = income - 10000 # 10%tax tax_payable = x 10 / 100
else:
# first 10,000
tax_payable = 0
# next 10,000 10%tax
tax_payable = 10000 10 / 100
# remaining 20%tax tax_payable += (income - 20000) * 20 / 100
print("Total tax to pay is", tax_payable)
if income <= 10000: tax_payable = 0elif income <= 20000: # no tax on first 10,000 x = income - 10000 # 10%tax tax_payable = x 10 / 100
else:
# first 10,000
tax_payable = 0
# next 10,000 10%tax
tax_payable = 10000 10 / 100
# remaining 20%tax tax_payable += (income - 20000) * 20 / 100
print("Total tax to pay is", tax_payable)
۱:۳۹
بازارسال شده از 100241-Python
تمرین۴۵برگردندان چند مقدار در تابع
def calculation(a, b): addition = a + b subtraction = a - b # return multiple values separated by comma return addition, subtraction
# get result in tuple formatres = calculation(40, 10)print(res)
def calculation(a, b): addition = a + b subtraction = a - b # return multiple values separated by comma return addition, subtraction
# get result in tuple formatres = calculation(40, 10)print(res)
۱:۴۰
بازارسال شده از 100241-Python
راه حل دیگر تمرین۴۵def calculation(a, b): return a + b, a - b
# get result in tuple format# unpack tupleadd, sub = calculation(40, 10)print(add, sub)
# get result in tuple format# unpack tupleadd, sub = calculation(40, 10)print(add, sub)
۱:۴۰
بازارسال شده از 100241-Python
تمرین۴۶ایجاد تابع با یک آرگومان پیش فرض در زمان فراخوانی# function with default argumentdef show_employee(name, salary=9000): print("Name:", name, "salary:", salary)
show_employee("Ben", 12000)show_employee("Jessa")
show_employee("Ben", 12000)show_employee("Jessa")
۱:۴۰
بازارسال شده از 100241-Python
تمرین۴۷ایجاد تابع در داخل یک تابع# outer functiondef outer_fun(a, b): square = a ** 2
# inner function def addition(a, b): return a + b
# call inner function from outer function add = addition(a, b) # add 5 to the result return add + 5
result = outer_fun(5, 10)print(result)
# inner function def addition(a, b): return a + b
# call inner function from outer function add = addition(a, b) # add 5 to the result return add + 5
result = outer_fun(5, 10)print(result)
۱:۴۰
بازارسال شده از 100241-Python
تمرین۴۸ایجاد تابع بازگشتیمنطور در داخل خودش دوباره فراخوانی می شودdef addition(num): if num: # call same function by reducing number by 1 return num + addition(num - 1) else: return 0
res = addition(10)print(res)
res = addition(10)print(res)
۱:۴۰
بازارسال شده از 100241-Python
تمرین۴۹انتساب نام جدید به یک تابعdef display_student(name, age): print(name, age)
# call using original namedisplay_student("Emma", 26)
# assign new nameshowStudent = display_student# call using new nameshowStudent("Emma", 26)
# call using original namedisplay_student("Emma", 26)
# assign new nameshowStudent = display_student# call using new nameshowStudent("Emma", 26)
۱:۴۰
بازارسال شده از 100241-Python
تمرین ۵۰ایجاد لیست با تابع rangeprint(list(range(4, 30, 2)))
۱:۴۰
بازارسال شده از 100241-Python
تمرین۵۱تابع بزرگترین مقدار لیستx = [4, 6, 8, 24, 12, 2]print(max(x))
۱:۴۰
بازارسال شده از 100241-Python
تمرین۵۲ برگشت چند مقدار بعد از فراخوانی تابعdef arithmetic(num1, num2): add = num1 + num2 sub = num1 - num2 multiply = num1 * num2 division = num1 / num2 # return four values return add, sub, multiply, division
# read four return values in four variablesa, b, c, d = arithmetic(10, 2)
print("Addition: ", a)print("Subtraction: ", b)print("Multiplication: ", c)print("Division: ", d)
# read four return values in four variablesa, b, c, d = arithmetic(10, 2)
print("Addition: ", a)print("Subtraction: ", b)print("Multiplication: ", c)print("Division: ", d)
۱:۴۰
بازارسال شده از 100241-Python
تمرین ۵۳استفاده از کلمه کلیدی passdef addition(num1, num2): # Implementation of addition function in comming release # Pass statement pass
addition(10, 2)
addition(10, 2)
۱:۴۰
بازارسال شده از 100241-Python
تمرین۵۴طول عمر متغیرها در توابعglobal_lang = 'DataScience'
def var_scope_test(): local_lang = 'Python' print(local_lang)
var_scope_test()# Output 'Python'
# outside of functionprint(global_lang)# Output 'DataScience'
# NameError: name 'local_lang' is not definedprint(local_lang)برنامه با خطا خواهد داشتاین برنامه نیز خطا خواهد داشتdef function1(): # local variable loc_var = 888 print("Value is :", loc_var)
def function2():
print("Value is :", loc_var)
function1()function2()حالا کد زیرمتغیر عمومی یا سراسری globalتعریف می شودglobal_var = 999
def function1(): print("Value in 1nd function :", global_var)
def function2(): print("Value in 2nd function :", global_var)
function1()function2()
def var_scope_test(): local_lang = 'Python' print(local_lang)
var_scope_test()# Output 'Python'
# outside of functionprint(global_lang)# Output 'DataScience'
# NameError: name 'local_lang' is not definedprint(local_lang)برنامه با خطا خواهد داشتاین برنامه نیز خطا خواهد داشتdef function1(): # local variable loc_var = 888 print("Value is :", loc_var)
def function2():
print("Value is :", loc_var)
function1()function2()حالا کد زیرمتغیر عمومی یا سراسری globalتعریف می شودglobal_var = 999
def function1(): print("Value in 1nd function :", global_var)
def function2(): print("Value in 2nd function :", global_var)
function1()function2()
۱:۴۰
بازارسال شده از 100241-Python
تمرین ۵۵متغیرهای سراسری# Global variableglobal_var = 5
def function1(): print("Value in 1st function :", global_var)
def function2(): # Modify global variable # function will treat it as a local variable global_var = 555 print("Value in 2nd function :", global_var)
def function3(): print("Value in 3rd function :", global_var)
function1()function2()function3()
def function1(): print("Value in 1st function :", global_var)
def function2(): # Modify global variable # function will treat it as a local variable global_var = 555 print("Value in 2nd function :", global_var)
def function3(): print("Value in 3rd function :", global_var)
function1()function2()function3()
۱:۴۰
بازارسال شده از 100241-Python
تمرین ۵۶استفاده از کلمه کلیدی global# Global variablex = 5
# defining 1st functiondef function1(): print("Value in 1st function :", x)
# defining 2nd functiondef function2(): # Modify global variable using global keyword global x x = 555 print("Value in 2nd function :", x)
# defining 3rd functiondef function3(): print("Value in 3rd function :", x)
function1()function2()function3()
# defining 1st functiondef function1(): print("Value in 1st function :", x)
# defining 2nd functiondef function2(): # Modify global variable using global keyword global x x = 555 print("Value in 2nd function :", x)
# defining 3rd functiondef function3(): print("Value in 3rd function :", x)
function1()function2()function3()
۱:۴۰
بازارسال شده از 100241-Python
تمرین ۵۷تابع nonlocalبرای متغیرهای تابعdef outer_func(): x = 777
def inner_func(): # local variable now acts as global variable nonlocal x x = 700 print("value of x inside inner function is :", x)
inner_func() print("value of x inside outer function is :", x)
outer_func()
def inner_func(): # local variable now acts as global variable nonlocal x x = 700 print("value of x inside inner function is :", x)
inner_func() print("value of x inside outer function is :", x)
outer_func()
۱:۴۰
بازارسال شده از 100241-Python
تمرینات بخش پنجم مربوط به رشتهتمرین۵۸حرف اول و وسط و آخر یک رشتهstr1 = 'James'print("Original String is", str1)
# Get first characterres = str1[0]
# Get string sizel = len(str1)# Get middle index numbermi = int(l / 2)# Get middle character and add it to resultres = res + str1[mi]
# Get last character and add it to resultres = res + str1[l - 1]
print("New String:", res)
# Get first characterres = str1[0]
# Get string sizel = len(str1)# Get middle index numbermi = int(l / 2)# Get middle character and add it to resultres = res + str1[mi]
# Get last character and add it to resultres = res + str1[l - 1]
print("New String:", res)
۱:۴۰
سورس پروژه جالب برای حدس زدن کلماتHangman gameimport randomimport timeprint("\nWelcome to Hangman game by DataFlair\n")name = input("Enter your name: ")print("Hello " + name + "! Best of Luck!")time.sleep(2)print("The game is about to start!\n Let's play Hangman!")time.sleep(3)
def main(): global count global display global word global already_guessed global length global play_game words_to_guess = ["january","border","image","film","promise","kids","lungs","doll","rhyme","damage","plants"] word = random.choice(words_to_guess) length = len(word) count = 0 display = '_' length
already_guessed = []
play_game = ""
def play_loop():
global play_game
play_game = input("Do You want to play again? y = yes, n = no \n")
while play_game not in ["y", "n","Y","N"]:
play_game = input("Do You want to play again? y = yes, n = no \n")
if play_game == "y":
main()
elif play_game == "n":
print("Thanks For Playing! We expect you back again!")
exit()
def hangman():
global count
global display
global word
global already_guessed
global play_game
limit = 5
guess = input("This is the Hangman Word: " + display + " Enter your guess: \n")
guess = guess.strip()
if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9":
print("Invalid Input, Try a letter\n")
hangman()
elif guess in word:
already_guessed.extend([guess])
index = word.find(guess)
word = word[:index] + "_" + word[index + 1:]
display = display[:index] + guess + display[index + 1:]
print(display + "\n")
elif guess in already_guessed:
print("Try another letter.\n")
else:
count += 1
if count == 1:
time.sleep(1)
print(" _ \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
elif count == 2:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
elif count == 3:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
elif count == 4:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | | \n"
" | O \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " last guess remaining\n")
elif count == 5:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | | \n"
" | O \n"
" | /|\ \n"
" | / \ \n"
"__|__\n")
print("Wrong guess. You are hanged!!!\n")
print("The word was:",already_guessed,word)
play_loop()
if word == '_' length: print("Congrats! You have guessed the word correctly!") play_loop()
elif count != limit: hangman()
main()
hangman()
def main(): global count global display global word global already_guessed global length global play_game words_to_guess = ["january","border","image","film","promise","kids","lungs","doll","rhyme","damage","plants"] word = random.choice(words_to_guess) length = len(word) count = 0 display = '_' length
already_guessed = []
play_game = ""
def play_loop():
global play_game
play_game = input("Do You want to play again? y = yes, n = no \n")
while play_game not in ["y", "n","Y","N"]:
play_game = input("Do You want to play again? y = yes, n = no \n")
if play_game == "y":
main()
elif play_game == "n":
print("Thanks For Playing! We expect you back again!")
exit()
def hangman():
global count
global display
global word
global already_guessed
global play_game
limit = 5
guess = input("This is the Hangman Word: " + display + " Enter your guess: \n")
guess = guess.strip()
if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9":
print("Invalid Input, Try a letter\n")
hangman()
elif guess in word:
already_guessed.extend([guess])
index = word.find(guess)
word = word[:index] + "_" + word[index + 1:]
display = display[:index] + guess + display[index + 1:]
print(display + "\n")
elif guess in already_guessed:
print("Try another letter.\n")
else:
count += 1
if count == 1:
time.sleep(1)
print(" _ \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
elif count == 2:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
elif count == 3:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | | \n"
" | \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
elif count == 4:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | | \n"
" | O \n"
" | \n"
" | \n"
"__|__\n")
print("Wrong guess. " + str(limit - count) + " last guess remaining\n")
elif count == 5:
time.sleep(1)
print(" _ \n"
" | | \n"
" | |\n"
" | | \n"
" | O \n"
" | /|\ \n"
" | / \ \n"
"__|__\n")
print("Wrong guess. You are hanged!!!\n")
print("The word was:",already_guessed,word)
play_loop()
if word == '_' length: print("Congrats! You have guessed the word correctly!") play_loop()
elif count != limit: hangman()
main()
hangman()
۲:۳۹