Collatz Function: Strange try/except Bugs - python

So I'm getting into coding and I was doing an exercise from the Automate the Boring Stuff book. I figured out how to write the original function, but then I wanted to try to add a little more to it and see if I could fit it all in one function.
So in Python 3.6.2, this code works fine if I enter strings, positive integers, nothing, or entering "quit". However, if I enter 1 at any point between the others then try "quitting", it doesn't quit until I enter "quit" as many times as I previously entered 1. (like I have to cancel them out).
If I enter 0 or any int < 0, I get a different problem where if I then try to "quit" it prints 0, then "Enter a POSITIVE integer!".
Can't post pics since I just joined, but heres a link: https://imgur.com/a/n4nI7
I couldn't find anything about this specific issue on similar posts and I'm not too worried about this working the way it is, but I'm really curious about what exactly the computer is doing.
Can someone explain this to me?
def collatz():
number = input('Enter a positive integer: ')
try:
while number != 1:
number = int(number) #If value is not int in next lines, execpt.
if number <= 0:
print('I said to enter a POSITIVE integer!')
collatz()
if number == 1:
print('How about another number?')
collatz()
elif number % 2 == 0: #Checks if even number
number = number // 2
print(number)
else: #For odd numbers
number = number * 3 + 1
print(number)
print('Cool, huh? Try another, or type "quit" to exit.')
collatz()
except:
if str(number) == 'quit':
quit
else:
print('Enter an INTEGER!')
collatz()
collatz()

Related

Am I using boolean operations correctly?

For an assignment for class, I am needing to create a program that returns if a number is even or odd, while having the main function get user input and displays the output, while another function checks whether the number is even or odd. My python knowledge so far is very basic.
Here is what I've got so far.
def check(number):
if (number % 2) == 0:
return True
else:
return False
def main():
number = int(input("Enter an integer: "))
if check is True:
print("This is an even number.")
elif check is False:
print("This is an odd number.")
__name__ == "__main__"
main()
When I run the code, I get the input prompt, but nothing in return after.
check is a function, so it should be like
if check(number):
print("This is an even number.")
else:
print("This is an odd number.")
Python is very flexible, you don't even need a function.
I would take advantage of f-strings and a ternary:
number = int(input("Enter an integer: "))
print(f'This is an {"odd" if (number % 2) else "even"} number')
Example:
Enter an integer: 2
This is an even number
Enter an integer: 3
This is an odd number
As you are basic this is not the best function for check using bool.
def check(num):
return num % 2 == 0 # return True if even otherwise odd
This code is simple and easily to read rapidly.

Passing variables defined inside of one function into another

Context:
I'm sure this has been asked elsewhere, but the topics I'm finding thus far are more advanced than what I'm doing and only confusing me further. I am a student in an intro to Python course, and am working on a "Lottery Number" assignment. Basically, randomly generate a 7-digit lottery number and print it back out.
That much I get, but I am trying to approach this from a less literal perspective and a more practical one. As in, I want the user to define how many numbers they need and which numbers to choose from. From there, I want the program to generate random numbers that fit the criteria they set.
My instructor wants everything done inside of functions, so I am trying to attempt the following:
What I'm doing:
main() Function - everything inside of here.
get_info() to collect the data from the user, number of digits (MaxDigits), range minimum (MinChoice), range maximum (MaxChoice).
lottery_pick() take the variables and do the lottery thing with them.
I have it "working", but I can only do so if I have lottery_pick() function run inside of the get_info() function. I imagine there has to be a way to define these variables independently, and just pass the variables from get_info() to lottery_pick().
import random
# Define the main function
def main():
get_info()
exit_prompt()
def get_info():
# Set Variables to 0
MaxDigits = 0
# Let the user know what we are doing
print("Let's choose your lottery numbers!")
print("First, How many numbers do you need for this lottery?")
# Request the user input the number of lottery numbers we need
while True:
try:
MaxDigits = int(input('Please enter how many numbers you need to choose: '))
if MaxDigits > 0:
break;
else:
print('Please enter an integer for how many numbers are being drawn. ')
except:
continue
print('Next, we need to know the smallest and largest numbers allowed to choose from')
# Request user input smallest number in range of numbers to pick from.
while True:
try:
MinChoice = int(input('Please enter the lowest number you are allowed to choose from: '))
if MinChoice >= 0:
break;
else: print ('Please enter an integer, 0 or greater for the smallest number to pick from.')
except:
continue
# Request user input largest number in range of numbers to pick from.
while True:
try:
MaxChoice = int(input('Please enter the largest number you are allowed to choose from: '))
if MaxChoice >= 0:
break;
else: print ('Please enter an integer, 0 or greater for the greatest number to pick from.')
except:
continue
# Define the function to actually assemble the lottery number
def lottery_pick(lot_digits, lot_min, lot_max):
numbers = [0] * lot_digits
for index in range(lot_digits):
numbers[index] = random.randint (lot_min, lot_max)
print('Here are your lottery numbers!:')
print(numbers)
# Execute the function - I've not yet figured out how to pass the variables from the get_info
# function to the lottery_pick function without lottery_pick being inside of get_info.
lottery_pick(MaxDigits, MinChoice, MaxChoice)
def exit_prompt():
while True:
try:
# use lower method to convert all strings input to lower-case. This method
# allows user to input their answer in any case or combination of cases.
ExitPrompt = str.lower(input('Would you like to generate another lottery number? Please enter "yes" or "no" '))
if ExitPrompt == 'yes':
main()
elif ExitPrompt =='no':
print('Goodbye!')
exit()
# If an answer other than yes or no is input, prompt the user again to choose to re-run or to exit
# until an acceptable answer is provided.
else:
print('Please enter "yes" to generate another lottery number, or "no" to exit. ')
except:
continue
main()

