Home Backend Development Python Tutorial Day Mastering the Art of Conditional Statements and Loops

Day Mastering the Art of Conditional Statements and Loops

Jan 03, 2025 am 11:33 AM

Day Mastering the Art of Conditional Statements and Loops

Conditional Statements

Like other programming languages, Python also includes conditional statements. But the only difference is that instead of else if, we have elif.
Conditional statements control the flow of a program based on specific conditions. They enable decision-making by allowing the program to execute different blocks of code depending on whether a condition evaluates to True or False.
instead of explaining the if,elif and else individually let us cover them all in a single example.

if a%2==0:
   print("The Number is an Even Composite")
elif not_prime(a):
   print("The Number is an Odd Composite")
else:
   print("The Number is a Prime")
Copy after login
Copy after login

here, let the number be 3.
First the program will check whether the number is divisible by 2 (if a%2==0)
since it is not even, it goes to elif satement(if not_prime(a))
since neither the if, nor the elif are not true, the program will go to the else part and it will print:
The Number is a Prime

Key Features:

1. Logical Operators for Conditions

age=19
if age>18 and age<25:
   print("the person is an Young Adult")
Copy after login
Copy after login

2. Nested Conditional Statements

You can nest conditional statements within one another to evaluate complex conditions.

age = 20
if age >= 18:
    if age < 25:
        print("You are a young adult.")
    else:
        print("You are an adult.")
else:
    print("You are not an adult yet.")
Copy after login
Copy after login

3. Ternary Conditional Statements

bob_score=87
alen_score=92
answer=bob_score if bob_score>alen_score else alen_score
print(answer)
Copy after login
Copy after login

Answer:92

? Trick of the Day:

startswith() and endswith()

  • The startswith() and endswith() are string methods that return True if a specified string starts with or ends with a specified value.
  • Let’s say you want to return all the names in a list that starts with
    "a."

  • here is how you would use startswith() to accomplish that.

  • Using startswith():

listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.startswith('a')]
pri nt(new_li st)
Copy after login
Copy after login

Answer: ['apple', 'apricot']

  • Using endwith():
listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.endswith('e')]]
pri nt(new_li st)
Copy after login
Copy after login

Answer: ['apple', 'Orange']

Loops

In Addition to decision-making statements, Python programming also supports looping statements. There are

1. while
2. for

1. For Loop:

The for loop in Python iterates over a sequence (such as a list, tuple, string, or range) and performs an operation for each item in that sequence.

a=[1,2,3,4]
for i in a:
   print(a)
Copy after login
Copy after login

Answer: 0n 1n 2n 3n 4n

Here, the for loop iterates through all the elements in the list a and prints them.
Using range() with for:
You can use the range() function to generate a sequence of numbers.

if a%2==0:
   print("The Number is an Even Composite")
elif not_prime(a):
   print("The Number is an Odd Composite")
else:
   print("The Number is a Prime")
Copy after login
Copy after login

Answer: 0n 1 n 2n 3n

Range():
The basic syntax of the range() function is:

age=19
if age>18 and age<25:
   print("the person is an Young Adult")
Copy after login
Copy after login

here start=0 and step=1 by default.

age = 20
if age >= 18:
    if age < 25:
        print("You are a young adult.")
    else:
        print("You are an adult.")
else:
    print("You are not an adult yet.")
Copy after login
Copy after login

Answer:1n 2n
1n 3n

While Loop:

The while loop continues to execute the block of code as long as the condition evaluates to True.

bob_score=87
alen_score=92
answer=bob_score if bob_score>alen_score else alen_score
print(answer)
Copy after login
Copy after login

Answer: 4n 3n 2n 1n

1. break Statement

The break statement is used to terminate a loop prematurely, regardless of its condition. Once the break statement is executed, the control exits the loop.

listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.startswith('a')]
pri nt(new_li st)
Copy after login
Copy after login

Answer: 10n 9n 8n 7n 6n

2. continue Statement

The continue statement is used to skip the rest of the code in the current iteration and proceed to the next iteration of the loop.

listl = ['lemon','Orange','apple', 'apricot']
new_list = [i for i in listl if i.endswith('e')]]
pri nt(new_li st)
Copy after login
Copy after login

Answer: 1n 3n 5n 7n 9n

3. pass Statement

The pass statement is a placeholder used when a block of code is syntactically required but you don't want to execute any code. It literally does nothing.

a=[1,2,3,4]
for i in a:
   print(a)
Copy after login
Copy after login

Answer: 0n 1n 2n 4n

The above is the detailed content of Day Mastering the Art of Conditional Statements and Loops. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1652
14
PHP Tutorial
1250
29
C# Tutorial
1224
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: The Power of Versatile Programming Python: The Power of Versatile Programming Apr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

See all articles