After getting result , it also mentions the memory location - python-3.x

def is_leap(num):
if(num % 400 == 0):
print("The year {} is a leap year".format(num))
elif(num % 4 == 0 and num % 100!= 0):
print("The year {} is a leap year".format(num))
else:
print("The year {} is not a leap year".format(num))
return is_leap
year = is_leap(2000)
print(year
)
I get the result but it also mentions this - function is_leap at 0x101a581e0
how can I avoid this? I have tried to resolve this myself after googling I found that I am returning my own function but still I am not able to figure it out on which part of the code should I modify

In the function you return 'is_leap', which is the function itself, meaning after year = is_leap(2000), the year variable refers to the function itself, and you print that stored value. Since you already print your result inside is_leap(), there is no need for returning something, or for using
print(is_leap(x))
If you simply remove the return statement from the function and then call it like is_leap(2000)
you should achieve what you want.

def is_leap(num):
is_leap_year=False
if(num % 400 == 0):
is_leap_year=True
print("The year {} is a leap year".format(num))
elif(num % 4 == 0 and num % 100!= 0):
is_leap_year=True
print("The year {} is a leap year".format(num))
else:
print("The year {} is not a leap year".format(num))
return is_leap_year
year = is_leap(2000)
print(year)
I think you want to set boolean either it is leap year or not but you are returning funtion name and printing it which is reference address of function.

Related

I have written a python code for identifying leap year. It works perfectly but the code seems a bit off

I have written a code for identifying leap year. It works perfectly but the code seems a bit off. I have added the code here. Plz someone confirm whether the code is correct or not.
the code
year = int(input("Which year do you want to check? "))
divided_by_4 = year % 4
divided_by_100 = year % 100
divided_by_400 = year % 400
if divided_by_4 == 0 and divided_by_400 == 0 or divided_by_100 != 0:
print("It is a leap year.")
else:
print("Not a leap year.")
A year is not a leap year if it is divisible by 100, unless it is divisible by 400, so you should test divided_by_100 != 0 first and then use the or operator to test divided_by_400 == 0 as a fallback. Since or has a lower operator precedence than and, you should enclose the or operation in parentheses:
if divided_by_4 == 0 and (divided_by_100 != 0 or divided_by_400 == 0):
print("It is a leap year.")
else:
print("Not a leap year.")

Cant figure out why this code is failing a single test

I'm trying to learn python more by solving the hacker rank puzzles and I can't understand why it is failing
This code is supposed to determine whether or not a year that is or above 1900 is, in fact, a leap year, the website says it passes 5 of 6 tests. For the input
2100 it's returning true instead of false.
def is_leap(year):
leap = False
if year%4==0:
return True
elif year%100==0:
return False
elif year%400==0:
return True
return leap
year = int(input())
print(is_leap(year))
I expect it to return false if the year is not divisible by 100 and return true if it is divisible by 4 or 400.
Let's see what happens if the year is, e.g. 1900, a year that was not a leap year:
Since year % 4 is 0, we return True immediately, which is of course wrong. In fact, any number that is divisible by 100 or 400 must also be divisible by 4, meaning that we never even get to the bottom two conditions.
So the solution is to reorder your conditions from most to least specific:
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
Your second misunderstanding has to do with return: A return statement doesn't somehow "mark" a value to be the return value at the end of the function, it immediately exits the function, returning that value. For better consistency, I would remove the leap variable, and just return False at the end of the function. Alternatively, you could assign to leap inside the conditions instead of returning there.
Your if statement is not changing the variable leap.
Try changing the variable leap like below.
def is_leap(year):
leap = False
if year%4==0:
leap = True
elif year%100==0:
leap = False
elif year%400==0:
leap = True
return leap
year = int(input())
print(is_leap(year))
def foo(year: int) -> bool:
"find a year is leapyear or not"
if year % 4 == 0 and year % 100 != 0:
return True
return year % 4 == 0 and year % 100 == 0 and year % 400 == 0
The function takes an integer as argument for the year parameter and returns True if the year is a leap year and False for the opposite. A year needs to be divisible by 4 and not by 100 to be a confirmed leap year. So, the conditional statement checks for that. If the condition's met it returns True else that function does not return anything and continues downward. Then, if the number is divisible by 4 and 100 and 400 as this case also means the year is a confirmed leap year, it returns True. We have done all checks and still if that's not True then certainly the years not a leap year.