Can't convert a variable to an integer (because of an if statement?)

Sorry for asking, but I'm writing a program for a past paper question to find if a user entered number is prime, then looping it.
The issue is that I can't seem to convert the input userno from a float to an int in the if statement.
Any help would be much appreciated
run = True
while run == True:
userno = float(input("Please enter a number to check if it's a prime number."))
if userno < 1:
print ("The number entered was lower than 1, so can't be prime.")
else:
int(userno) #this doesn't seem to work
for norange in range (2,userno): #userno is still a float here
if userno % norange == 0:
print ("This is not a prime number, sorry.")
else:
print ("This is a prime number. :)")
runagain = input ("Do you want to enter another number? Please enter 'yes' or 'no'.")
if runagain == "no":
run = False
int(userno) returns userno as an integer but it does not overwrite the userno actual variable's value.
You need to use userno = int(userno)

How to check user input for multiple conditions within same loop or function in Python 3?

I'm trying to take user-input but I need the input to be an integer, AND be between 1 and 9. I tried putting "in range(1,10)" in a few places in the code but it didn't work. I need the program to keep asking the user for the right input until they give the correct input. So far I've only been able to make sure their input is an integer with he following code. I will be taking input by using int(input("...")), rather than using input("...").
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
break
except ValueError:
print("You have to choose a number between 1 and 9")
continue
Add a check before the break and move the error message to the end of the loop.
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
if 1 <= ui1 <= 9:
break
except ValueError:
pass
print("You have to choose a number between 1 and 9")
Why not just check isdigit() and in range ?
while True:
ui1 = input("Player 1, Your move. Select your move. ")
if ui1.isdigit() and int(ui1) in range(1,10):
break
print("You have to choose a number between 1 and 9")
# Continue code out of the loop
# beJeb
# Stack overflow -
# https://stackoverflow.com/questions/51202856/how-to-check-user-input-for-multiple-conditions-within-same-loop-or-function-in
# Our main function, only used to grab input and call our other function(s).
def main():
while True:
try:
userVar = int(input("Player 1, Your move. Select your move: "))
break
except ValueError:
print("Incorrect input type, please enter an integer: ")
# We can assume that our input is an int if we get here, so check for range
checkRange = isGoodRange(userVar)
# Checking to make sure our input is in range and reprompt, or print.
if(checkRange != False):
print("Player 1 chooses to make the move: %d" %(userVar))
else:
print("Your input is not in the range of 1-9, please enter a correct var.")
main()
# This function will check if our number is within our range.
def isGoodRange(whatNum):
if(whatNum < 10) & (whatNum > 0):
return True
else: return False
# Protecting the main function
if __name__ == "__main__":
main()
Note: I tested a couple inputs so I believe this should be enough to help you understand the process, if not please comment, message, etc. Also, if this answer helps you, please select it as answered to help others.
Let the number be the input you are taking from the user.
while(1): #To ensure that input is continuous
number = int(input())
if number>=1 and number<=10 and number.isdigit():
break #if the input is valid, you can proceed with the number
else:
print("Enter a valid Number")
The number can be used for further operations.

Boolean return value?

def main():
num = int(input('Please enter an odd number: '))
if False:
print('That was not a odd number, please try again.')
else:
print('Congrats, you know your numbers!')
def number():
if (num / 2) == 0:
return True,num
else:
return False,num
main()
I am trying to make it so that if the number entered is odd, it congratulates the user. If not then it should tell them to try again. I am trying to return the Boolean value to main and then when I try to use the code in the main function to prompt the user, it doesn't work.
Your functions are very odd and I'm not talking about numbers that aren't divisible by 2. Try this:
num = int(input('Please enter an odd number: '))
if num % 2 == 0:
print('Better luck next time??') # no really, you should go back to school (;
else:
print('Genius!!!')
Try this:
num_entry = int(input('Please enter an odd number: '))
def number():
return num_entry % 2 == 0
def main():
if number() == True:
print('Sorry, please try again.')
else:
print('Nice! You know your numbers!')
number()
main()
This should work!
Your code does look odd like Malik Brahimi mentioned. This may be because you are trying to write your python code like Java, which requires a main method. There is no such requirement in python.
If you would like to have your check for the "odd-ness" of the number wrapped in a defined function that you can call elsewhere, you should try writing it like this.
def odd_check(number):
if number % 2 == 0:
#This is the check the check formula, which calculates the remainder of dividing number by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
num = int(input('Please enter an odd number: ')) #where variable is stored.
odd_check(num) #This is where you are calling the previously defined function. You are feeding it the variable that you stored.
If you would like a piece of code that will continue to ask your user to enter a number until they get it right, try something like this:
while True: #This ensures that the code runs until the user picks an odd number
number = int(input('Please enter an odd number: ')) #where variable is stored.
if number % 2 == 0: #the check formula, which calculates the remainder of dividing num by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
break #This stops the "while" loop when the "else" condition is met.

Categories

Resources