Question:
Write a function print_shampoo_instructions() with parameter
num_cycles. If num_cycles is less than 1, print "Too few.". If more
than 4, print "Too many.". Else, print "N : Lather and rinse."
num_cycles times, where N is the cycle number, followed by "Done.".
Sample output with input: 2
1 : Lather and rinse.
2 : Lather and rinse.
Done.
My Error:
Program end never reached.
This is commonly due to an infinite loop or infinite recursion.
My code is as follows:
def shampoo_instructions(num_cycles):
if num_cycles < 1:
print ('Too few.')
elif num_cycles > 4:
print ('Too many.')
else:
i = 0
while i<num_cycles:
print (i+1,": Lather and rinse")
i = i + 1
print('Done')
shampoo_instructions(2)
user_cycles = int(input()) #cannot be altered per the program
print_shampoo_instructions(user_cycles) #cannot be altered per the program
Your actually reassigning i outside of the while loop. Inside the loop you're simply printing out i + 1. Instead reassign the counter inside the loop:
while i<num_cycles:
print (i+1,": Lather and rinse")
i = i + 1
def shampoo_instructions(user_cycles):
if user_cycles < 1:
print("Too few.")
elif user_cycles > 4:
print("Too many.")
else:
for i in range(1, user_cycles + 1):
print(i,":","Lather and rinse.")
print("Done.")
user_cycles = int(input())
shampoo_instructions(user_cycles)
Related
I tried to use continue in a while loop to skip print number but it doesn't work.
num = int(input())
while int(num) > 0 :
num-=1
print(num)
if num == 6:
continue
elif num ==1:
print("8 Numbers Printed Successfully.")
break
#i want to remove number six
Try this
num = int(input())
while num > 0 :
num -= 1
if num == 6:
continue
elif num == 1:
print("8 Numbers Printed Successfully.")
break
print(num)
Your print line should be after the if-else block
num = int(input())
while int(num) > 0:
num -= 1
# print(num) => if you print here, it does not check the condition
if num == 6:
continue
elif num == 1:
print("8 Numbers Printed Successfully.")
break
# print number here
print(num)
First of all, how do you know it's been 8 numbers? The input can be any number. Secondly, if you want to print every number but 6 you need to move the num -= 1 too. Being there, it won't print the first number.
Try this if you don't insist on using continue:
num = int(input())
printed_numbers = 0
while int(num) > 0 :
if num != 6:
print(num)
printed_numbers += 1
num -= 1
print("{} Numbers Printed Successfully.".format(printed_numbers))
Or this, if you want to test continue:
num = int(input())
printed_numbers = 0
while int(num) > 0 :
if num == 6:
num -= 1
continue
print(num)
printed_numbers += 1
num -= 1
print("{} Numbers Printed Successfully.".format(printed_numbers))
Finally, If you're ok with the num -= 1 there:
num = int(input())
printed_numbers = 0
while int(num) > 0 :
num -= 1
if num == 6:
continue
print(num)
printed_numbers += 1
print("{} Numbers Printed Successfully.".format(printed_numbers))
NOTE: I'm using printed_numbers because if the input is less than 6 you will print all the numbers else you'll have one less. You can use this condition instead.
You are print the number before the condition. chnage the code as follows.
num = int(input())
while int(num) > 0 :
num-=1
if num != 6:
print(num)
elif num == 1:
print("8 Numbers Printed Successfully.")
break
#i want to remove number six
Can someone help me figure out why this loop is infinite? The class I am in automatically inputs the variables for me per those last 2 lines. It passes the test with numbers 2 and 4. However there is another input, that I am unable to see, that keeps this running as an infinite loop. I can not figure out where there is a gap in this code that would allow an infinite loop. Any suggestions?
def shampoo_instructions(user_cycles):
N = 1
while N <= user_cycles:
if N < 1:
print('Too few')
elif N > 4:
print('Too many')
else:
print(N,': Lather and rinse.')
N = N + 1
print('Done.')
user_cycles = int(input())
shampoo_instructions(user_cycles)
Indent N = N + 1 out of the loop, otherwise it never get's to adding.
Or better use N += 1:
def shampoo_instructions(user_cycles):
N = 1
while N <= user_cycles:
if N < 1:
print('Too few')
elif N > 4:
print('Too many')
else:
print(N,': Lather and rinse.')
N = N + 1
print('Done.')
user_cycles = int(input())
shampoo_instructions(user_cycles)
First: get used to testing your code. Since you have conditionals involving the numbers 1 and 4, you should test numbers that are less than 1 and greater than 4 to see what happens beyond those edges. Sure enough, giving 5 as an input produces an infinite loop:
0
Done.
1
1 : Lather and rinse.
Done.
4
1 : Lather and rinse.
2 : Lather and rinse.
3 : Lather and rinse.
4 : Lather and rinse.
Done.
5
1 : Lather and rinse.
2 : Lather and rinse.
3 : Lather and rinse.
4 : Lather and rinse.
Too many
Too many
Too many
Too many
Too many
Too many
Why does that happen? user_cycles == 5 so the loop won't stop until N == 6 (or any value greater than 5.
What happens when N == 5? We print "Too many" and then continue the loop without incrementing N again. Hence the loop will always get stuck at N = 5.
Note that testing with these values also shows is that we never hit the Too few condition -- this is dead code! It's not possible to ever reach this condition because N always starts at 1 and is never decreased.
The way to fix the infinite loop depends on the desired behavior. You could break the loop as soon as N exceeds 4:
elif N > 4:
print('Too many')
break
Another option would be to make sure that N is always incremented, either by incrementing it inside that conditional block or incrementing it outside the entire if...elif...else statement rather than inside the else (which will only run for values between 1 and 4).
Im trying to write a function that outputs all the prime numbers between a certain range that ends with 7. However when I run the program it gives me numerous outputs of the same number. I think it has something to do with the loop but I dont know what to fix.
lower=int(input('enter lower bound: '))
upper=int(input('enter upper bound: '))
for i in range(lower, upper + 1):
if i > 1:
for x in range(2, i):
if (i % x) == 0:
break
elif i%10==7:
print(i)
For now the elif is related to this if, so when you're testing 17 for all number that are not a divisor of 17 you're going into the elif and print it
if (i % x) == 0:
break
elif i%10==7:
print(i)
Fix with a for-else
Use the for-else, if the loop encounter no break it goes into the else (if there is one), here you can add your condition
for i in range(lower, upper + 1):
if i > 1:
for x in range(2, i):
if (i % x) == 0:
break
else:
if i % 10 == 7:
print(i)
Improve
Then you can imagine, to check prime only for ..7 numbers, this will avoid a huge amount of computing. Also to remove the if i>1 which is quickly useless, use max on the lower bound, if you set like a negative value, it'll start at 2, no empty run, and end the testing loop at sqrt(i) because you won't find a divisor after its square root
from math import sqrt
for i in range(max(lower, 2), upper + 1):
if i % 10 == 7:
for x in range(2, int(sqrt(i))):
if (i % x) == 0:
break
else:
print(i)
for i in range(min(lower,2), upper + 1):
if i % 10 == 7:
for x in range(2, i):
if (i % x) == 0:
break
else:
print(i)
I want to check the value range of an input number, then print the correct "size" (small, medium or large). If the value is out of my acceptable range, then I want the else statement to print out that the number is not valid.
Minimal example for my problem:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
if 5 <= n < 10:
a = "medium"
if 10 <= n <= 20:
a = "large"
print("this number is",a)
else:
print("thats not a number from 0 to 20")
According to Google, this is a problem with indentation. I've tried multiple ways of indenting this; I can fix the syntax, but I can't get the logic correct.
Let's fix your immediate issue: you have an else with no corresponding if statement. Syntactically, this is because you have an intervening "out-dented" statement, the print, which terminates your series of ifs.
Logically, this is because you have two levels of decision: "Is this a number 0-20?", and "Within that range, how big is it?" The problem stems from writing only one level of ifs to make this decision. To keep close to your intended logic flow, write a general if on the outside, and encapsulate your small/medium/large decision and print within that branch; in the other branch, insert your "none of the above" statement:
n = int(input("number= "))
if 0 <= n <= 20:
if n < 5:
a = "small"
elif n < 10:
a = "medium"
else:
a = "large"
print("this number is", a)
else:
print("that's not a number from 0 to 20")
You should try something like
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
elif 5 <= n < 10:
a = "medium"
elif 10 <= n <= 20:
a = "large"
else:
a = "not a number from 0 to 20"
print("this number is",a)
The print statement before the else statement needs to either be removed or indented to match:
a= "large"
You've syntax (indentation) error:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
if 5 <= n < 10:
a = "medium"
if 10 <= n <= 20:
a = "large"
#print("this number is",a) indentation error in this line
else:
print("thats not a number from 0 to 20")
You can use also use following code
n = int(input("number= "))
if 10 <= n <= 20:
a = "large"
print("this number is",a)
elif 5 <= n < 10:
a = "medium"
print("this number is",a)
elif 0 <= n < 5:
a = "small"
print("this number is",a)
else:
print("thats not a number from 0 to 20")
The problem is with the print statement.
It is indented on the same level as the if block and thus, the if block ends on line containing the print statement.
Thus, the else on the next line is incorrect.
To achieve what you are trying, you should do something like this:
n = int(input("number= "))
if 0 <= n < 5:
a = "small"
elif 5 <= n < 10:
a = "medium"
elif 10 <= n <= 20:
a = "large"
else:
print("not between 0 and 20")
print("The number is", a)
The print statement needs to be placed after the else block. Also, its best to use elif statements than if statements in a situation like this.
n = int(input("Enter a number between 0 and 20: "))
if 0 <= n <= 5:
a = "small."
elif n <= 10:
a = "medium."
elif n <= 20:
a = "large."
else:
a = "invalid / out of range."
print("This number is ", a)
So my program checks for the number of palindrome numbers, lychrels, and non-lychrels. Originally I used a 'break' and a for loop, but I was supposed to use a while loop.
My while loop does not work the same as my for loop and I dont know what i did wrong?
-- The range is meant to be between num1 and num2
also, the output is meant to be an exact copy of the prompt, so thats why it looks like this.
Thanks!
Your while loop:
while (nums>=num1 and nums<=num2 and flag):
#for nums in range(num1, num2+1):
num_str = str(nums)
if num_str == num_str[::-1]:
pal += 1
else:
count = 0
num_el = num_str
while (count < 60):
np_total = int(num_el) + int(num_el [::-1])
count += 1
nums_el = str(np_total)
num_el = nums_el
if num_el == nums_el [::-1]:
nonlych += 1
flag = False
else:
lychrel += 1
print(nums, "looks like a lychrel number")
nums += 1
The
else:
lychrel += 1
print(nums, "looks like a lychrel number")
is executing every time the while loops exits. The break in your for loop was skipping it.
Second problem is that when flag is set to False, it will stop your outer while loop, so the first non-lychrel number you find will be the last number you test.
Here's my attempt at changing as little as possible. You can add a flag like isLychrel instead of using the count variable to pass information.
nums = num1
while (nums>=num1 and nums<=num2):
num_str = str(nums)
if num_str == num_str[::-1]:
pal += 1
else:
count = 0
num_el = num_str
while (count < 60):
np_total = int(num_el) + int(num_el [::-1])
count += 1
nums_el = str(np_total)
num_el = nums_el
if num_el == nums_el [::-1]:
nonlych += 1
count = 999 # breaks while loop
if (count != 999):
lychrel += 1
print(nums, "looks like a lychrel number")
nums += 1