While loop only looping 3 times

I'm trying to create a sum game where the problems are randomly generated. I'm using the random module to generate numbers and then asking for the user to input answers, then trying to compare user input to a variable that already contains the correct answer.
After 5 questions I want the while loop to break and 'end the game', but it's doing some strange things. It will loop 3 times then call a correct answer incorrect (See function CheckAnswer()) It's like my function to check user input against the correct answer isn't running, but I can't find where it's failing.
I'm pretty new to Python and this is the first project i'm attempting on my own. I didn't want it to be simple.
I've really just tried messing around with my functions and code to see if anything improves and it's worked for me until now.
point = 0
q_num = 0
def RandomNums():
rNum1 = random.randrange(51)
rNum2 = random.randrange(51)
return rNum1
return rNum2
def Add():
rNum1 = RandomNums()
rNum2 = RandomNums()
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = rNum1 + rNum2
return question
print(answer)
return answer
#Check actual answer against user input
def CheckAnswer():
if question == answer:
point += 1
print("Correct! +1 Point!")
print(point)
else:
print("Wrong. Next question.")
time.sleep(1)
# Ask user to choose their operator
op = input("Which operator do you want to use (x, -, /, +)?: ").strip().lower()
if op == 'x':
while q_num < 5:
RandomNums()
Multiply()
question = Multiply()
answer = Multiply()
CheckAnswer()
q_num += 1
print(point)
elif op == '+':
while q_num < 5:
RandomNums()
Add()
question = Add()
answer = Add()
CheckAnswer()
q_num += 1
print(point)
else:
print("What!? That's not a choice!")
I expect that if I get the answer correct (on input) that I'll get the print statement inside my CheckAnswer() function and that 1 will be added to my 'point' variable. I also expect that my 'q_num' variable will increase by 1 regardless because I want the while loop to break at 5 questions, ending the game.
What I get when I run the program is I can input anything and it won't tell me anything, regardless of whether it's correct or not. The while loop will loop 3 times and say my answer is incorrect on the 4th loop. Then it seems to reset the loop and q_num count.
Several problems here, and first I strongly recommend taking a python course, or working through an online book. I worry that you're going to develop some very serious misconceptions that I already see in your code.
First off, and I don't know how to say this so that you'll absorb it, the computer executes instructions in order, one at a time. This is a hard lesson to learn, especially if you try to learn it after already playing around with code some!
I know, because I remember as a kid wanting something to work with BASIC for loops that makes no sense if you've properly absorbed this lesson, but that made perfect sense to me at the time.
In your code, the consequence of not absorbing this lesson properly are the multiple return statements in a function. Once the computer hits one return statement, it leaves the function. This means that stuff after the first return statement that's encountered doesn't happen.
So let's take a look at your Add function:
def Add():
rNum1 = RandomNums()
rNum2 = RandomNums()
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = rNum1 + rNum2
return question
print(answer)
return answer
It's going to get two random numbers (we'll ignore the issues in RandomNums for the moment), then it's going to ask a question, take what the user did, put it in the local variable question, compute something for the local variable answer and then return the local variable question.
That's it. It's done then. It never does anything else.
This means that later in your program, when you say:
question = Add()
answer = Add()
What happens is that you ask the user two questions, and then set the global variable question to what the user said the first time, and set the global variable answer to what the user said the second time.
So your loop is really doing this:
RandomNums() # Compute two random numbers, return one, throw result away
Add() # Make a question, ask the user, throw the result away
question = Add() # Make a question, ask the user, store what they said
answer = Add() # Make a question, ask the user, store what they said
CheckAnswer() # Check if what the user said both times is the same, print message
q_num += 1 # increment loop number
print(point) # print point total
So your while loop wasn't running three times - it was running once, and in that one loop you were asking the user a question three times.
So you'd think then that something you could do is answer the same thing the last two times, and then you'd at least get the "correct answer" message. Unfortunately, you don't, because of another problem that's something slightly tricky about Python. What happens is this:
Which operator do you want to use (x, -, /, +)?: +
What is 40 + 31?: 3
What is 13 + 31?: 3
What is 2 + 9?: 3
Traceback (most recent call last):
File "/tmp/quiz.py", line 49, in <module>
CheckAnswer()
File "/tmp/quiz.py", line 24, in CheckAnswer
point += 1
UnboundLocalError: local variable 'point' referenced before assignment
What's happening here is that python thinks that point is a variable name that is local to the function CheckAnswer, when you of course want CheckAnswer to be modifying the global variable called point. Usually, python does the right thing with whether a variable should be global or local, (after all, it correctly deduced that you wanted to deal with the global answer and question) but += 1 looks like you're setting a new value (it's equivalent to point = point + 1), so python thought you meant a local variable called point. You can tell it otherwise by adding a global point statement to the top of CheckAnswer:
def CheckAnswer():
global point
if question == answer:
point += 1
print("Correct! +1 Point!")
print(point)
else:
print("Wrong. Next question.")
time.sleep(1)
Now when I play your quiz, this happens:
$ python /tmp/tst.py
Which operator do you want to use (x, -, /, +)?: +
What is 19 + 18?: 3
What is 4 + 39?: 3
What is 15 + 27?: 3
Correct! +1 Point!
1
1
What is 19 + 31?: 3
What is 21 + 47?: 4
What is 23 + 39?: 3
Wrong. Next question.
1
What is 45 + 12?: 2
What is 8 + 32?: 3
What is 28 + 16?: 3
Correct! +1 Point!
2
2
What is 23 + 0?: 0
What is 20 + 28?: 1
What is 0 + 49?: 2
Wrong. Next question.
2
What is 42 + 4?: 0
What is 27 + 18?: 1
What is 16 + 8?: 2
Wrong. Next question.
2
So that's a tiny improvement, and you can see that the loop is happening five times as expected.
Okay, so what about the problem you had before that you need to return two things, but the function stops at the first return statement?
What you can do is return something that in python is called a tuple, and then you can unpack it at the other end:
def RandomNums():
rNum1 = random.randrange(51)
rNum2 = random.randrange(51)
return (rNum1, rNum2) # return two things as a tuple
def Add():
(rNum1, rNum2) = RandomNums() # Unpack the tuple into two variables
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = rNum1 + rNum2
return (question, answer) # return a tuple of question and answer
And then later:
elif op == '+':
while q_num < 5:
(question, answer) = Add()
CheckAnswer()
q_num += 1
print("Points are: {}".format(point))
So this almost works. Unfortunately, it says our answer is wrong every time!
That's because in python, strings and integers are different things. What you got from the user (question) will be the string '40' whereas the answer you computed will be the integer 40. So to properly compare them, you need to either turn answer into a string or turn question into an integer.
I chose in the code below to turn answer into a string, but you could take the other choice if you're okay with your program blowing up when the user enters something that isn't an integer. (My experience with users is that they'll start to enter swear words into your program after a bit, which naturally won't turn into integers). The function in python to turn most things into a string is str.
So here's the whole program now:
# in your post, you forgot these import statements
import time
import random
# set up global variables
point = 0
q_num = 0
def RandomNums():
rNum1 = random.randrange(51)
rNum2 = random.randrange(51)
return (rNum1, rNum2) # return a tuple
def Add():
(rNum1, rNum2) = RandomNums() # unpack tuple into two variables
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = str(rNum1 + rNum2) # Note how answer is now a string
return (question, answer)
#Check actual answer against user input
def CheckAnswer():
global point # need this since we assign to point in this function
if question == answer:
point += 1
print("Correct! +1 Point!")
print(point)
else:
print("Wrong. Next question.")
time.sleep(1)
# Ask user to choose their operator
op = input("Which operator do you want to use (x, -, /, +)?: ").strip().lower()
if op == 'x':
while q_num < 5:
print("Not done yet, come back later")
break # Now the computer won't try anything below; break exits the while loop
(question, answer) = Multiply()
CheckAnswer()
q_num += 1
print("Points are: {}".format(point))
elif op == '+':
while q_num < 5:
(question, answer) = Add()
CheckAnswer()
q_num += 1
print("Points are: {}".format(point))
else:
print("What!? That's not a choice! (yet)")
Now go implement the rest of your quiz.
A small suggestion: for - and especially for /, you might want to have the two random numbers chosen be the second operand and the answer, instead of the two operands. For example:
def Divide():
(answer, rNum2) = RandomNums() # unpack tuple into two variables
product = rNum2 * answer # good thing answer isn't a string yet, or this wouldn't work
question = input("What is {} / {}?: ".format(product, rNum2))
answer = str(answer) # change answer to a string, now that we're done doing math
return (question, answer)

A simple question about Collatz Function,Why this is a unreachable code?

I'm a new learner of python, when I try to write a Collatz function I find that pycharm shows me one line is unreachable. I wonder why the function can't run the code
def Collatz(numBer):
if numBer%2 == 0:
return numBer//2
else:
return 3*numBer+1
print(numBer) #this code is unreachale
print('Please input the number:')
numBer = int(input())
while numBer != 1:
Collatz(numBer)
print(Collatz(numBer)) #because the former code are unreachable,so I write this to print the results
numBer = Collatz(numBer)
All code within the same scope below a return statement is unreachable because the function will finish its execution there. In your case you are returning the result so there is no need to rerun the function again to print it. Just take it in a variable and use it:
def Collatz(numBer):
if numBer%2 == 0:
return numBer//2
else:
return 3*numBer+1
print('Please input the number:')
numBer = int(input())
while numBer != 1:
numBer = Collatz(numBer)
print(numBer)
Hello welcome to Stack Overflow!
The reason why the print is "unreachable" is because of the return before the print. return ends a control flow so any code after the return is disregarded. Basically, the control flow goes like this (based on your function):
"Is the numBer divisible by 2?"
"If yes, then give me the integer division of that number and 2"
"Otherwise, give me the 3*number + 1"
If you wanted to print the number before you return it, it would be best to store it first into a variable and then return that variable, like so:
def Collatz(numBer):
if Collatz % 2 == 0:
value = numBer // 2
else:
value = 3 * numBer + 1
print(value)
return value

How can I count and display my recursive steps in Python?

I am trying to count how many times my program goes through my recursive statement and gives me my result. This is the code:
def days(amt):
day = 0
new = (amt*.05) + amt - 10
if amt == 0:
return 0
elif amt == '':
return
elif new >= 0 and new <= 1000:
day += 1
return days(new)
print("In {} days, you'll have {}".format(day,new))
So when you call the function days(100), it calculates that it takes 15 days to reach new amount which less than 0 or greater than 1000 (and then it stops bc it satisfies the second elif condition).
So I want my output to look like this In 15 days, you'll have -7.892....
My problem is no matter where I place the counter, it doesn't count.
To persist the count you need to either use some global variable or use a parameter to do the counting then return both the count and the amt:
def days(amt, day=1):
new = (amt * .05) + amt - 10
if amt == 0:
return day, 0
elif 0 <= new <= 1000:
return days(new, day + 1)
return day, new
Which gives you:
In [2]: print("In {} days, you'll have {}".format(*days(100)))
In 15 days, you'll have -7.89281794114
You cannot set day = 0 anywhere in the function as every call is going to reset it to 0. I also removes elif amt == '' as I cannot see how a function that takes an int/float should ever equal to an empty string.

Resources