فيما يلي مجموعة من الامثلة على استخدام حلقات for في بايثون:
طباعة كلمة hello عشر مرات:
طباعة كلمة hello عشر مرات:
مثال
#print the word "hello" 10 times
for i in range(0,10):
print("hello")
طباعة جميع الاعداد الصحيحة بين 1 و 100 :
طباعة جميع الاعداد الصحيحة بين 1 و 100 :
مثال
# print the all integer numbers between 1 to 100
print("integer numbers between 1 to 100 are:")
for i in range(1, 101):
print(i)
طباعة جميع الاعداد الزوجية بين 1 و 100 :
طباعة جميع الاعداد الزوجية بين 1 و 100 :
مثال
#print all even numbers between 1 to 100 for i in range(1, 101): if i%2==0: print(i)
طباعة جميع الاعداد الفردية بين 1 و 100 :
طباعة جميع الاعداد الفردية بين 1 و 100 :
مثال
#print all odd numbers between 1 to 100 for i in range(1, 101): if i%3==0: print(i)
طباعة احرف اللغة الانجليزية بشكل صغير small letters:
طباعة احرف اللغة الانجليزية بشكل صغير small letters:
مثال
#print all english small letters for i in range(97,123): print(chr(i))
طباعة احرف اللغة الانجليزية بشكل كبير capital letters:
طباعة احرف اللغة الانجليزية بشكل كبير capital letters:
مثال
#print all english capital letters for i in range(65,91): print(chr(i))
انشاء مصفوفة من الارقام ومن ثم طباعة عناصر المصفوفة باستخدام حلقة for :
انشاء مصفوفة من الارقام ومن ثم طباعة عناصر المصفوفة باستخدام حلقة for :
مثال
#create an array of numbers, then print it's values using for loop: numbers=[23,3,3,22,523,232] for index in range(0,6): print(numbers[index])
برنامج يطبع محتويات مصفوفة عن طريقة تمريرها بحلقة:
برنامج يطبع محتويات مصفوفة عن طريقة تمريرها بحلقة:
مثال
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)
برنامج يمر على جميع احرف كلمة معينة ويطبع كل حرف
برنامج يمر على جميع احرف كلمة معينة ويطبع كل حرف
مثال
for x in "banana": print(x)
الخروج من الحلقة عندما تصل للكلمة banana :
الخروج من الحلقة عندما تصل للكلمة banana :
مثال
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break
نفس المثال السابق لكن يتجاهل طباعة الكلمة banana ويكمل طباعة جميع عناصر المصفوفة :
نفس المثال السابق لكن يتجاهل طباعة الكلمة banana ويكمل طباعة جميع عناصر المصفوفة :
مثال
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
طباعة الاعداد من 1 الى 4
طباعة الاعداد من 1 الى 4
مثال
#print the numbers between 1 to 4, using for loop
for i in range(1, 5):
print(i)
print('The for loop is over')
while loops
برنامج يطبع كلمة hello مئة مرة
مثال
#write python program to print the word 'hello' 100 times
counter=1
while counter<=100:
print('hello')
counter=counter+1
برنامج بايثون يطبع الاعداد بين 1 الى 100
برنامج بايثون يطبع الاعداد بين 1 الى 100
مثال
#write python program to print the numbers between 1 to 100 counter=1 while counter<=100: print(counter) counter=counter+1
برنامج يطبع قيمة العداد في كل لفة , وبعد انتهاء الحلقة يطبع كلمة good bye
برنامج يطبع قيمة العداد في كل لفة , وبعد انتهاء الحلقة يطبع كلمة good bye
مثال
count = 0 while (count < 9 xss=removed>
لعبة تحزير الكلمات, لكن باستخدام الحلقات, بحيث يظل البرنامج يطلب من المستخدم ادخال القيمة مادامت غير صحيحة
لعبة تحزير الكلمات, لكن باستخدام الحلقات, بحيث يظل البرنامج يطلب من المستخدم ادخال القيمة مادامت غير صحيحة
مثال
#guess game
correctNumber=int(input("please enter the number "))
running=True
while running==True:
guess=int(input("enter your guess:"))
if guess==correctNumber:
print("congratulations,, you guessed it!")
running=False
elif guess>correctNumber:
print("wrong number, your number is bigger than correct number")
elif guess
برنامج يطبع الاعداد الزوجية بين 1 الى 100
برنامج يطبع الاعداد الزوجية بين 1 الى 100
مثال
#write python program to print the even numbers between 1 to 100
c=1
while c<=100:
if c % 2==0:
print(c)
c = c + 1
print("done")
برنامج يطبع الاعداد الفردية بين 1 الى 100
برنامج يطبع الاعداد الفردية بين 1 الى 100
مثال
#write python program to print the odd numbers between 1 to 50
x=1
while x<=100:
if x % 3==0:
print(x)
print("done")
برنامج لحساب قيمة الاس
برنامج لحساب قيمة الاس
مثال
#Write python program that computes n^p where n and p are two numbers given by the user.
n=int(input('enter the number'))
p=int(input('enter the power'))
counter=1
result=1
while counter<=p:
result*=n #same as result=result*n
counter+=1 #same counter=counter+1
print("result is :",result)
برنامج يحسب مجموع الجذور التربيعية للاعداد من 1 الى n
برنامج يحسب مجموع الجذور التربيعية للاعداد من 1 الى n
مثال
#Exercise: Write python program that computes the sum of the squares between 1 and n where n is given
#by the user. Use while to ensure that the value of n is strictly positive.
import math
summ=0
n=int(input("enter n:"))
i=1
while i<=n:
summ+=math.sqrt(i)
i+=1
print("sum of squares is: ",summ)
تعريف مصفوفة list من الارقام وكيفية استدعاء عناصر معينة منها:
تعريف مصفوفة list من الارقام وكيفية استدعاء عناصر معينة منها:
مثال
numbers=[12,2,22,2,94,2] print(numbers[0]) print(numbers[3]) print(numbers[-1]) #prints 2 print(numbers[2:5]) #prints: 22,2,94 print(numbers[:4]) #prints: 12,2,22,2 print(numbers[2:]) #prints: 22,2,94,2 print(numbers[-4:-1]) #prints: 22,2,94
انشاء List ومن ثم طباعة قيم عناصرها وعدد عناصرها:
انشاء List ومن ثم طباعة قيم عناصرها وعدد عناصرها:
مثال
thislist = ["apple", "banana", "cherry"]
print(thislist)
print("list length is : "+len(thislist))
#Check if "apple" is present in the list:
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
لديك خيارات كثيرة عند انشاء list, وانواع بيانات كثيرة, وايضا بامكانك وضع عناصر بانواع بيانات مختلفة عن بعضها:
لديك خيارات كثيرة عند انشاء list, وانواع بيانات كثيرة, وايضا بامكانك وضع عناصر بانواع بيانات مختلفة عن بعضها:
مثال
#String, int and boolean data types: list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False] #A list with strings, integers and boolean values: list1 = ["abc", 34, True, 40, "male"]
كيف تعديل قيمة عنصر في list:
كيف تعديل قيمة عنصر في list:
مثال
#Change the second item: thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) #Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon": thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermelon"] print(thislist) #Change the second value by replacing it with two new values: thislist = ["apple", "banana", "cherry"] thislist[1:2] = ["blackcurrant", "watermelon"] print(thislist) #Change the second and third value by replacing it with one value: thislist = ["apple", "banana", "cherry"] thislist[1:3] = ["watermelon"] print(thislist) #Insert "watermelon" as the third item: thislist = ["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist)
اضافة عنصر جديد الى list:
اضافة عنصر جديد الى list:
مثال
#Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
#Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
#Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
#Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
حذف عنصر من list:
حذف عنصر من list:
مثال
#Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
#Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
#Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
#Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
#Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
#Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
طرق استعراض العناصر في List:
طرق استعراض العناصر في List:
مثال
#Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) #Print all items by referring to their index number: thislist = ["apple", "banana", "cherry"] for i in range(len(thislist)): print(thislist[i]) #Print all items, using a while loop to go through all the index numbers thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i = i + 1 #A short hand for loop that will print all items in a list: thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist]
امثلة عن استخدامات Continue
امثلة عن استخدامات Continue
مثال
var = 10
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print("Good bye!")
امثلة عن استخدامات Break
امثلة عن استخدامات Break
مثال
#this exerice to practice on using the break statement
#write a program that keep asking user to enter any thing in keyboard untill user enters the word 'quit'
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
python functions examples
امثلة على استخدامات التوابع في python
function code in python
مثال
#write a python program, to define a function and call it back
def say_hello():
# block belonging to the function
print('hello world')
# End of function
say_hello() # call the function
say_hello() # call the function again
Function default:
Function default:
مثال
#this program is to explain the idea of default argument(parameter)
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5)
Function global:
Function global:
مثال
x = 50
def func():
global x
print('x is', x)
x = 2
print('Changed global x to', x)
func()
print('Value of x is', x)
Function local:
Function local:
مثال
#this code is to explain the principle of local variables
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
print(x)
func(f)
print('x is still', x)
Function keyword:
Function keyword:
مثال
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Function param:
Function param:
مثال
#this program do the following: define a function with parameters then call it def print_max(a, b): if a > b: print(a, 'is maximum') elif a == b: print(a, 'is equal to', b) else: print(b, 'is maximum') # directly pass literal values print_max(3, 4) x = 5 y = 7 # pass variables as arguments print_max(x, y)
Function return:
Function return:
مثال
def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: return y print(maximum(2, 3))
Example on functions: Traffic light program
Example on functions: Traffic light program
مثال
#write python program that prompts user to enter the color of traffic light, and then acts upon it.
def guessLight(l):
if l == 'red':
print('stop')
elif l == 'yellow':
print('Slow down')
elif l == 'green':
print('go')
else:
print('invalid entry, Choose between red, green, and yellow.')
light = input('please enter the color of traffic light')
guessLight(light.lower())
'''Exercise 1: Write a function f that computes f(x) where f(x) = x^3 - x + 1. (2 solutions are expected: with and without calling pow() from cmath library)'''
مثال
'''Exercise 1: Write a function f that computes f(x) where f(x) = x^3 - x + 1. (2 solutions
are expected: with and without calling pow() from cmath library)'''
import cmath
def f(x):
#i= x ** 3 - x + 1 #without using pow()
i=pow(x,3)-x+1 #using pow()
print('the result is ',i)
#Exercise : Write a function g that computes g(x, y) where g(x, y) = x^2 + √2
مثال
#Exercise : Write a function g that computes g(x, y) where g(x, y) = x^2 + √2
import math
def g(x , y):
return x**2 + math.sqrt(y)
print("example: result of g(2,3) is : ",g(2,3))
مثال عملي كبير: برنامج الة حاسبة باستخدام التوابع functions:
مثال عملي كبير: برنامج الة حاسبة باستخدام التوابع functions:
مثال
#create simple calculater و using functions:
def sum(num1,num2):
return num1+num2
def subtract(num1,num2):
return num1-num2
def multiply(num1,num2):
return num1*num2
def divide(num1,num2):
return num1/num2
def remainder(num1,num2):
return num1%num2
def power(number,power):
counter = 1
result = 1
while counter <= power:
result *= number # same as result=result*n
counter += 1 # same counter=counter+1
return result
x=int(input('please enter first number:'))
y=int(input('please enter second number:'))
choice=input("1.summation\n2.subtract\n3.multiply\n4.divide\n5.remainder\n6.power")
if choice=="1":
print('the summation result is :' , sum(x,y))
elif choice=="2":
print('the subtraction result is :',subtract(x,y))
elif choice=="3":
print('the multiplication result is :',multiply(x,y))
elif choice=="4":
print('the division result is :',divide(x,y))
elif choice == "5":
print('the remainder result is :', remainder(x, y))
elif choice == "6":
print('the power result is :',power(x, y))
else:
print("invalid entry")