0% found this document useful (0 votes)
21 views3 pages

50 Python While Loop Examples

The document contains 50 basic Python programs that utilize while loops to solve various problems, such as finding the smallest digit in a number, checking for prime numbers, and counting consonants in a string. Each program includes code snippets and outputs for clarity. The examples cover a range of topics including mathematical operations, string manipulations, and basic games.

Uploaded by

garimaagrawalibm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views3 pages

50 Python While Loop Examples

The document contains 50 basic Python programs that utilize while loops to solve various problems, such as finding the smallest digit in a number, checking for prime numbers, and counting consonants in a string. Each program includes code snippets and outputs for clarity. The examples cover a range of topics including mathematical operations, string manipulations, and basic games.

Uploaded by

garimaagrawalibm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

50 Basic Python While Loop Programs with Solutions

31. Find smallest digit in a number


n = 4629
smallest = 9
while n > 0:
d = n % 10
if d < smallest:
smallest = d
n //= 10
print("Smallest digit =", smallest)

32. Check prime number using while loop


n = 17
i=2
flag = True
while i < n:
if n % i == 0:
flag = False
break
i += 1
if flag:
print("Prime")
else:
print("Not prime")

33. Count consonants in a string


s = "education"
i=0
count = 0
while i < len(s):
if s[i].isalpha() and s[i] not in "aeiou":
count += 1
i += 1
print("Consonants =", count)

34. Find sum of squares of digits of a number


n = 234
sum_sq = 0
while n > 0:
d = n % 10
sum_sq += d*d
n //= 10
print("Sum of squares =", sum_sq)

35. Print cube of numbers from 1 to 5


i=1
while i <= 5:
print(i**3)
i += 1

36. Find gcd of two numbers


a, b = 48, 18
while b != 0:
a, b = b, a % b
print("GCD =", a)

37. Find lcm of two numbers


a, b = 12, 15
lcm = a*b
x, y = a, b
while x != y:
if x < y:
x += a
else:
y += b
print("LCM =", x)
38. Count spaces in a string
s = "Python is easy"
i=0
count = 0
while i < len(s):
if s[i] == " ":
count += 1
i += 1
print("Spaces =", count)

39. Remove vowels from a string


s = "education"
i=0
result = ""
while i < len(s):
if s[i] not in "aeiou":
result += s[i]
i += 1
print(result)

40. Print first n multiples of 3


n=5
i=1
while i <= n:
print(3*i)
i += 1

41. Reverse list using while loop


lst = [1, 2, 3, 4]
i = len(lst)-1
rev = []
while i >= 0:
[Link](lst[i])
i -= 1
print(rev)

42. Print ASCII value of each character in a string


s = "ABC"
i=0
while i < len(s):
print(s[i], ord(s[i]))
i += 1

43. Count uppercase letters in a string


s = "PyThOn"
i=0
count = 0
while i < len(s):
if s[i].isupper():
count += 1
i += 1
print("Uppercase count =", count)

44. Count lowercase letters in a string


s = "PyThOn"
i=0
count = 0
while i < len(s):
if s[i].islower():
count += 1
i += 1
print("Lowercase count =", count)
45. Remove digits from a string
s = "Py123thon45"
i=0
result = ""
while i < len(s):
if not s[i].isdigit():
result += s[i]
i += 1
print(result)

46. Find power of a number using while loop


base, exp = 2, 5
result = 1
i=1
while i <= exp:
result *= base
i += 1
print("2^5 =", result)

47. Find average of numbers in a list


lst = [10, 20, 30, 40]
i=0
sum_ = 0
while i < len(lst):
sum_ += lst[i]
i += 1
avg = sum_ / len(lst)
print("Average =", avg)

48. Convert decimal to binary


n = 10
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
print("Binary =", binary)

49. Convert binary to decimal


binary = "1010"
i = len(binary)-1
decimal = 0
power = 0
while i >= 0:
decimal += int(binary[i]) * (2**power)
power += 1
i -= 1
print("Decimal =", decimal)

50. Guess the number game


secret = 7
guess = 0
while guess != secret:
guess = int(input("Enter guess: "))
print("You guessed it!")

