• 1
    डेटा I/O
    • कार्य
  • 2
    शर्तें
    • कार्य
  • 3
    for लूप
    • कार्य
  • 4
    स्ट्रिंग
    • कार्य
  • 5
    while लूप
    • कार्य
  • 6
    सूचियां
    • कार्य
  • 7
    2D मैट्रिक्स
    • कार्य
  • 8
    डिक्शनरी
    • कार्य
  • 9
    सेट
    • कार्य
  • 10
    फ़ंक्शन
    • कार्य
  • к

पाठ 5. While cycle

कठिनाई:

иконка человека красный иконка человека белая иконка человека зеленая Pythonlib

कार्य«अंकगणितीय श्रेणी»

💻 Python

एक युवा माली जिसका नाम एलेक्स है, ने एक जादुई अंकुर लगाया। वह अपनी प्रारंभिक ऊंचाई, हर दिन अंकुर कितनी बार बढ़ता है, और वह इसे कितना ऊंचा उगाना चाहता है, जानता है। एलेक्स पहले से जानना चाहता है कि उसे कितने दिन इंतजार करना होगा।


एक प्रोग्राम लिखें जो:



  1. माली का नाम पूछता है।

  2. अंकुर की प्रारंभिक ऊंचाई, दैनिक वृद्धि गुणक और वांछित ऊंचाई पढ़ता है। सभी ऊंचाई पूर्णांक हैं।

  3. गणना करता है कि अंकुर की ऊंचाई वांछित ऊंचाई के बराबर या उससे अधिक होने में कितने दिन लगेंगे।

  4. माली के लिए दिनों की संख्या के साथ एक व्यक्तिगत संदेश प्रदर्शित करता है।

  5. बोनस के रूप में अंतिम फूल को "चित्रित" करता है, जिसके तने की ऊंचाई वृद्धि के दिनों की संख्या पर निर्भर करती है।


यह कार्य आपको लूप while और for, सशर्त ऑपरेटरों, साथ ही स्ट्रिंग्स सहित डेटा के इनपुट और आउटपुट का उपयोग करने का अभ्यास करने में मदद करेगा।

इनपुट फॉर्मेट

