Odd/even range in python3.x - python-3.x

Given an input range (lowest/highest) and choice(odd/even) how can I print the desired output in python? In the below code it doesn't seem to be executing the else condition
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
oddeven = input("Do you want to see odd or even numbers: ")
print(oddeven)
for num in range(low, high):
if (num % 2 == 0):
print(num)
else :
if (num % 2 == 1):
print(num)

I think the easiest solution to implement, would be for you to create two for loops, one for the even case and one for the odd case, so you only have to check once rather than for each iteration of the for loop:
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
low = get_int_input("Enter the lowest number in the range (inclusive): ")
high = get_int_input("Enter the highest number in the range (inclusive): ")
valid_odd_even_responses = {"odd", "even"}
odd_even_response = ""
while odd_even_response not in valid_odd_even_responses:
odd_even_response = input(
"Do you want to see odd or even numbers: ").lower()
if odd_even_response == "odd":
for num in range(low, high + 1):
if num % 2 == 1:
print(num)
else:
for num in range(low, high + 1):
if num % 2 == 0:
print(num)
Example Usage:
Enter the lowest number in the range (inclusive): -1
Enter the highest number in the range (inclusive): 13
Do you want to see odd or even numbers: even
0
2
4
6
8
10
12

Some thoughts:
Check your indentation (look that "else")
"oddeven" is useless
You don't need num % 2 == 0, just num % 2, because, in python, 0 is 'false' already
You don't need the second 'if', because the 'else' is already doing the job bifurcating the flow in your program
If you're learning, try to draw your algorithm with paper and pencil before implementing it
Happy coding!

The first two lines are OK:
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
Here, I add a clarification that tells the user how to answer the question. Your code does not use this variable, that is why you get the wrong output.
even = int(input("Do you want to see odd (0) or even (1) numbers: "))
If the user wants even numbers but low is not even, or the other way around, adjust it:
if (even and low % 2 == 1) or (not even and low % 2 == 0):
low += 1
Step though all odd or even numbers:
print("\n".join(str(x) for x in range(low, high + 1, 2)))

Related

Having an issue relating to finding an Armstrong number from a list in Python [duplicate]

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

Python 3 for beginners Control Flow, While Loops and Break Statements

I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.

How to 'Write a script that computes and prints all of the positive divisors of a user-inputted positive number from lowest to highest in Python?'

Write a script that computes and prints all of the positive divisors of a user-inputted positive number from lowest to highest.
It was with the help of Pythontutor that I was able to get this far. If someone can suggest a better way than what I've done that is appreciated as well.
print('Please enter a positive number:')
num = int(input())
if num < 0:
print('Please enter a positive number:')
else:
for i in range(1,num+1):
calc = i / 2
if calc==int(calc):
print(i)
else:
continue
I expected for this to be considered correct since factors are being returned, but I think the problem is, for example if I input '4', it only returns 2 and 4, not 1.
The below code will work. The below code runs infinitely, Hit Ctrl + c to quit from below code. Remove while True: to remove infinite loop.
while True:
value = int(input('Please enter a positive number: '))
if value < 0:
continue
for i in range(1, value + 1):
if value % i == 0:
print(i)
Output:
1
2
4

How to fix this

This code is supposed to find all the primes in a given range. But something is very wrong here
import math
def display(num, truth):
if truth:
print(num)
lower = int(input("Enter lower limit :"))
upper = int(input("Enter upper limit :"))
for x in range(lower, upper, 1):
b = 2
c = True
a = math.sqrt(x)
while b < a:
if x%b != 0:
continue
else:
c = False
break
display(x,c)
print("Done")
I expect that it should output, say between 2 and 6:
Enter lower limit :2
Enter upper limit :6
2
3
5
Done
But the output is (for same range)
Enter lower limit :2
Enter upper limit :6
2
3
4
Note that 'Done' does not appear
And when I try to close the shell Python warns that the program is still running.
I am not sure to understand some of the code you have written.
How About something like this:
import math
lower = int(input("Enter lower limit :"))
upper = int(input("Enter upper limit :"))
for x in range(lower,upper + 1):
# prime numbers are greater than 1
if x > 1:
for i in range(2,x):
if (x % i) == 0:
break
else:
print(x)
print("Done")

Python 3 Count and While Loop

I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break
I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break
I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))

Resources