Function with loop: Shampoo Exercise Prints "Done" in Error - python

I have this exercise with the details:
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.
Hint: Define and use a loop variable.
This is my code for the program:
def print_shampoo_instructions(num_cycles):
if num_cycles < 1:
print('Too few.')
if num_cycles > 4:
print('Too many.')
else:
cycles = 1
while cycles <= num_cycles:
print(f'{cycles}: Lather and rinse.')
cycles += 1
print('Done.')
user_cycles = int(input())
print_shampoo_instructions(user_cycles)
My results have some tests passing but not all. The test with the input -1 failed when the print_shampoo_instructions function was called. For some reason it prints 'Done' after 'Too few.', even though I do not have a print statement 'Done' in the if statement for num_cycles < 1 and don't know why. Any help on getting the right output would be appreciated :).
Output:
Testing with input: 4 (Correct)
1: Lather and rinse.
2: Lather and rinse.
3: Lather and rinse.
4: Lather and rinse.
Done.
Testing with input: 6 (Correct)
Too many.
Testing with input: -1 (Incorrect)
Too few.
Done.
Expected output:
Too few.

Related

While can't work in a form that PyCharm tell's my to simplify

I had this question many days before and today I have the courage to ask in this page my problem.
I did a weird while statement and it doesn't work... I have been working on it several days but I can't understand it.
That is the code, I'm asking to the user a number between 1 and 5.
num = int(input("Num? (1-5) : "))
while 1 > num > 5:
num = int(input("Num? (1-5) : "))
print(f"El numero introduit: {num}")
In theory, if num is bigger than 5 or smaller than 1 the while statement starts but I have this result...
Num? (1-5) : 7
El numero introduit: 7
But if I use this...
num = int(input("Num? (1-5) : "))
while num < 1 or num > 5:
num = int(input("Num? (1-5) : "))
print(f"El numero introduit: {num}")
I have what I want...
Num? (1-5) : 7
Num? (1-5) :
When I put the second code in PyCharm, it tells me that I can simplify it in the form of the first code but it doesn't work but why?
It's because the first code acts like an "and" and the second code have the "or"?
Chained conditions combine the conditions using and, so
while 1 > num > 5:
is equivalent to
while 1 > num and num > 5:
which can never be true.
You can simplify the code by using the condition to break out of the loop.
while True:
num = int(input("Num? (1-5) : "))
if 1 <= num <= 5:
break
1 is not bigger than 7:
while 1 > num < 5:

How to have 3 random objects spawn on 3 places

The goal is having random objects spawn on 3 positions once .
the code works and looks like this but with more if statements and 3 small stataments:
if mainloop != 3:
if smallloop1 != 1:
if randomnumber == x:
object.goto(x, y)
mainloop += 1
smallloop += 1
the problem is that the if statement doesnt stop so multiple objects spawn
im also not getting any error messages
I tried changing the if statements to while loops which didnt change anything except having to stop them with the break command or using a list instead of a random number which made the thing more complicated and again didnt change anything
Thanks in advance
Edit: small reproducible example:
if bigloop < 1:
if mediumloop1 < 1:
if random1 == 1 or 2 or 3:
print("first loop")
bigloop += 1
mediumloop1 += 1
if random1 == 4 or 5 or 6:
print("first loop")
bigloop += 1
mediumloop1 += 1
The problem is that it prints "first loop" twice.

How to take a new number and run the same process python

I'm trying to make a script that calculates the famous "3x+1" equation and I want python to take a number in by the user then determine if its even or odd. If even divide by half if odd do 3x+1 and then take the new number that went through the process and do it again until the number becomes 4.
I have all the parts done and properly working except for the part that takes the new number and repeats the process. Does anyone know how i can get this to take the new number created and repeat the process.
(for those wondering why i made the number of times it does the process meow i couldn't think of a name and my cat was next to me meowing for food so i went with it)
Code:
meow = 0
num = int(input("Enter a number"))
meow += 1
while True:
if num == 4:
print("you are now caught in a loop. (4 becomes 2 which becomes 1 which becomes 4 ect)")
print("it took this number",meow-1,"times to get caught in this uninevitable loop for all recorded numbers")
else:
if(num % 2 != 0):
print(num*3+1)
else:
print(num/2)
Just update num every iteration:
meow = 0
num = int(input("Enter a number"))
meow += 1
while True:
if num == 4:
print("you are now caught in a loop. (4 becomes 2 which becomes 1 which becomes 4 ect)")
print("it took this number",meow-1,"times to get caught in this uninevitable loop for all recorded numbers")
else:
if(num % 2 != 0):
num = num*3+1
print(num)
else:
num = num/2
print(num)

Python if statement using Modulo

I made a list called 'l' then I created a for loop with an if statement inside. The if statement is suppose to check if num is even (equal to 0) if it is then it will print the num if not it will print "Odd number".
Why does the first one print incorrectly ( 2 4 Odd number! )
and the second one prints correctly ( Odd number 2 Odd number 4 Odd number )
I already tried changing the spacing on the first one but I kept getting statement exceptions.
l = [1, 2, 3, 4, 5]
# First
for num in l:
if num % 2 == 0:
print num
else:
print 'Odd number!'
print
print
#Second
for num in l:
if num % 2 == 0:
print num
else:
print 'Odd number!'
Output:
First
2
4
Odd number!
Second
Odd number!
2
Odd number!
4
Odd number!
Indentation. Python uses indentation to figure out scopes in your code, so for your first for loop, it doesn't do anything. Reformat it like this:
for num in l:
if num % 2 == 0:
print num
else:
print 'Odd number!'
The second piece of code was properly indented, that's why it worked.
Python cares about how much whitespace is at the start of a line. This line:
if num % 2 == 0:
is not being considered as part of the for loop.

Guess the Number Game with Different Guess Names

This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!

Categories

Resources