rn
  • माली का नाम (पंक्ति)। प्रारंभिक अंकुर की ऊंचाई (पूर्णांक)।
  • rn
  • दैनिक वृद्धि गुणक (पूर्णांक, 1 से अधिक)।
  • rn
  • वांछित अंतिम ऊंचाई (पूर्णांक)।
  • आउटपुट फॉर्मेट

    rn
  • विकास के लिए समय की आवश्यकता होने पर परिणाम (पंक्ति) के साथ व्यक्तिगत संदेश। फूल की शैलीबद्ध छवि (कई पंक्तियाँ)।
  • rn
  • यदि विकास की आवश्यकता नहीं थी तो वैकल्पिक संदेश (पंक्ति)।
  • rn

    उदाहरण

    इनपुट

    माशा
    2
    3
    50

    आउटपुट

    माशा, तुम्हारे अंकुर को बढ़ने में 3 दिन लगेंगे।
    & nbsp; (---)
    & nbsp; (o)
    & nbsp; & nbsp; |
    & nbsp; & nbsp; |
    & nbsp; & nbsp; |
    & nbsp; / \

    संकेत

    All about thewhile loop in Python

    The while cycle (translated as "for now") allows you to repeat the execution of a block of code as long as a certain logical condition remains true (True). This is an indispensable tool when you don't know in advance exactly how many times you need to perform an action. The main difference from the for loop is that for is usually used to iterate over a known sequence (list, string, range), and while when the number of iterations depends on the fulfillment of some condition in during the program operation.

    Loop syntax while

    Here is the basic syntax of the while loop in Python:

    while condition:
        code block_
    
    • Condition: this is any expression that returns True or False. This can be not only a comparison of variables, but also, for example, checking the presence of items in the list or the value returned by the function. If the condition is true (True), the block_code is executed.
    • Code block: one or more indented statements that are executed each time the loop passes (each iteration).

    Example of a simple loop while

    Let's look at an example where we output numbers from 1 to 5:

    count = 1
    while count <= 5:
        print(count)
    count += 1 # The most important line: increase the value of the count variable by 1
    

    Output:

    1
    2
    3
    4
    5
    

    Here we start with the value count = 1. Before each iteration, Python checks the condition count<=5. As long as it is true, a block of code is executed: the current value of count is printed, and then it increases by 1. As soon as count becomes 6, the condition 6 <= 5 becomes false (False), and the loop ends its work.

    A useful tip: the variable that controls the loop (in our case count) is often called a counter or a loop control variable. It is extremely important to ensure that it changes within the loop in such a way that the condition sooner or later becomes false.

    Potential problems: endless loops

    An infinite loop is a cycle that never ends. This happens when his condition always remains true.

    count = 1
    while count <= 5:
        print(count)
        # Error: we forgot to change the count value, so the condition will always be True.
    

    To stop the execution of such a cycle, you need to interrupt the program manually (for example, by pressing Ctrl+C in the terminal).

    However, it is worth noting that infinite loops are not always a mistake. Sometimes they are used intentionally, for example, in programs that need to run all the time: servers listening to connections, or game loops. In such cases, the while True construction is often used.:, and the exit from the loop is organized using a break for some special event.

    Using break to exit the loop early

    We can use the break operator to immediately and completely terminate the loop, even if its main condition is still true.

    count = 1
    while count <= 10: # The condition allows you to go up to 10
        if count == 3:
            print("We have met the number 3, we exit the loop.")
    break  # Exit the loop when count is 3
        print(count)
        count += 1
    

    Output:

    1
    2
    We have met the number 3, we exit the cycle.
    

    A useful tip: if you have nested loops (one while inside the other), the break statement will interrupt execution of only the innermost loop in which it is located.

    Using continue to skip an iteration

    The continue operator skips the rest of the code in the current iteration and immediately proceeds to check the condition for the next iteration.

    count = 0
    while count < 5:
        count += 1
        if count == 3:
            print("Skipping the number 3...")
    continue # Skip the remaining code and move on to the next iteration
    print(f"Processing the number: {count}")
    

    Output:

    Processing the number: 1
    Processing the number: 2
    Skip the number 3...
    Process the number: 4
    Processing the number: 5
    

    It is important not to confuse continue with break. break stops the loop completely, and continue only completes the current step ahead of schedule.

    Loop while with user input

    while loops are ideal for processing user input when data needs to be requested until it meets the required criteria.

    import random
    
    secret_number = random.randint(1, 10)
    guess = None # Initialize the variable before the loop
    
    # The loop will run until guess is equal to secret_number
    while guess != secret_number:
        guess_text = input("Guess a number from 1 to 10:")
    # Check if the user has entered a number
        if not guess_text.isdigit():
            print("Please enter a number.")
            continue # Skip the rest of the logic and request input again.
        
        guess = int(guess_text)
    
        if guess < secret_number:
    print("Your number is less than the number you have guessed.")
    elif guess> secret_number:
    print("Your number is more than the number you have guessed.")
    
    print(f"Congratulations! You guessed the number {secret_number}!")
    

    Loop while with block else

    Loops in Python have an interesting and not the most well-known feature - the else block. The code in the else block is executed only if the loop ended naturally (that is, its condition became False), and was not interrupted by the break operator.

    # Example where else will execute
    count = 1
    while count <= 3:
        print(f"Iteration {count}")
    count += 1
    else:
    print("The loop ended naturally.")
    
    # Output:
    # Iteration 1
    # Iteration 2
    # Iteration 3
    # The cycle ended naturally.
    
    # Example where else fails due to break
    count = 1
    while count <= 3:
        if count == 2:
    print("The loop is interrupted by the break statement.")
    break
        print(f"Iterate {count}")
    count += 1
    else:
    print("This block will not be executed.")
        
    # Output:
    # Iteration 1
    # The loop is interrupted by the break statement.
    

    Conclusion

    The while loop is a powerful tool in Python. Here are the main points to remember:

    1. Initializing variables: Make sure that the variables used in the condition exist before the loop starts.
    2. Condition change: Something must happen inside the loop that will eventually make the condition false in order to avoid an infinite loop.
    3. break and continue: Use break to exit the loop completely and continue to skip the current iteration.
    4. The while True pattern: This is a convenient way to organize a cycle that must be interrupted by a complex internal condition using break.
    5. The else block: Keep in mind that you can use the else block for code that should be executed only at the normal end of the loop.
    main.py
    परीक्षण 1
    परीक्षण 2
    परीक्षण 3
    परीक्षण 4
    परीक्षण 5
    परीक्षण 6
    परीक्षण 7
    परीक्षण 8
    परीक्षण 9
    परीक्षण 10
    डेवलपर का समाधान
    # Формат кода с комментариями к строкам для объяснения
    
    # Ввод данных
    gardener_name = input()  # Считываем имя садовода (строка)
    current_height = int(input())  # Считываем начальную высоту (целое число)
    multiplier = int(input())  # Считываем множитель роста (целое число)
    target_height = int(input())  # Считываем желаемую высоту (целое число)
    
    days = 0  # Инициализируем счетчик дней
    
    # Основной цикл для расчета дней
    # Цикл while работает, пока текущая высота меньше желаемой
    while current_height < target_height:
        current_height *= multiplier  # Увеличиваем высоту ростка в multiplier раз
        days += 1  # Увеличиваем счетчик дней на один
    
    # Вывод результата
    # Используем f-строку для форматирования и вывода персонального сообщения
    print(f"{gardener_name}, вашему ростку потребуется {days} дней, чтобы вырасти.")
    
    # Условие для красивого вывода
    # Если росток уже большой, рисуем цветок без стебля
    if days > 0:
        print("  (---)") # Верхушка цветка
        print(" ( O )")
        # Цикл for для отрисовки стебля
        # Он выполнится 'days' раз, рисуя по одной секции стебля
        for _ in range(days):
            print("   |")
        print("  / \\") # Основание
    else: # Если ждать не нужно
        print("Ваш росток уже достиг нужной высоты!")

    🎉 बधाई! 🎉

    आपने कार्य को शानदार ढंग से हल किया! यह कठिन था, लेकिन आपने सही उत्तर खोजा। आप प्रोग्रामिंग में महारत के करीब हैं! ऐसे ही जारी रखें।

    AD

    विज्ञापन

    red-snake blue-snake green-snake

    कोड चल रहा है...

    AI सहायक

    नमस्ते! मैं आपका प्रोग्रामिंग सहायक हूँ। Python के बारे में कोई भी सवाल पूछें — मैं functions, methods समझा सकता हूँ और मौजूदा task में मदद कर सकता हूँ!