0% found this document useful (0 votes)
108 views4 pages

Emulating Do While Loop in Python

Python does not have a do-while loop like other languages, but it can be emulated using a while True loop and a break statement. Several examples are given of using while True loops to get input from the user until a certain condition is met, similar to how a do-while loop works. Python also does not have a switch statement, but if-elif-else statements and match-case expressions can be used instead to achieve similar functionality to a switch.

Uploaded by

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

Emulating Do While Loop in Python

Python does not have a do-while loop like other languages, but it can be emulated using a while True loop and a break statement. Several examples are given of using while True loops to get input from the user until a certain condition is met, similar to how a do-while loop works. Python also does not have a switch statement, but if-elif-else statements and match-case expressions can be used instead to achieve similar functionality to a switch.

Uploaded by

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

do while loop in Python

Python does not have built-in functionality to explicitly create a do while  loop like other
languages. But it is possible to emulate a do while loop in Python.

How to emulate a do while loop in Python


To create a do while loop in Python, you need to modify the while loop a bit in order to get similar
behavior to a do while loop in other languages.
As a refresher so far, a do while loop will run at least once. If the condition is met, then it will run again.
The while loop, on the other hand, doesn't run at least once and may in fact never run. It runs when and
only when the condition is met.
while True:
do_something()
if condition():
break

Python doesn't have do-while loop. But we can create a program like this.
The do while loop is used to check condition after executing the statement. It is like
while loop but it is executed at least once.
Syntax while if
while True:
# statement (s)
If not condition:
break;

i=1
while True:
print(i)
i=i+1
if(i > 5):
break

i = int(input("enter no 1 to 5 = "))
while True:
print(i)
i=i+1
if(i > 5):
break

#The code will run at least one time, asking for user input.
secret_word = "python"
counter = 0

while True:
word = input("Enter the secret word: ").lower()
counter = counter + 1
if word == secret_word:
break
if word != secret_word and counter > 7:
input("you lost")
break
#: take multiple input from user until press y / n
while True:
a = int(input("Enter no.: "))
print("square root is " , a*a)
reply = input('do you want to continue (y/n): ')
if reply == 'n': break

Python Switch Case Statement


Is there any python switch statement?
It is usually found that the use of switch statements is very rare while programming in the python language. So,
always a question arises whether the python language supports the switch case statements or not? Well, the answer
to this question is NO. Unlike any other programming language, python language does not have switch statement
functionality. This is also a trick question for students to get in their python assignments. So, we use the other
alternatives which can replace the switch case statement functionality and make the programming easier and faster.
Let us study each python switch statement one by one below.

Method 1) If-elif-else
lang = input("What's the programming language you want to learn?- JavaScript, Python, PHP, Solidity,
Java== ")
if lang == "JavaScript":
print("You can become a web developer.")

elif lang == "Python":


print("You can become a Data Scientist")

elif lang == "PHP":


print("You can become a backend developer")

elif lang == "Solidity":


print("You can become a Blockchain developer")

elif lang == "Java":


print("You can become a mobile app developer")
else:
print("The language doesn't matter, what matters is solving problems.")

Method 2) match-case
#EXAMPLE2: An example of a switch statement written with the match case syntax is shown below. It
is a program that prints what you can become when you learn various programming languages:

lang = input("What's the programming language you want to learn?- JavaScript, Python, PHP, Solidity,
Java== ")
match lang:
case "JavaScript":
print("You can become a web developer.")

case "Python":
print("You can become a Data Scientist")

case "PHP":
print("You can become a backend developer")

case "Solidity":
print("You can become a Blockchain developer")

case "Java":
print("You can become a mobile app developer")
case _:
print("The language doesn't matter, what matters is solving problems.")

#example3:
num1 = int(input("enter ist no. "))
num2 = int(input("enter iind no. "))
choice = int(input("1-addition, 2-subtraction 3-multiplication, 4-division "))
match choice:
case 1:
print("THE ADDITION OP IS",num1+num2)

case 2:
print("THE ADDITION OP IS",num1-num2)

case 3:
print("THE ADDITION OP IS",num1*num2)

case 4:
print("THE ADDITION OP IS",num1/num2)
case _:
print(" SORRY WRONG OPTIONS")

a=int(input("entre a no"))
b=1
c=1
while b<=a:
 c=c*b
 b+=1
print("factorial",c)

a=int(input("entre"))
b=int(input(" entre"))
while b<=a:
    if b%2==0:
        print("even",b)
    else:
        print("odd",b)
    b=b+1

HOMEWORK

SWITCH = AREA OF CIRCLE,RECT,TRI,SQUARE

WHITE TRUE: SIMPLE INTEREST

Common questions

Powered by AI

Python does not have a native switch case statement like some other programming languages. However, similar functionality can be achieved using alternatives such as if-elif-else statements and the match-case syntax introduced in Python 3.10. These alternatives are necessary for situations where the programmer requires a multi-way branch, a function typically provided by switch statements in other languages. For instance, the if-elif-else construct allows evaluation of multiple expressions, executing the associated block under the first condition that is true, as shown in the example of determining career paths based on programming language input: 'if lang == "JavaScript": print("You can become a web developer.")'

The 'match-case' syntax, introduced in Python 3.10, enhances code readability and maintainability by providing a more structured and clear way to handle multiple conditional branches. Unlike 'if-elif-else', which can become cumbersome and difficult to manage with many conditions, 'match-case' offers a cleaner syntax that resembles a switch case structure found in other languages. This format allows developers to easily see each distinct case directly associated with its expression, improving readability. Additionally, the default case, represented as 'case _:', simplifies handling of unmatched conditions, contributing to more maintainable code by ensuring that all logical paths are considered.

A do while loop in Python can be emulated by using a while loop with a True condition and an if statement for breaking. This involves placing the main loop logic inside a 'while True:' loop and using an if condition to break out of the loop when necessary. This ensures that the loop executes at least once before the condition is checked, similar to traditional do while loops in other languages. For example: 'while True: do_something() if condition(): break' The above code will run 'do_something()' at least once, and then condition() will determine if the loop should terminate.

Using a 'while True' loop with a break statement can be advantageous because it provides fine-grained control over the flow of the loop, allowing it to run indefinitely until a specific condition is met. This construct ensures that the code within the loop executes at least once, addressing cases where at least one execution is guaranteed. This approach is particularly useful when the continuation condition is complex or requires dynamic evaluation at different stages within the loop, which would be cumbersome or inefficient using alternative constructs like a typical 'while' or 'for' loop. Moreover, using 'while True' with explicit break conditions can make the exit logic clearer and separate from other loop-related logic, thereby improving code clarity.

The emulation of a do while loop using 'while True:' in Python exemplifies the language's flexibility because it demonstrates how Python can adapt to support logical constructs that are not natively available. By employing 'while True:', a standard while loop is effectively modified to behave like a do while loop, running the loop body at least once before evaluating the exit condition. This capability indicates Python's versatility in allowing constructs from other languages to be implemented creatively through existing features, enhancing its utility across different programming paradigms despite its simpler base structure. Such adaptability is critical for writing versatile code that can mirror the logic of other languages when porting programs or concepts.

You might also like