Home > Enterprise >  Struggling with simple loops
Struggling with simple loops

Time:11-16

//I started learning python 2 weeks ago and right now stack with this problem for a few days. I need somobody to give me a hint or something close to solution. Thank you.Here is my code.

from math import sqrt

# Write your solution here
number = int(input("Please type in a number:"))
while True:
    if number > 0:
        print(sqrt(number))
    break
    if number == 0:
        print("Invalid number")
    break
    if number < 0:
        print("Exiting...")
    break
//Expected output example

Please type in a number: 16
4.0
Please type in a number: 4
2.0
Please type in a number: -3
Invalid number
Please type in a number: 1
1.0
Please type in a number: 0
Exiting..

CodePudding user response:

the first break statement always breaks out of the loop, so you never reach the second (and third if). you may want to indent it to be part of the if statements' bodies:

from math import sqrt

# Write your solution here
number = int(input("Please type in a number:"))
while True:
    if number > 0:
        print(sqrt(number))
        break
    if number == 0:
        print("Invalid number")
        break
    if number < 0:
        print("Exiting...")
        break

Also, if you want to continue the loop until 0 is read, you may want to remove the first two break statements and move the input reading into the function:

from math import sqrt

# Write your solution here
while True:
    number = int(input("Please type in a number:"))
    if number > 0:
        print(sqrt(number))
    if number == 0:
        print("Invalid number")
    if number < 0:
        print("Exiting...")
        break

The conditions of the if's are mutually exclusive, so only one statement can be entered at a time. In more complex scenarios, if you only want to enter one if statement, you may want to use elif or continue:

from math import sqrt

# Write your solution here
while True:
    number = int(input("Please type in a number:"))
    if number > 0:
        print(sqrt(number))
        continue # continue with next loop iteration, skip anything below
    elif number == 0: # only check condition, if first loop condition was false
        print("Invalid number")
    elif number < 0:
        print("Exiting...")
        break

EDIT: John Gordon rightfully pointed out, that your cases for exit and invalid number are swapped. To make sure this is a complete solution, I will also incorporate this change:

from math import sqrt

# Write your solution here
while True:
    number = int(input("Please type in a number:"))
    if number > 0:
        print(sqrt(number))
    elif number < 0:
        print("Invalid number")
    elif number == 0:
        print("Exiting...")
        break
  • Related