While len i python 3

Цикл while

Цикл while (“пока”) позволяет выполнить одну и ту же последовательность действий, пока проверяемое условие истинно. Условие записывается до тела цикла и проверяется до выполнения тела цикла. Как правило, цикл while используется, когда невозможно определить точное значение количества проходов исполнения цикла.

i = 0
while i 5 :
print (i)
i += 1

Цикл while и цикл for имеют схожую структуру, НО есть одно важное различие — цикл while может быть бесконечным.

Читайте также:  Python numpy array to bytes

i = 0
while True :
print (i)
i += 1

# Вывод:
>>> 0
>>> 1
>>> 2
>>> 3
>>> 4
# Это может продолжаться долго.

Код выше будет бесконечно печатать возрастаютщую последовательность чисел.

Цикл while можно сравнить с цикличным условным оператором.

text = ‘Hello world’
i = 0
while i len (text):
print (text[i])
i += 1

Код, приведенный выше, печатает строку посимвольно. Приведу пример аналогичного цикла for:

text = ‘Hello world’
for i in text:
print (i)

Более того, я приведу даже два цикла for!

text = ‘Hello world’
for i in range ( len (text)):
print (text[i])

Напомню, что отличие между двумя, приведенными выше примерами, в следующем: первый цикл проходит по элементам последовательности (в нашем случае строки), а второй — по ее индексам. Здесь также используется функция len(), которая позволяет узнать длину последовательности.

Вернемся к циклу while. Цикл while, как и цикл for, можно остановить с помощью специальной управлющей конструкции break.

j = 0
while True :
if j == 3 :
print ( ‘Выход из цикла’ )
break
print (j)
j += 1

Конструкция break прерывает цикл. Она очень похожа на обычное условие после ключевого слова while.

Так же есть еще одна управляющая конструкция — continue. С ее помощью мы можем не выпонять текущую итерацию (повторение) цикла и перейти сразу к следующему.

j = 0
while j 5 :
j += 1
if j == 3 :
print ( ‘Пропускаем j == 3 ‘ )
continue
print (j)

Как и для цикла for, для цикла while мы можем записать конструкцию else.

from random import randint
j = 0
element = randint ( 0 , 15 )
while j 10 :
j += 1
if j == element:
print ( ‘Нашли element, он равен’ , element)
break
else :
print ( ‘Неудачная попытка’ )

Примеры решения задач

Возведение числа в степень с помощью цикла while

n = int ( input ()) # число
k = int ( input ()) # степень
i = 1 # текущая степень
result = 1
while i k:
result *= n
i += 1
print (result)

Сумма последовательности с помощью цикла while

n = int ( input ())
result = 0
i = 0
while i n:
result += i
i += 1
print (result)

Ввод последовательности чисел

i = 0
while True :
n = input ()
if n == ‘end’ :
print ( ‘Ввод закончен’ )
print ( ‘Было введено’ , i, ‘чисел’ )
break
n = int (n)
i += 1

i = 0
summa = 0
while True :
n = input ()
if n == ‘end’ :
print ( ‘Ввод закончен’ )
print ( ‘Было введено’ , i, ‘чисел’ )
print ( ‘Их сумма равна’ , summa)
break
n = int (n)
summa += n
i += 1

Решение задач

1. Дано положительное число N. Вывести все числа от 0 до N с помощью цикла while.

2. Дано положительное число N. Вывести все числа от N до 0 с помощью цикла while. Пример:

