Am I using boolean operations correctly? - python

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.

Related

Python How to break loop with 0

I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function

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)

Collatz Function: Strange try/except Bugs

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()

none type, don't know how to get rid of it

I'm having a problem with some coding that I'm doing for a school assignment, the same thing happened and I managed to fix it but I did so without knowing how I did it.
def number():
num = input("please enter the number of people that would like play:")
try:
if int(num) >= 2:
if int(num) <=7:
return num
else:
print("number must be 7 or less")
number()
else:
print("number must be greater than 2")
number()
except:
print("that is not a valid number. number must be between 2 and 7")
number()
number = number()
print(number,"people are playing")
This is the code which is causing the problem. If I enter an invalid number it works fine, I can just re-enter a new number, but as you can see I have wanted to print out the "number of people playing" but it returns with "none people are playing" but this is only after I have entered an invalid number. What can I do?
In the ideal case, without any errors, number() returns the entered num and all is well. However, in all other cases, you end the function with a recursive call to number() without actually returning anything. So the function implicitly returns None (i.e. nothing).
Just change every recursive call to return number() and it should work.
Btw. you should avoid recursion for this; see this answer on how to best ask the user repeatedly for valid input.
You need to use a loop rather than calling your routine again which will not have the effect you are looking for (look into recursion). Something like the following approach would be better:
def number():
while True:
num = input("please enter the number of people that would like play: ")
try:
num = int(num)
if num > 7:
print("number must be 7 or less")
elif num <= 2:
print("number must be greater than 2")
else:
return num
except:
print("that is not a valid number. number must be between 2 and 7")
number = number()
print(number, "people are playing")
The reason you are seeing None is that it is possible to reach the bottom of your function without a return being used. In this case Python defaults the returned value to None.

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