Python — самый быстрорастущий язык программирования в мире. Благодаря своей высокоуровневой, интерпретируемой и объектно-ориентированной архитектуре он подходит для всех типов программных решений. Он имеет простой синтаксис, похожий на естественный язык, что упрощает его чтение и понимание.

Вы можете ознакомиться с пошаговым руководством по установке Python в Visual Studio Code здесь или загрузить PyCharm, IDE для python здесь.

Ниже приведены программы, описывающие ввод, вывод, присваивание, циклы, массивы и другие функции Python 3. Вы можете запустить эти программы на своей стороне, чтобы лучше понять, как они работают.

Оглавление

Программа для вывода сообщения
Программа, присваивающая значения переменным
Программа, выполняющая сложение двух чисел
Программа, запрашивающая ввод от пользователя
Программа с условным оператором (if…else)
Пока цикл
По циклу
Программа, выполняющая итерацию
По циклу (в диапазон)
Массивы в Python

I) Программа для отображения сообщения

print("Hello World!")

Выход:

Hello World!

II) Программа, присваивающая значения переменным

x=5 
#since integer 5 is assigned to x, then x becomes an integer variable, i.e., the datatype of x is now integer
outstring="Hello world!" 
#since a text is assigned to outstring, then outstring becomes a string variable, i.e., the datatype of outstring is now string

III) Программа, выполняющая сложение двух чисел

x=5 
#value 5 is assigned to x
y=4
sum= x+y 
#adds the values of x and y and assigns the result to sum
print("The sum of", x, "and",  y, "is", sum) 
#prints the sum of x and y

Выход:

The sum of 5 and 4 is 9

IV) Программа запрашивает ввод данных у пользователя

print("Enter your name: ", end="") 
#prompts the user to enter their name
name=input() 
#reads the user's input and assigns it to the variable name

ДРУГОЙ ПУТЬ

name=input("Enter your name: ") 
#prompts the user to enter his/her name

Терминал:

Please enter your name: Farhaan

V) Программа с условным оператором (if…else)

num=input("Enter a number: ") 
#Assume only real numbers can be entered
if(int(num)>0): 
#if the condition evaluates to true then positive is displayed
    print("Positive")
else: 
#if the condition evaluates to false then negative is displayed
    print("Negative")

Выход:

Enter a number: 5
Positive

VI) Программа с циклом while

num = 1
while num < 5: #while loop
  print(num) #prints the value of num
  num+= 1 #incrementing the value of num by 1

Выход:

1
2
3
4

VII) Программа с циклом for

x = ["1", "2", "3"] # List of strings
for i in x: # Loop through the list
   print(i)
else:
   print("No more data") # Print this when the loop is done

Выход:

1
2
3
No more data

VIII) Программа, выполняющая итерацию

text="Hello World!"
for i in text: #for each character in text
    print (i, end="") #print the character

Выход:

Hello World!

IX) Программа с циклом for (в диапазоне)

sum=0
for i in range(10): #0 to 9
    sum= sum + 1
print(sum)

Выход:

10

X) Массивы в Python

Python не имеет встроенной поддержки массивов, но имеет тип данных, называемый списком, который функционально очень похож на массивы из C/C++.

Важные методы для Array/List в Python

append()
clear()
copy()
count()
extend()
index()
insert()
pop ()
remove()
reverse()
sort()

Ниже приведены примеры использования некоторых методов.

array =["red", "blue", "yellow", "green"] #initial array

а) добавить()

print("The initial array: ",array)
array.append("purple") #add purple to the end of the array
print("Final array: ",array)

Выход:

The initial array:  ['red', 'blue', 'yellow', 'green']
Final array:  ['red', 'blue', 'yellow', 'green', 'purple']

б) удалить()

print("The initial array: ",array)
array.remove("blue") #remove blue from the array
print("Final array: ",array)

Выход:

The initial array:  ['red', 'blue', 'yellow', 'green', 'purple']
Final array:  ['red', 'yellow', 'green', 'purple']

в) поп()

print("The initial array: ",array)
array.pop(2) #remove the element at index 2
print("Final array: ",array)

Выход:

The initial array:  ['red', 'yellow', 'green', 'purple']
Final array:  ['red', 'yellow', 'purple']

г) вставить()

print("The initial array: ",array)
array.insert(0, "orange") #insert orange at the beginning of the array(overwritting existing element)
print("Final array: ",array)

Выход:

The initial array:  ['red', 'yellow', 'purple']
Final array:  ['orange', 'red', 'yellow', 'purple']

e) sort() по возрастанию

print("The initial array: ",array)
array.sort(reverse=False) #sort the array in ascending order
print("Final array: ",array)

Выход:

The initial array:  ['orange', 'red', 'yellow', 'purple']
Final array:  ['orange', 'purple', 'red', 'yellow']

f) sort() по убыванию

print("The initial array: ",array)
array.sort(reverse=True) #sort the array in descending order
print("Final array: ",array)

Выход:

The initial array:  ['orange', 'purple', 'red', 'yellow']
Final array:  ['yellow', 'red', 'purple', 'orange']

Большое спасибо, что нашли время, чтобы прочитать мою статью. Не забудьте подписаться на меня, чтобы не пропустить следующие статьи. Вы также можете ознакомиться с моим портфолио здесь.