Python - Can't figure out how to re-run my program - python

I have been having trouble trying to figure out how to re-execute this code. Nothing I have found has worked. If there is a way to do it without completely rewriting it that would be great. It took me a good amount of time just to get this to work at all.
def oddsquare(numbers):
for n in numbers:
if n % 2 == 1:
print n**2,
else:
return ""
startingnumber1 = int(raw_input('Enter your starting number:'))
endingnumber = int(raw_input('Enter your ending number:')) + 1
list1 = range(startingnumber1, endingnumber)
oddsquare(list1)

I think you are at a very beginner level. And assuming this I'll answer you.
When you return from the else statement, the loop ends, that's why you feel to "re-run" it
Corrected Code
def oddsquare(numbers):
for n in numbers:
if n % 2 == 1:
print n**2
startingnumber1 = int(raw_input('Enter your starting number:'))
endingnumber = int(raw_input('Enter your ending number:')) + 1
list1 = range(startingnumber1, endingnumber)
oddsquare(list1)
I'll suggest you one more thing, one my behalf, if you are not using python3 and above,
To input integers you can use input() instead of raw_input().
So the input lines of your code become :
startingnumber1 = input('Enter your starting number:'))
endingnumber = input('Enter your ending number:')) + 1

It would be a lot more easier if you defined re-run, but you could just place it all in a while loop, like so:
def oddsquare(numbers):
for n in numbers:
if n % 2 == 1:
print n**2
else:
return ""
while True:
startingnumber1 = int(raw_input('Enter your starting number:'))
endingnumber = int(raw_input('Enter your ending number:')) + 1
list1 = range(startingnumber1, endingnumber)
oddsquare(list1)
if you need to stop the loop you simply use "break".
Also, as the person in the comments mentions, no need for the else, that will actually break your code, because it will return nothing if it's not equal to one, so unless it's divisble with every number, it will fail.

Well, if you want something really short, you could put execfile(__file__) at the end of your program. You should probably do some error testing, however, so I would have it look more like this:
try:
execfile(__file__)
except (KeyboardInterrupt, EOFError) as e:
pass

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

calculate the sum of the digits of any three digit no(in my code loop is running every time help in correction)

my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))

python..I am stuck with one of the functions for and while loop

I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times
>>> game(3) #will run 3 times
I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!
import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
Do not use eval. You expect an integer from the user, use int.
Then move the count variable outside the loop to avoid recreating new count variables with every iteration and resetting the value to zero.
def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
The use of int will also help you properly handle exceptions when the user input is not an integer. See Handling exceptions.
P.S. On using eval: Is using eval in Python a bad practice?
Value of count is reinitialize every time to zero
def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=int(input('Enter your answer:'))
result=a+b
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print(count)
reason eval is insecure because eval can execute the code given as input eg.
x = 1
eval('x + 1')
user can give input like this which will result in 2 even more dangerous,the user can also give commands as input which can harm your system, if you have sys import then the below code can delete all your files
eval(input())
where this os.system('rm -R *') command can be given as input

How to add a set of numbers that the user inputted in Python?

How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])

Square number sequence in Python

I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
When I run this code it infinitely prints "1" ... I'm guessing that the value of a does not increase by += so it's a=1 forever. How do I fix this?
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
You're setting the value of a back to 1 on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1 line.
As others have noted, your specific problem is resetting a each time you loop. A much more Pythonic approach to this is the for loop:
for a in range(1, n):
print(a ** 2)
This means you don't have to manually increment a or decide when to break or otherwise exit a while loop, and is generally less prone to mistakes like resetting a.
Also, note that raw_input returns a string, you need to make it into an int:
n = int(raw_input("Enter number: "))
an even better idea is to make a simple function
def do_square(x):
return x*x
then just run a list comprehension on it
n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]
this is a more pythonic way to do what you are trying to do
you really want to use functions to define functional blocks that are easy to digest and potentially can be reused
you can extend this concept and create a function to get input from the user and do some validation on it
def get_user_int():
#a function to make sure the user enters an integer > 0
while True:
try:
n = int(raw_input("Enter a number greater than zero:"))
except TypeError:
print "Error!! expecting a number!"
continue;
if n > 0:
return n
print "Error: Expecting a number greater than zero!"
and then you can build your input right into your list
squares = [do_square(i) for i in range(1,get_user_int()+1)]
and really do_square is such a simple function we could easily just do it in our loop
squares = [x*x for x in range(1,get_user_int())]
The first line in your loop sets's a to one on every iteration.
You assign a=1 inside the loop. That means it's overwriting the a+=1.
try this:
n = eval(raw_input("Enter number"))
a=1
while a < n:
print a*a
a += 1
The issue here is that the value of a gets overridden every time you enter in the loop
Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..
def powers(x):
n=1
while((n**2)<=x):
print(n**2, end =' ')
n +=1

Categories

Resources