Python 3 for beginners Control Flow, While Loops and Break Statements - python-3.x

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.

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)

Odd/even range in python3.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)))

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

We are getting an error with this while loop but cannot see why

The error we are getting is that it is looping infinitely and does not appear to be picking a number to be the correct choice
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 0
print ("Guess!")
guess = int( input())
while guessTaken < 6:
guess != guess+1
print ("Wrong!, guess again")
if guess == input():
print ("Correct")
print ( )
The loop's termination is based on the value of guessTaken; since that is never changed, once the loop is entered, it will never end.
Your code has many mistakes but I will try my best to fix them here:
First of all guess != guess+1 serves no purpose you are checking if guess is not equal to guess+1 (it isn't) which means that this line is always returning True and you aren't event doing anything with it.
I believe you meant to write:
guessTaken += 1
Which increments the number of guesses taken by 1
Next you will need to convert the second input to an int to compare it to guess so I recommend doing:
if guess == int(input()):
instead of
if guess == input():
Finally I suspect you want to exit the loop once the number has been guessed so I would add a break statement in the if condition as such:
if guess == int(input()):
print ("Correct")
break
You have many mistakes in your code. Not sure what you need, but you can try below:
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 0
wrong = True
print (number)
guess = int( input())
while guessTaken < 6: #Maximum guesses are 6
if guess != number:
print ("Wrong!, guess again")
guess = int( input())
else:
print ("Correct")
break #remember to put break when found correct number
guessTaken += 1
if guessTaken == 6:
print ("Maximum guessed")
I have tried to modify your code:
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 1
while guessTaken < 6:
if guessTaken == 1:
print('Guess!')
guess = input()
else:
print('Guess Again')
guess = input()
if int(guess) == number:
print('Correct')
break
else:
print('Wrong')
guessTaken = guessTaken + 1 #counter

I cant make the program continue to loop if its invalid input is entered

I have this program:
number = int(input('Contact Number:'))
def validatePhoneNumber(number):
count = 0
while True:
while number > 0:
number = number//10
count = count+1
if (count == 10) :
break
elif (count > 10) :
print('Invalid phone number')
return -1
elif (count < 10):
print('Invalid phone number')
return -1
validatePhoneNumber(number)
it will appear like this:
Contact Number:1234
Invalid phone number
>>>
I want it to continue to loop until a 10 digit number is entered then it will stop.
Contact Number:1234567890
>>>
The condition is that If the number is missing or invalid, return ‐1.
Am I missing something inside the program?
Thanks
What about this:
number = input('Contact Number:') # it's a str now, so we can use len(number)
def validatePhoneNumber(number):
while len(number) != 10:
number = input("Please enter a 10-digit contact number: ")
return number
number = validatePhoneNumber(number)
It's a more pythonic approach and therefore easier to understand and debug. Also as other comments pointed out, leading 0s aren't stripped away now.

Resources