How to take a new number and run the same process python - 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)

Related

Program must ask the user for an even integer max six times, if not it ends

The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.

How can i stop a for-loop iterating when the input is not valid? (not allowed to use a while loop) - Python

for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop. Nor can i use a function :(
You can have your for loop behave like a while loop and have it run forever and implement your i as a counter. Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:
cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break
But seriously, whatever the reason for not using a while loop, you should use it anyhow..
Try something like this. You can keep track of the number of valid inputs, and only stop your loop (the while) once you hit your target number.
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
If you really cannot use a while loop...
def get_valid_input():
user_input = input(...)
valid = True
if (...): # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3):
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...
There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.
You can put the input statement inside while loop containing try block.
for j in range(3): # or any other range
try:
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
break
except:
pass

How to break out of continue statement after certain amount of tries?

Apologies if the question to this is worded a bit poorly, but I can't seem to find help on this exercise anywhere. I am writing a basic Python script which sums two numbers together, but if both numbers inputted are the same the sum will not be calculated.
while True:
print('Please enter a number ')
num1 = input()
print('Please enter a second number ')
num2 = input()
if num1 == num2:
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
If both numbers are equal I want the script to loop back once more and if the numbers inputted are equal again I want the program to end. With the code I have provided the issue I am having is that when I enter two equal numbers it keeps constantly looping until I enter two different numbers.
You would likely want to have a variable keeping track of the number of times that the numbers were matching. Then do something if that counter (keeping track of the matching) is over a certain threshold. Try something like
matches = 0
while True:
num1 = input('Please enter a number: ')
num2 = input('Please enter a second number: ')
if num1 == num2 and matches < 1:
matches += 1
print('Bingo equal numbers!')
continue
elif num1 == num2:
print('It was fun calculating for you!')
break
print('The sum of both numbers is = ' + str(int(num1) + int(num2)))
break
You can add give input code again inside first if statement or use some other dummy variable for loop so that you can break the loop, for e.g. use while j == 0 and increase it j += 1when you are inside the first if statement
continue skips the execution of everything else in the loop. I don't see it much useful in your example. If you want to print the sum then just remove it.
How continue works can be demonstrated by this sample (taken from python docs)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Result
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

Collatz Sequence - Trying to fix a printed 'None' value

Complete beginner here, I'm currently reading through "Automate the Boring Stuff With Python" by Al Sweigert. I'm running into an issue where my program is returning a None value and I can't figure out how to change that.
I understand that at some point collatz(number) doesn't have a value, therefor None is returned- but I don't understand how to fix it. The book hasn't touched on yield yet. I've tried using return instead of print within the function, but I haven't been able to fix it.
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
print(collatz(number))
except ValueError:
print ('Please enter an integer.')
As #chepner proposed you need to remove the print statement which is enclosing your collatz(number) call. The correct code would look like
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
collatz(number)
except ValueError:
print ('Please enter an integer.')

Newbie at Python (greater than but less than; return

cookiedict = {'banana':5, 'blueberries':5, 'jerky':5}
def cookies():
return input('Which of the cookies do you want to eat?')
def number():
return int(input('How many cookies do you want to eat?'))
cookies = cookies ()
number = number ()
while True:
if cookiedict[cookies] >0 <=5:
cookiedict[cookies] -= number
print ('You ate {} of the {} cookies'.format(number,cookies))
elif cookiedict[cookies] >=6:
print ('Game Over!!! You ate too much!!!')
break
else:
print ('Incorrect Input. Try again...')
This is my second day. I'm using a combo of udemy course and youtube videos. You probably know what I'm trying to accomplish by looking at the code. If you eat more than the available cookies you lose. There are only 5 for each.
if cookiedict[cookies] >0 <=5:
cookiedict[cookies] -= number
print ('You ate {} of the {} cookies'.format(number,cookies))
I have no idea why this does not work. It keeps outputting the print no matter what number I type in, even though I think I'm telling it to only print when greater than 0 and equal or less than 5.
Also, am I doing this part correct? It seems like it shouldn't work for some reason but it is accepting input.
def cookies():
return input('Which of the cookies do you want to eat?')
def number():
return int(input('How many cookies do you want to eat?'))
cookies = cookies ()
number = number ()
Thanks for any help. I've spent the last couple of hours playing with this and can not get it to work!!
x >0 <=5 is short for x > 0 and 0 <= 5. Since 0 is always less than 5, the second part is always true and you end up only comparing >0.
What you want is: 0 < x <= 5, which means 0 < x and x <= 5.
It is always printing because you are not comparing the number input but the number of available cookies. You need to compare the input number and print if the input number is <=5 and >0.
Do This:-
while True:
if 0 < number <= 5:
cookiedict[cookies] -= number
print ('You ate {} of the {} cookies'.format(number,cookies))
elif number >= 6:
print ('Game Over!!! You ate too much!!!')
break
else:
print ('Incorrect Input. Try again...')

Categories

Resources