Common questions

Powered by AI

The Python code determines the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. The algorithm repeatedly replaces the larger number by its remainder with respect to the smaller number, until one of the numbers becomes zero. At that point, the other number is the GCD. The implementation is as follows: `a, b = 48, 18; while b != 0: a, b = b, a % b; print('GCD =', a)` .

The script removes digits from a string by iterating through each character and appending non-digit characters to a new string. This ability to filter characters can be critical for data cleaning, preparing textual data for analysis where numeric values might introduce noise. The code is `s = "Py123thon45"; result = ''; i = 0; while i < len(s): if not s[i].isdigit(): result += s[i]; i += 1; print(result)` .

The program converts a decimal number to binary by continuously dividing the number by 2 and storing the remainder. This remainder signifies each bit in the binary representation starting from the least significant bit. When the decimal number be`a comprehensive insight into binary representations is crucial in computer science and digital electronics where binary is the fundamental language. The code snippet: `n = 10; binary = ''; while n > 0: binary = str(n % 2) + binary; n //= 2; print('Binary =', binary)` demonstrates this conversion.

The guessing game repeatedly prompts the user to input a guess until it matches a predefined secret number. By keeping the variable `guess` in a while loop with condition `guess != secret`, it ensures that the interaction continues until the correct guess is made. Enhancements like providing hints or limiting attempts can improve user engagement and manageability. The basic structure: `secret = 7; guess = 0; while guess != secret: guess = int(input('Enter guess: ')); print('You guessed it!')` .

Using a loop to calculate power involves multiplying the base by itself, iterating `exp` times. This iterative approach helps in understanding the underlying mechanics of exponentiation and can be modified for non-standard operations like modular exponentiation, essential in cryptography. In contrast, Python's `**` operator is concise and optimized for typical exponentiation. The loop is: `base, exp = 2, 5; result = 1; i = 1; while i <= exp: result *= base; i += 1; print('2^5 =', result)` .

The Python program counts consonants in a string by iterating through each character, checking if it is an alphabetic character and not a vowel. The count is incremented for consonants only. This involves checking membership in the string "aeiou" and calling `isalpha()`. The given code: `s = "education"; i = 0; count = 0; while i < len(s): if s[i].isalpha() and s[i] not in "aeiou": count += 1; i += 1; print('Consonants =', count)` .

The Python program finds the LCM by initializing two variables `x` and `y` with the values of `a` and `b` respectively. It then incrementally increases `x` or `y` by `a` or `b` until they become equal, which is the LCM. Another method involves using the relationship `LCM(a, b) * GCD(a, b) = a * b` for a more efficient calculation, especially beneficial for large numbers. The implemented method: `a, b = 12, 15; x, y = a, b; while x != y: if x < y: x += a; else: y += b; print('LCM =', x)` .

Counting uppercase letters in a string checks case sensitivity, which is crucial in tasks like formatting or parsing data where uppercase may indicate proper nouns or specific emphasis. This loop methodually traverses the string and applies `isupper()` to identify such letters. Its significance extends to natural language processing and data normalization. The code is: `s = "PyThOn"; i = 0; count = 0; while i < len(s): if s[i].isupper(): count += 1; i += 1; print('Uppercase count =', count)` .

Reversing a list with a while loop involves iterating backward from the last index to zero, appending each element to a new list. This manual method contrasts with Python's built-in function `reversed()` or slicing (e.g., `list[::-1]`), which are more concise and optimized. The manual approach used is: `lst = [1, 2, 3, 4]; i = len(lst)-1; rev = []; while i >= 0: rev.append(lst[i]); i -= 1; print(rev)` .

The code checks if a number, `n`, is prime by testing divisibility from 2 to `n-1`. A flag `True` indicates primality, and it changes to `False` if any divisibility is detected. However, this approach is inefficient for large numbers due to unnecessary checks beyond the square root of `n`. A more optimal method would check divisibility up to the square root of `n` only. The code snippet is: `n = 17; i = 2; flag = True; while i < n: if n % i == 0: flag = False; break; i += 1` .

You might also like