python user input for finding leap year not printing - python

I am trying to create a function that accepts a users input and tries to figure out whether the year is a leap year and later also accept the users day of year (i.e. 355) and turns it into which day of the year it is (and output December, 10 2018). But for now I am not sure why it will not output whether the year is True or False. I tried to use the int parameter to change the user input from a string to a number but I am not sure if that is where I went wrong.
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")

You're only defining the function leap_year but you're never calling it, below is an example where it actually gets called:
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
leap_year(val)
Also your indentation is a bit off, which causes it to not compile in the first place, but that could also be an error while copying to Stackoverflow.

Related

A TypeError prevents me from forming the conditionals of my function (Python)

The function is supposed to receive a number representing a year, and then print if it's a leap year or not.
def isItALeapYear(year):
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
The program works, the only thing I can't get right is that it is supposed to notify you if anything that it's not a number is being used as an argument. I've tried both the isinstance() function, as well as writing what I want as year != int. And then year == None in the hopes of making it work in case anything nondefined is used as an argument.
I read this post with the exact same error: TypeError: not all arguments converted during string formatting python
But I'm not intending to format anything with the % symbol
As far as I'm concerned the % can be used as an operand to get the residue of a division.
So in this case I'm using it to figure out if a year is a leap year or not by asking if the residue is 0 when divided by 4. I'm pretty stuck, and the sad thing is the error comes up in the very first "if", so I can't really know if the last lines for excluding any non int type argument work or not. Any help would be really appreciated!
You could use the isleap() function from the standard library (module calendar):
from calendar import isleap
def isItALeapYear(year):
if not isinstance(year, int):
print("Please provide a number")
elif isleap(year):
print("That is a leap year!")
else:
print("That is not a leap year...")
I recommend to divide the functionality of checking the number from returning the output as well as from receiving the input.
def is_multiple_of_four(number: int):
if number % 4 == 0:
return True
else:
return False
if __name__ == '__main__':
user_input = ""
while not user_input.isdigit():
user_input = input("Please type in a year: ")
if is_multiple_of_four(int(user_input)):
print("That is a leap year!")
else:
print("That is not a leap year.")
Here you can see the function that checks the number does only that, it checks the number if it's modulo of 4 equals 0.
In the script outside the function you can retrieve the user input for as long as it takes to get a valid numeric and return the output in respect of the functions results.
Edit (adding clarification asked in the comments)
The first condition if __name__ == '__main__' is quiet common in python. It's not necessary for your function, but I like using it in answers if people seem to learn Python, so they don't miss out on it. Here is a question with a good answer: What does if __name__ == "__main__": do?
The short answer in the accepted answer is enough to understand why you might want to use it.
The second condition
user_input = ""
while not user_input.isdigit():
first defines a variable user_input with an arbitrary non-digit String value and than uses the negated isdigit() method of the String class on it as condition. Therefor the while loop gets entered in the beginning, as the arbitrary value is not an digit. From then on the value will be re-assigned with user input until it holds an actual digit. This digit is still a String however.
First thing while loop in the function makes no sense you can remove it(If you want).
There are multiple ways to do that I will show.
First One.
def isItALeapYear(year):
if type(year) != int:
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
Another is.
def isItALeapYear(year):
try:
int(year)
except ValueError: # this line of code executes when the year is not the int
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
I know there are more ways to do that but these are the best ones (I Think).
Your function is not accurate then you can use this one.
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
Edit For Quetioner
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
try:
isItALeapYear(asdasd)
except NameError:
print("You give the wrong Value")

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.')

Code not checking values in list?

This program I am trying to build needs to check if the user's input corresponds to values in a list. Here is the code I have:
def find_val(val, seq):
for ele in seq:
if val == ele:
return True
return False
def get_input(possible_vals, day_or_time_string):
if day_or_time_string == "day":
answer = input("What day would you like your appointment? ")
else:
answer = input("What time would you like your appointment? ")
answer = answer.strip()
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
count = 0
while False:
second_answer = input("Invalid entry. Please enter a valid day: ")
count = count + 1
if count == 3:
print("This is getting silly - still not a valid entry")
if second_answer in possible_vals:
return second_answer
else:
return answer
day_list = ["Monday", "Tuesday", "Wednesday"]
res = get_input( day_list, "day" )
print("The funtion returned", res)
This is the type of output I should be getting:
What day would you like your appointment? saturday
Invaild entry. Please enter a valid day: Monday
The funtion returned Monday
However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list:
What day would you like your appointment? akw
The function returned akw
What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list?
First
valid_entry = find_val(answer, possible_vals)
if valid_entry == True:
can be simplified to
if answer in possible_vals:
(your find_val function is totally unnecessary)
Then your problem is that
while False:
...
simply never executes... Did you mean while True? If so You'll need to somehow break out this (now) infinite loop using a break statement for example.
And finally as A.G. suggests, you explicitly tell your program to return answer when it's not "valid" so why do you expect otherwise?

Python, True/False, integrate function into program

I'm relatively new to python. I want to make a program that checks if a date is valid or not. I wrote the function code to check for leap years so far. But I want to integrate into the bigger program that checks for the validity of the month and date as well. How can I say in the last line "when C is true continue with a certain if else logic (...code that I will write later)" and "when C is false continue with this other if else logic"
def leap_year(c):
if c % 4 == 0 and y % 100 != 0:
print("True (Non-Centurial)")
else:
if c % 400 == 0:
print("True (Centurial)")
else:
print("False")
pass
for c == True:
...(my if else statements)
You can implement a if-else structure using the elif keyword:
if c % 4 == 0 and y % 100 != 0:
print("True (Non-Centurial)")
elif c % 400 == 0:
print("True (Centurial)")
elif condition1:
pass
elif contition2:
pass
else
print("False")
It may be what you're looking for.
if(c): # Checks if C is True,
then… # If so, it gets in
return … # Otherwise, it goes other way
Keep in mind your leap_year function, must return something in oder to make this work

Int in raw_input does not work [duplicate]

This question already has answers here:
How can I convert a string to an int in Python?
(8 answers)
Closed 8 years ago.
while True:
a = raw_input("Your number: ")
if a == int: # letters:
if a > 0 and a % 3 == 0:
print 'fizz'
if a > 0 and a % 5 == 0:
print 'buzz'
if a > 0 and a % 3 != 0 and a % 5 != 0:
print a
if a <= 0:
print 'bad value'
else:
print "Not integer, try again"`
How do I make this raw_input work? I want this to run the game when the user input is an integer and "try again" when it is not.
raw_input() always returns a string. If you want to make it an int, call the int() builtin function. If the contents of the string cannot be converted, a ValueError will be raised. You can build the logic of your program around that, if you wish.
raw_input is a string. You can convert it to an int using int. If it's not convertible, this returns an error. So use try... except to handle the error. It's a good idea to put as little as possible into the try... part because otherwise some other error might be accidentally caught. Then put in a continue into the except part to skip back to the start.
while True:
try:
a= int(raw_input("Your number: "))
except ValueError:
print "not integer, try again"
continue
if a > 0:
if a % 3 == 0:
print 'fizz'
if a % 5 == 0:
print 'buzz'
if a % 3 != 0 and a % 5 != 0:
print a
else: #a<=0
print 'bad value'

Categories

Resources