I am new to python,trying to write program for finding amstrong and modulus . But I have problem in finding amstrong no,it will not go to end state,hang in the middle. However,modulus is working fine. It will not throw any error. Here is my code:
try:
def check(s):
if(s==1):
print 'enter the no'
v=[]
s=int(raw_input())
print s
for x in str(s):
print x
v.append(x)
print v
x=len(v)
i=0
y1=0
print v[0]
while(i<x):
y=int(v[i])
y=y**3
y1=y1+y
print y1
if(y1==s):
print "given no",s,"is amstrong no"
else:
print "given no",s,"is not a amstrong no"
elif(s==2):
print 'enter the 1st no'
s=int(raw_input())
print 'enter the 2nd no'
s1=int(raw_input())
ans=s%s1
print 'modulus ans is',ans
finally:
print "bye bye"
try:
print "1.amstrong 2.modulus"
x=int(raw_input())
if(x>=1 and x<=2):
check(x)
finally:
print 'bye bye'
Please help me on this.
The reason it's hanging in the middle is that you enter into the while loop while(i<x):, but you never change the value of either i or x. (You do change y and y1, but your conditional doesn't involve either.) The condition never ends up being false, and can't ever end up being false, so it continues to execute forever.
Note also that you're not really using try blocks correctly. There's no point in using try unless you're using except to handle any exceptions. (On a different level, you shouldn't be wrapping the entirety of your code in a try block in the first place - exceptions are useful information that make it easier to discover ways your program isn't working correctly, and ignoring them can lead to unpredictable, difficult-to-debug states.)
Last piece of advice - recognizing and fixing your problems is almost universally made easier (for both of us) by using distinct, pertinent names to your variables - it's very difficult to figure out what you're doing when every single variable is a single letter, and some are just a letter you've already used with a number appended.
You can check if a number is a 3-digit ammstrong using the function coded below.
This however is restricted to only 3 digits, but using loops correctly this will work of a greater number of digits as well. Almost in the way you have done. But always remember to increment or decrement the loop counter to prevent infinite loop. Otherwise the loop "will not go to end state,hang in the middle".
def Ammstrong(s):
n1=s/100
#n1 contains the 1st digit of number, s.
n2=s%100
n2=n2/10
#n2 contains the 2nd digit of number, s.
n3=s%10
#n3 contains the 3rd digit of number, s.
number=(n1**3)+(n2**3)+(n3**3)
if number==s:
print number,"is an Ammstron Number"
#return number
else:
print number,"is not an Ammstron Number"
#return number
num=input(Enter a number: ")
Ammstrong(num)
#use this if return is uesd:
#number=Ammstrong(num)
This function will print the answer. So, there wont be any need to use the print function in the main function to print your answer.
If you wish to perform further calculations, use 'return'. This is illustrated in the coded using comments. But, as soon as the return execution is executed, the program in which the statement is executed, terminates. Meaning the function will terminate not the main program. So, use the return function after the print function.
If you do use the return function u'll have to store the returned value in a variable.
One thing more:
You have made use of the variable x before initiating it.
And, instead of using (s==2) statement use (s!=0). "!=" is the symbol for "not equal"
Best of luck with learning python. It is a very interesting language.
http://pythontutor.com will show you the execution of the code step by step.
Related
I'm trying to create a loop if the condition is not met. If it is met at minimum second run, the print from my last run is also in my output, like in the example its printing the same print() that was printed in the previous run in addition to the result of the second run.
secretcode= r.randint(1, 100)
print("\n\n\nWelcome to the lottery!\n")
print("Guess a number from 1 to 100!")
print(secretcode)
def usrinput():
usrinputnumber = int(input("Your number: "))
schleife(usrinputnumber)
def schleife(usrinputnumber):
while not (secretcode == usrinputnumber):
if usrinputnumber > secretcode:
print("Awh damn! Your number is too high!!")
usrinput()
else:
print("Unlucky! YOur number is too low!")
usrinput()
print("Congratz! You guessed the number!!")
usrinput()
Everything works fine when I do an "if" instead the while and using the last print as "else"
Example:
The "secretcode" is 55.
As input I type 45.
The console prints "Unlucky! The number is too low!"
Now I type 55.
The console prints the "Congratz" message AND the "too low" message. Why the "too low" message?
I know functions are not needed, I just wanna know what the problem is and if I can run it in functions like I did.
Thank you very much!
This control flow does not make any sense. Please keep in mind that calling a function is not at all like telling the code to "go here next". It is a request to compute a result, which you will then use in the current context. It is also important to understand that each call to a function is a separate process. The function is not like a machine that is set in motion when called, but instead like a set of instructions that will be followed by a new executor, each time.
When usrinput() is called from within schleife, right now usrinput will call schleife again. That separate call has its own complete set of local variables, including the usrinputnumber parameter. Supposing that the user typed the correct secretcode, this call to schleife will escape its while loop, print the success message...
... and then return back the result of its computation (which is None) to its caller, the call of usrinput, which returns its result (also None) to the other call of schleife, which also hadn't finished yet. And, within that call, nothing has changed its local value for usrinputnumber, so the loop continues.
Remember that functions are supposed to do one thing. The purpose of usrinput is to get the user's input. The task performed by schleife is not a logical part of that task, therefore usrinput should not call schleife.
Instead: usrinput, instead of trying to feed the result of its computation (i.e., the user's input) to the "next step", should return that result - that is what return is for.
On the other hand, schleife can still call usrinput, because "get new user input to see if it matches this time" is a logical part of its task. Since the value will be returned, we need to make use of that by explicitly assigning it to usrinputnumber. We can also see that since schleife will be calling usrinput in the loop anyway, it makes as much sense to get the initial value that way, too.
Putting it together, we get:
def usrinput():
return int(input("Your number: "))
def schleife():
usrinputnumber = usrinput()
while not (secretcode == usrinputnumber):
if usrinputnumber > secretcode:
print("Awh damn! Your number is too high!!")
usrinputnumber = usrinput()
else:
print("Unlucky! YOur number is too low!")
usrinputnumber = usrinput()
print("Congratz! You guessed the number!!")
schleife()
I can't seem to find what's wrong. It gives me no error message, but instead just ends the process without printing the wanted message
def choose_chracter_class():
character_class_option = raw_input()
return character_class_option
if character_class_option is str("mage") or str("Mage"):
print "Mage, sorcerers who wield mass amounts of magic energy to cause havoc among their opponents, summon entities, or protect themselves from harm."
print "Attack - 5"
print "Magic Atk - 30"
print "Defence - 10"
print "Magic Def - 15"
print "Speed - 10"
if chracter_class_option is str("warrior") or str("Warrior"):
print "Warrior"
else:
print character_class_option + " isn't an option"
choose_chracter_class()
I agree with the previous comment that one issue is the return on the second line preventing the remaining code from executing. I also agree with the previous comment that using the .lower() would probably be cleaner code then checking for both the situations of lowercase 'mage' and the first letter being capital 'Mage'. By using .lower() you don't need to check both situations of 'mage' and 'Mage' as no matter how it is typed even if it is typed like: 'mAgE' then the code would still work.
However, I have one idea to get the code to work in a similar way that you have it set up.
You could also try:
if character_class_option == "mage" or character_class_option == "Mage"
In addition, I don't think it is necessary use str() on something that is already a string. However, I can understand you may have done this in an attempt to debug.
An Emirp is a prime number whose reversal is also a prime number. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
The following code compiles and accepts input. The input validation is correct but the program keeps running and does not output anything. I also wanted to know how it's possible to find errors in python. Please ignore indentation errors if there are any.
class negerror(UserWarning):
pass
while True:
prompt = input('Please enter a positive number: ')
try:
number=int(prompt)
if number<=0:
raise negerror
break
except ValueError:
print('You did not enter an integer. Please try again. ')
except negerror:
print('You entered a negative number. Please make sure to enter a positive number')
def isPrime(value):
count=0
for i in range(1,value+1):
if value%i==0:
count=count+1
if count<=2:
return True
else:
return False
def reverse(value):
val=str(value)
val=val[::-1]
val=int(val)
return val
Test=2
countemirps=0
numberinoneline=0
while countemirps<number:
if isPrime(Test) and isPrime(reverse(Test)):
print('%6s'%Test, end = ' ')
countemirps=countemirps+1
Test=Test+1
numberinoneline=numberinoneline+1
if numberinoneline%5==0:
print('\n')
Your isPrime function is off. It counts the number of divisors of value and stores it in variable count. However, you return True if count>2 and False otherwise. It should be the other way around: a prime number has two divisors and composite numbers have more then two. So change the test to count <= 2. Even better and more pythonic, replace the last lines of that function with
return count <= 2
or perhaps
return count == 2
Do you see why that works?
(I see that you have now corrected this error and edited your question but the program still does not work.)
Another error is that in your main loop you have the test
if isPrime(Test) and isPrime(reverse(Test)):
If that test is passed, you print the number and update your variables including Test--all is well. However, if the test fails you do nothing, and in particular the value of Test is not changed. The loop repeats and you do exactly the same test, and nothing changes. The program is stuck in an infinite loop.
You can fix this by moving the line that updates Test out of the if test and place it at the end of the loop so it is executed on each loop. Your loop then becomes
while countemirps<number:
if isPrime(Test) and isPrime(reverse(Test)):
print('%6s'%Test, end = ' ')
countemirps=countemirps+1
numberinoneline=numberinoneline+1
if numberinoneline%5==0:
print('\n')
Test=Test+1
When I test your program now, it seems to work.
There may be other errors as well that I do not see. You should test function isPrime separately from the rest of your code. When that works well, then test function reverse. Then test sections of your code. Running your code all at once makes it difficult to localize and find errors.
Finally, you ask "how it's possible to find errors in Python". This is too broad a question for this site--you should read a book chapter or a tutorial on debugging. But in brief, there are two main approaches for beginners. The first is to liberally put print statements in your code, showing the flow of the program execution and the values of your key variables. If you had place the statement
print(Test)
at the beginning of your loop, you would have seen that the loop was repeating indefinitely and the value of Test was not changing. When the errors seem to be gone, you can remove or comment-out the print statements. Logging can do this a bit more easily
Another, better approach is to use a debugger. I do most of my Python programming in Spyder, a development environment which includes a debugger. I used that to execute your program one line at a time, and one window in Spyder showed my the values of your variables. There also are debuggers that work outside a development environment. I encourage you to find, learn, and use an Integrated Development Environment that includes a debugger. Spyder is a free, excellent one that specializes in scientific programming. I use it for my mathematics programming.
My question is regarding this statement I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.
So I have this procedure that takes in two numbers as inputs and returns the greater of the two inputs.
Therefore, the 4th and 5th lines of code in this first example, which are at the same level of indentation as "if a>b:" should always run according to the statement above.
Example #1
def bigger(a,b):
if a>b:
x = "the first number is bigger"
x = "the second number is bigger"
return x
print bigger(9,7)
Python prints "the second number is bigger," so the code is working according to that original statement I wrote in the beginning. Even though that is false because 9>7.
But where I run into confusion is when return statements are used in the following example:
Example #2
def bigger(a,b):
if a>b:
return "the first number is bigger"
return "the second number is bigger"
print bigger(9,7)
This time, Python prints "the first number is bigger." This is true because 9>7
My confusion: Shouldn't the 4th line of code in this second example, "return "the second number is bigger"", always run because it's at the same indentation level of the "if statement," just like we saw in example #1?
It seems like the two examples of code contradict each other because in the example #1, Python recognizes the "second number is bigger" line and prints that line but in example #2, Python ignores the "second number is bigger" line and prints the other "first number is bigger" line.
I tried to make this as clear as possible. Thanks
My confusion: Shouldn't the 4th line of code in this second example,
"return "the second number is bigger"", always run because it's at the
same indentation level of the "if statement," just like we saw in
example #1?
This is because the function execution breaks when you have a return statement:
def bigger(a,b):
if a>b:
return "the first number is bigger" # function execution breaks here!!!
return "the second number is bigger"
print bigger(9,7)
You might want to read a little a bit about function and what return means.
Very briefly, if a return statement is executed the function goes out of scope and will not run anything after it.
In the first example, first it compares two values 9 and 7, then x = the first number is bigger, then it assigns x= the second number is bigger and return x. It is why you see this line.
In second example, it also compare two values, but it return x immediately, so it doesn't go the the next lines.
I think the "statement that you read" was a bit too simplistic. It is correct only if nothing changes Python's normal control flow during the if statement or the following indented block. It doesn't apply if the control flow is changed, which is exactly what you're doing in your second example. A return statement does change the control flow, to make the function exit immediately, so the rest of the code after the if does not get run.
Other statements that change the control flow are raise (and invalid operations that cause exceptions to be raised without an explicit raise statement), break and continue. The latter two are only valid in loops.
Please see the code below -
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
print "Let's do some math with just functions!"
age = add(float(raw_input("Add this:")), float(raw_input("To this:")))
Is there anyway, I can shorten the last line? Or, is there another way of getting user input?
Thanks
Applying "don't repeat yourself", we can take the repeated code and make a function out of it:
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
print "Let's do some math with just functions!"
def getf(prompt_mesg):
s = raw_input(prompt_mesg)
return float(s)
age = add(getf("Add this:"), getf("To this:"))
And then if you want you can make the input function handle errors better. Instead of raising an exception that takes down the whole program, you can handle errors gracefully:
def getf(prompt_mesg):
while True:
try:
s = raw_input(prompt_mesg)
return float(s)
except ValueError:
print("Could not convert that input. Please enter a number.")
This will loop forever until the user enters a valid input (or terminates the program).
I see you're using p2.x. First thing - I'd recommend switching to p3.x (it has many enhancements, but in this case you'll be happy to see that raw_input() became input() and input () with evaluation is gone).
Other way to shorten this stuff is using input() instead of raw_input(). If user gives you anything that is not a number, you'll get some sort of exception at addition, if he gives you a number (float, int, whatever) - your program will work.
==EDIT==
As glglgl pointed out - second part is dangerous and warning here is appriopriate. Using input() is basically the same as eval(raw_input()). Unfortunately, I forgot about the fact, that it doesnt take locals and globals parameters like eval - if it would, you could make it safe. For real-life applications it shouldnt be used, because some rogue user could evaluate anything he wants, causing program (or even computer) to crash. For simple apps like that, I stand my ground, and keep saying that it is useful.