class TimeIterator:
def __init__(self,start,stop):
self.start=start
self.stop=stop
self.day=0
self.hr=0
self.sec=0
def __getitem__(self,index):
if index<self.stop-self.start:
time=self.start+index
day+=(((time//60)//60)%24)
hr+=((time//60)%60)
sec=(time%60)
raise IndexError
'{0:02d}:{1:02d}:{2:02d}'.format(day,hr,sec)
start, stop, index=map(int, input().split())
for i in TimeIterator(start,stop):
print(i)
print('\n', TimeIterator(start, stop)[index],sep='')
I'm trying to get results like
00:00:00
00:00:01
00:00:02
00:00:02
with the input 0 3 1
and I don't know what's wrong with the code here...Please help...
If you want a value to be returned by a function, you need to specify that value with a return statement.
Related
I'm pretty new to Python, Lately I was working on user input validation with nested try/except. My code is as below:
def user_input():
try:
myinput = 0
myinput = float(input("Enter a numberic value:"))
if myinput > 10:
raise ValueError('Expect a number between 0 and 10')
#print(myinput)
return myinput
except:
print("something went wrong try again!")
user_input()
print(user_input())
Though it was almost working as expected, I noticed an issue. When I call this function and at the initial stage if I pass an acceptable input the function returns the correct numeric value.
But when I try to input a false value initially and subsequently passing the correct value, the function seems not returning the numeric value. I tried to print the return output inside the function, there I'm getting the expected value.
Thanks in Advance
Try return user_input() instead of user_input() in the except block.
Hello i've been having some issues with jupyter notebook lately and am wondering if anyone knows why.
I'll sometimes have the program not execute and it'll have this symbol [*] so ill restart the kernal. Then it executes. However sometimes it wont produce the correct execution even though the code is correct. so I'll restart the kernel and clear my outputs. That usually fixes it. Now i'm working on this problem where i ask the user to answer a math problem if their input sum is correct it will say congrats if wrong it will say they got it incorrect. The program initially kept saying that user_answer was not defined. Then it didn't give me an error at all but would skip over the if statement and just print out the else: statement even if the answer given by the user was correct. is it my code? or is it the editor i'm using and if so how can i make it execute properly. I'm trying to learn python and i'm finding this a bit frustrating because i don't know if its my code or the editor half the time.
Here's my code:
import random
number_1 = random.randint(1,250)
number_2 = random.randint(1,250)
def main():
ask_question()
check_answer(user_answer)
def ask_question():
user_answer = int( input( "What is " +\
str(number_1 )+ ' + ' +\
str( number_2 ) + '? '))
return user_answer
def check_answer( user_answer ):
correct_answer = number_1 + number_2
if user_answer == correct_answer:
print("Congratulations", user_answer, +\
"is correct!")
else:
print("Sorry that is not correct the" +\
" answer should be", correct_answer)
main()
outputs:
**most common one**
What is 126 + 250? 8 (enter)
----------------------------------------------------
-----------------------
NameError Traceback
(most recent call last)
<ipython-input-2-99955f4e983a> in <module>
29 " answer should be",
correct_answer)
30
---> 31 main()
32
<ipython-input-2-99955f4e983a> in main()
6 def main():
7 ask_question()
----> 8 check_answer(user_answer)
9
10 def ask_question():
NameError: name 'user_answer' is not defined
OR
I'll get this and i didn't change anything in my
code..
What is 126 + 250? 376 (enter)
Sorry that is not correct the answer should be 376
The main function of your code is slightly wrong.
def main():
ask_question()
check_answer(user_answer)
In the check_answer function, replace user_answer with the number that the user enters. So, assign a variable to the ask_question function, which is then put into the check_answer function.
def main():
user_answer = ask_question()
check_answer(user_answer)
Also, it is not a good idea to mix local variables (variables that are inside functions) and global variables (variables that are outside functions). in your case, you are calling global variables (number_1 and number_2) inside the check_answer function, which is not good python.
A better way of creating this code would be to have only one function which chooses two random numbers, asks for the user answer and verifies if it is correct or not.
I was unable to reproduce the other error (of the answer being wrong).
I just wrote a function to search the binary tree for the closest number in tree. This is what I wrote below. However, it seems that the self.res in the dfs function does not renew the self.res in closeestValue function. I know I can write the dfs into the closestValue to solve the problem. But I do want to write two seperated functions. Is there any solution for that? Thank you!
class Solution:
"""
#param root: the given BST
#param target: the given target
#return: the value in the BST that is closest to the target
"""
def closestValue(self, root, target):
# write your code here
if root is None:
return None
self.res = root.val
self.dfs(root, target)
return self.res
def dfs(self, aroot, atarget):
if not aroot:
return None
if abs(aroot - atarget) < abs(self.res - atarget):
self.res = aroot.val
if atarget > aroot.val:
self.dfs(aroot.right, atarget)
else:
self.dfs(aroot.left, atarget)
return aroot.val
Problem solved. The call of res is not a problem. The abs(aroot - atarget) should be abs(aroot.val - atarget).
def twothousand(amt):
n=500
div1=amt//n
mod1=amt%n
return (mod1,n,div1)
def fivehundred(amt):
n=200
div1=amt//n
mod1=amt%n
return (mod1,n,div1)
def calculate(amt):
if amt <10:
print("hi")
elif amt>=200 and amt<500:
mod1,n,div1=fivehundred(amt)
return (mod1,n,div1)
#the above return statement isn't returning anything.
#That is, now the program doesn't go to the main function 2nd time.
elif amt>=500 and amt<2000:
mod1,n,div1=twothousand(amt)
return (mod1,n,div1)
def main1():
amt=int(input("Enter the amount: "))
mod1,n,div1=calculate(amt)
print (mod1,n,div1)
#The above print function executes only once.
if mod1!=0:
amt=mod1
calculate(amt)
if __name__=="__main__":
main1()
OUTPUT:
Enter the amount: 1700
200 500 3
EXPECTED OUTPUT:
Enter the amount: 1700
200 500 3
0 200 1
I'm unable to execute return statement after calculate() function call happens 2nd time, as written in comments.
I'm not getting the second output. New to python, kindly help.
sorry for not updating the logic earlier .
The logic is:
When user asks for an amount of 1700, he can only be given that amount using 500 and 200 currency. So, the 1st output is - 200 500 3 ; that is, 3 number of 500 currency.. and remaining is 200.
I want to call the function calculate till the value mod1 == 0.
Your main() function should look like this:
def main1():
amt=int(input("Enter the amount: "))
mod1,n,div1=calculate(amt)
print (mod1,n,div1)
#The above print function executes only once.
if mod1!=0:
amt=mod1
mod1,n,div1 = calculate(amt)
print (mod1,n,div1)
i'm new to python.i have been getting NZEC run time error for this code in codechef. i changed input() to raw_input().can someone explain to me why my code is getting a NZEC error
def function1(list1,sum):
if len(list1)==1:
return sum
m=min(list1)
i=list1.index(m)
if list1.count(m)>1:
sum+=list1.count(m)
else:
sum+=1
list1=list1[:i]
return function1(list1,sum)
t=int(raw_input())
global list1
global sum
while t>0:
n=int(raw_input())
sum=0
list1=list()
list1[1:n]=raw_input().split()
m=min(list1)
i=list1.index(m)
if i==0:
if list1.count(m)>1:
sum+=list1.count(m)
else:
sum+=1
print(sum)
else:
k=function1(list1,sum)
k+=1
print(k)
t-=1
You can do this this is solve my error.
put your all code in try and expect block.
This is solve my error.
try:
***your code***
except:
pass
(NZEC) I think you can't put custom input value in blank?
Ple click on custom input button check tick...
And write down some custom value on it in blank ... for test case
after you click to run...