3. Даны два положительных числа K и N (K 4. Даны положительные числа A и B (A > B). На отрезке длины A размещено максимально возможное количество отрезков длины B (без наложений). Не используя операции умножения и деления, найти длину незанятой части отрезка A (взятие остатка A % B)

5. Даны положительные числа A и B (A > B). На отрезке длины A размещено максимально возможное количество отрезков длины B (без наложений). Не используя операции умножения и деления, найти количество отрезков B, размещенных на отрезке A (деление нацело A // B)

6. Дано положительное число N. Найти сумму всех четных чисел от 0 до N с помощью цикла while.

7. Даны два положительных числа K и N (K нечетных чисел от K до N с помощью цикла while.

8. Дано положительное число N. Найти факториал числа N. Факториалом числа называется произведение всех чисел от 1 до N. Например, факториал числа 5 равен 5! = 1*2*3*4*5 = 120 , 2! = 1*2 = 2 , 9! = 1*2*3*4*5*6*7*8*9 = 362880

9. Дано целое число N (> 0). Если оно является степенью числа 3, то вывести YES, если не является — вывести NO.

10. Дано целое число N (> 0). Найти двойной факториал N: N!! = N * (N-2) * (N-4)* . . Для решения этой задачи посмотрите на задачу 2

Сложные задачи

1. Дано целое число N (> 1). Найти наименьшее целое число K, при котором выполняется неравенство 3^K > N, где 3^K — это 3 в степени K или число 3, умноженное само на себя K раз. Например, 3^5 = 3*3*3*3*3 . Ответом в задаче будет первая степень числа 3, которая больше, чем заданное число N. Например, если N=41, распишем степени числа три: 3^1 = 3; 3^2 = 3*3 = 9; 3^3 = 3*3*3 = 27; 3^4 = 3*3*3*3 = 27 * 3 = 81; . Таким образом, первая степень, в которую возвести число 3, превышающая число N — это 4.
В этой задаче нужно выполнять цикл while, пока остаток от деления на число три равен 0

2. Дано целое число N (> 0). Используя операции деления нацело и взятия остатка от деления, вывести все его цифры, начиная с самой правой (разряда единиц).
Перед решением этой задачи вспомните, как найти сумму цифр трехначного числа.

3. Даны целые положительные числа A и B. Найти их наибольший общий делитель (НОД), используя алгоритм Евклида: НОД(A, B) = НОД(B, A mod B), если B = 0; НОД(A, 0) = A.

4. Спортсмен-лыжник начал тренировки, пробежав в первый день 10 км. Каждый следующий день он увеличивал длину пробега на P процентов от пробега предыдущего дня (P — вещественное, 0 5. Дано целое число N (> 1). Последовательность чисел Фибоначчи FK определяется следующим образом: F(1) = 1, F(2) = 1, F(K) = F(K-2) + F(K-1), K = 3, 4, . . Проверить, является ли число N числом Фибоначчи. Если является, то вывести TRUE, если нет — вывести FALSE.

6. Даны положительные числа A, B, C. На прямоугольнике размера A x B размещено максимально возможное количество квадратов со стороной C (без наложений). Найти количество квадратов, размещенных на прямоугольнике. Операции умножения и деления не использовать.

7. Дано целое число N (> 1), являющееся числом Фибоначчи: N = F(K). Найти целое число K — порядковый номер числа Фибоначчи N.

Источник

18 Python while Loop Examples and Exercises

Pythonista Planet Logo

In Python programming, we use while loops to do a task a certain number of times repeatedly. The while loop checks a condition and executes the task as long as that condition is satisfied. The loop will stop its execution once the condition becomes not satisfied.

The syntax of a while loop is as follows:

while condition: statements

In this post, I have added some simple examples of using while loops in Python for various needs. Check out these examples to get a clear idea of how while loops work in Python. Let’s dive right in.

1. Example of using while loops in Python

2. Example of using the break statement in while loops

In Python, we can use the break statement to end a while loop prematurely.

3. Example of using the continue statement in while loops

In Python, we can use the continue statement to stop the current iteration of the while loop and continue with the next one.

4. Using if-elif-else statements inside while loop

5. Adding elements to a list using while loop

myList = [] i = 0 while len(myList) < 4 : myList.append(i) i += 1 print(myList)

6. Python while loop to print a number series

7. Printing the items in a tuple using while loop

myTuple = (10,20,30,40,50,60) i = 0 while i < len(myTuple): print(myTuple[i]) i += 1

8. Finding the sum of numbers in a list using while loop

myList = [23,45,12,10,25] i = 0 sum = 0 while i < len(myList): sum += myList[i] i += 1 print(sum)

9. Popping out elements from a list using while loop

fruitsList = ["Mango","Apple","Orange","Guava"] while fruitsList: print(fruitsList.pop()) print(fruitsList)

10. Printing all letters except some using Python while loop

i = 0 word = "Hello" #print all letters except e and o while i < len(word): if word[i] == "e" or word[i] =="o": i += 1 continue print("Returned letter",word[i]) i += 1

11. Python while loop to take inputs from the user

n = int(input("Enter a number: ")) while n != 0: n = int(input("Enter zero to quit: "))

12. Converting numbers from decimal to binary using while loop

num = int(input("Enter a number: ")) b = 0 p = 1 n = num while n>0: rem = n%2 b += rem * p p = p*10 n = n//2 print("Binary value: ",b)

13. Finding the average of 5 numbers using while loop

p = 5 sum = 0 count = 0 while p > 0: count += 1 f = int(input("Enter the number ")) sum += f p -= 1 average = sum/count print("Average of given Numbers:",average)

14. Printing the square of numbers using while loop

15. Finding the multiples of a number using while loop

n = int(input("Enter an integer: ")) i = 1 while i 

16. Reversing a number using while loop in Python

n = int(input("Enter a number: ")) rev = 0 while n!=0: r = n%10 rev = rev * 10 + r n = n//10 print("Reversed number:",rev)

17. Finding the sum of even numbers using while loop

i = 0 sum = 0 n = int(input("Enter the number n: ")) while i 

18. Finding the factorial of a given number using while loop

n = int(input("Enter the number: ")) f =n r = 1 while f != 0 : r *= f f -= 1 print("Factorial of",n,"is:",r)

I hope this article was helpful. Check out my post on 21 Python for Loop Examples.

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

13 thoughts on “ 18 Python while Loop Examples and Exercises ”

I am looking for a way to take user inputs in while loop & compare it & print the smallest/largest value. Can you help?

9.) Popping out elements from a list using while loop
thank your us this kind of content for free appreciate 🙂
i was curious this # 9.)

while len(fruitsList) > 3:
fruitsList.pop()
print(fruitsList)

n=”e”
numlist = []while n != “”
n= int(input (“Enter A Number: “))
numlist.append(n)
print(numlist)
print(max(numlist))
print (min(numlist))

You can append the numbers in the list and find the minimum or maximum.

i=0
newlist=[] #create an empty list
while ix=int(input(' Enter numbers'))
i+=1
newlist.append(x)
print(newlist) #you may skip this line
print("The smallest number is", min(newlist))

The output will be:
Enter numbers 3
Enter numbers 4
Enter numbers 8
Enter numbers 2
Enter numbers 9
[3,4,8,2,9]The smallest number is 2

My bro ,u are too much oo,u really open my eyes to many things about pythons ,which I did not know b4 .pls am a beginer to this course .I need yr help oo,to enable me know more sir.
Thanks and God bless u

Printing the items in a tuple using while loop exercise shows wrong answer please review the answer.

I just checked again, and it is the correct answer. Can you check your code once again? Maybe you might have missed something in your code.

Hi, Ashwin Thanks for these informative and variative while loops examples; they are really helpful for practicing. 🙂

name = input(‘name’)
strip= input(‘word’)

# Now i want to see both methods while and for to striped out the strip’s values from the name’s letters.

no output is coming in example 10.

lst = []for i in range(5):
num = int(input(“Enter your numbers: “))
lst += [num]print(“The greater number is”,max(lst))
print(“The smallest number is”,min(lst))

How I wish you were able to write comments on your code lines to help newbies better understand the concept.

Leave a Reply Cancel reply

Recent Posts

Python is an amazing technology and there are so many things you can do with it. If you want to master Python language, you need to know some advanced concepts in Python along with the.

If you're like me, you probably like coding and learning new technologies. One such technology that you must learn is Git. In this article, let's go through the fundamentals of Git and I promise to.

About Me

Hi, I’m Ashwin Joy. I’m a Computer Science and Engineering graduate who is passionate about programming and technology. Pythonista Planet is the place where I nerd out about computer programming. On this blog, I share all the things I learn about programming as I go.

Pythonista Planet is the place where you learn technical skills and soft skills to become a better programmer. This site is owned and operated by Ashwin Joy. Pythonista Planet is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. This site also participates in affiliate programs of Udemy, Treehouse, Coursera, and Udacity, and is compensated for referring traffic and business to these companies.

Источник

Оцените статью