Loop won't finish...Poor indentation? - python-3.x

I am new to python and Jupyter Notebook
The objective of the code I am writing is to request the user to introduce 10 different integers. The program is supposed to return the highest odd number introduced previously by the user.
My code is as followws:
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: '))
if c%2==0:
print('The number is even')
elif c> y
y=c
print('y')
i=i+1
My loop is running over and over again, and I don't get a solution.
I guess the code is well written. It must be a slight detail I am not seeing.
Any help would be much appreciated!

You have elif c > y, you should just need to add a colon there so it's elif c > y:

Yup.
i=1
c=1
y=1
while i<=10:
c=int(input('Enter an integer number: ')) # This line was off
if c%2==0:
print('The number is even')
elif c> y: # Need also ':'
y=c
print('y')
i=i+1

You can right this in a much compact fashion like so.
Start by asking for 10 numbers in a single line, separated by a space. Then split the string by , into a list of numbers and exit the code if exactly 10 numbers are not provided.
numbers_str = input("Input 10 integers separated by a comma(,) >>> ")
numbers = [int(number.strip()) for number in numbers_str.split(',')]
if len(numbers) != 10:
print("You didn't enter 10 numbers! try again")
exit()
A bad run of the code above might be
Input 10 integers separated by a comma(,) >>> 1,2,3,4
You didn't enter 10 numbers! try again
Assuming 10 integers are provided, loop through the elements, considering only odd numbers and updating highest odd number as you go.
largest = None
for number in numbers:
if number % 2 != 0 and (not largest or number > largest):
largest = number
Finally, check if the largest number is None, which means we didn't have any odd numbers, so provide the user that information, otherwise display the largest odd number
if largest is None:
print("You didn't enter any odd numbers")
else:
print("Your largest odd number was:", largest)
Possible outputs are
Input 10 integers separated by a comma(,) >>> 1,2,3,4,5,6,7,8,9,10
Your largest odd number was: 9
Input 10 integers separated by a comma(,) >>> 2,4,6,8,2,4,6,8,2,4
You didn't enter any odd numbers

Related

Just started python and working through Automate The Boring Stuff with Python. Any recommendations on cleaning my code?

New here at stackoverflow. I'm learning python right now and picked up the book Automate the Boring Stuff with Python. Need some recommendations or tips on how to clean up my code. Here is one of the small projects from the book:
Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
The output of this program could look something like this:
Enter number:
3
10
5
16
8
4
2
1
Here's the code I came up with. Any recommendations on cleaning up the code or is this good enough? Thank you all!
def collatz(number):
if number % 2 == 0: # Even numbers
print(number // 2)
return number // 2
elif number % 2 == 1: # Odd numbers
result = 3 * number + 1
print(result)
return result
while True: # Made a loop until a number is entered
try:
n = input("Enter a random number: ")
while n != 1:
n = collatz(int(n))
break
except ValueError:
print("Enter numbers only.")
Use else in the place of elif , it will give same reasult.
Optimized for readability and usage, not on performance.
def collatz(number):
print(n)
return number // 2 if number % 2 == 0 else 3 * number + 1
while True: # Made a loop until a number is entered
try:
n = input("Enter a random number: ")
while n != 1: n = collatz(int(n))
break
except ValueError: print("Enter numbers only.")

Python, How do I ignore a string such as 'done' amongst numbers to sum the total from a list

while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
I've had a hard time understanding exactley what u want to do with this code, please use a proper code block next time, with proper indentation. My guess is that u want to get a input number like 345 and add 3+4+5 as a output. If the input is not a int it should break the loop. Ive come up with 2 diffrent solutions, depending on what you need.
This code will simply take the input and check if it is "done", if it is not "done" it will try to add. This is a easy to understand solution but it will produce a error if the input is any diffrent string than "done".
while True:
numbers = input(">")
if numbers == "done":
break
else:
total = 0
for number in numbers:
total += int(number)
print(total)
This approach will test for the "done" string again, but afterwards will also check if the input can be converted into a int. if not the error is captured and it will return "invalid input". If u want the programm to terminate at any string u can just put break in the except section.
while True:
numbers = input(">")
if numbers == "done":
break
else:
try:
testing = int(numbers)
total = 0
for number in numbers:
total += int(number)
except:
total = "invalid input"
print(total)
im a Beginner myself and if a experiencend person can show me a better way to do this i would be very interested
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
Assuming this as your code:
Here's a solution to your problem-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
total=0
for number in numbers:
total = total + int(number)
print(total)
By default everything gets accepted as string so we convert it to integer to find total.
Also we use list to store all the values we accept.
Another Solution is-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
p=map(int,numbers)
print(sum(p))
Hope you understand the solution :-)
total = 0
average = 0
count = 0
while True:
numbers = input('> ')
if numbers == 'done': break
try:
total = int(numbers) + total
count = count + 1
except:
print('nope')
try:
average = total / count
except:
print('error')
print(total)
print(average)
print(count)
Try this:
total = 0
number_of_inputs = 0
while True:
number_string = input('Enter a number: ')
try:
total += float(number_string)
number_of_inputs += 1
except ValueError:
break # we weren't given a number, so exit the loop
# Now that we're outside of the loop, print out the total:
print('The total is:', total)
if number_of_inputs > 0:
average = total / number_of_inputs
print('The average is:', average)
else:
print('The average cannot be calculated, as no inputs were given.')
Do you see what's happening? The while loop keeps ask for and adding integers to total until a non-integer (like "done") is given. Once it gets that non-integer, the int() function will fail, and the exception it throws will get caught, and the code will immediately break out of the while loop.
And once out of the loop, the total and the average are printed out.
A few things you should be aware of:
If the user gave no inputs (which is possible here), the total will correctly print out as 0, but if you try to calculate the average, you will error, due to diving by number_of_inputs (which is also 0). That is why I check that number_of_inputs is greater than zero before I even attempt to calculate the average.
Originally I used int() to convert the string to a number, but I changed it to use float() instead. I figure that since you want to calculate an average, averages are not necessarily integers (even if all the inputs are), so there's no point in enforcing integer input. That is why I changed the int() to float(), but whether or not you want to use it is up to you.
ValueError isn't a function; it's an Exception. At this point you probably don't know what Exceptions are, so just know that they are special cases that can happen, and they're often used for catching errors, such as bad input values.
In the code I posted above, the loop is always expecting numerical input. But as soon as we have input that can't be converted to a number, the program then says, "Hey, I have an exception to what we're expecting! The exception is that there's an error in the value!" Then the program, instead of continuing to the next line of code (which is number_of_inputs += 1) will then execute the block of code under the except ValueError: section. And in the code above, all it does is call break, which exits the loop.
Once out of the loop, the code prints out the total and the average.
If it weren't for the try: and except ValueError: lines in the code, then the program would abruptly end (with a lengthy error message) once someone gave a non-numerical input. That happens because the call to float() wouldn't know how to convert a value like "done" to a number, so it does nothing more than just quitting.
However, by using try: and except ValueError:, we are anticipating that someone might give non-numerical input. When that happens (which it will, when the user is finished giving inputs) -- instead of quitting -- we want an alternate action to take. And we specify that alternate action to be a simple break out of the loop -- which will allow the program to continue with whatever is after the loop.
I hope this makes sense. If it doesn't, it will make more sense once you start learning about Exceptions in Python.

Adding more variables to result every while loop

I started to learn python last week and I have to write a while loop where the user is repeatedly asked to input an even number. Then, as long as he inputs an even number, the program should put out the sum of all of the previously added numbers. As soon as an odd number is added, the loop should stop without putting out the odd-numbered result.
Do you have any tipps?
thank you!
total = 0
while True:
number = int(input("enter number:" ))
if number % 2 == 0:
total += number
print(f"Total: {total}")
else:
print(f"Final total: {total}")
break
total = 0 - First, we want to initialize our total variable so that we can use it within the loop to count up the sum of all entries.
The while True: line starts an infinite loop. These can be dangerous, but we're going to break out of it later when a condition is met (in this case, an odd number being entered).
number = int(input("enter number: ")) asks the user for input, converts that input into and int and stores it in the variable called number.
if number % 2 == 0: - This checks whether or not the number is even using the modulo operator. This returns the remainder from the division of the first number into the second. For a number to be even, it must have a remainder of 0 when divided by 2.
total += number is shorthand for total = total + number. This simply adds the user's input to the total.
print(f"Total: {total}") prints out the total using an f-string. See PEP 498 for more info. Essentially, creating an f-string is as easy as putting an f before the literal string creation. This allows you to plug variables directly into strings instead of having to rely on the .format() method.
The above print line would be written as print("Total: {}".format(total)) if not using f-strings.
The else statement catches any number that is not even, so therefore must be odd. It prints out the final total and then break will make us leave our infinite loop.

for some input in python3 in increasing order of list not come right

my code is:
n=int(input())
list_1 = []
for i in range(n):
list_1.append(input())
list_2=[]
#print(list_1)
while list_1:
minimum = list_1[0]
for x in list_1:
if x < minimum:
minimum = x
list_2.append(minimum)
list_1.remove(minimum)
print (' '.join(map(str, list_2)))
all output come correct but incorrect come in some input like
4
10
3
7
6
please help
Your list 'list_1' is a list of strings, and for strings minimums work in a different manner. For example, '10' < '3' is True.
Change the line:
list_1.append(input())
To:
list_1.append(int(input()))
The first thing you should do when posting questions here is properly explain your problem, and what the code does.
Now for your question, Mono found the issue in your code, but you should know that you do not need all this to sort a list of numbers. It already exists in the language. Use the sort() function on the list, like this:
print("This script will ask you for numbers and print them back to you in order.")
print("Enter how many numbers you will input: ", end="")
n=int(input())
list_1 = []
print("Please type each number.")
for i in range(n):
print(" Number", i, ": ", end='')
list_1.append(int(input()))
list_1.sort()
print("These are your numbers, in order:")
print (' '.join(map(str, list_1)))
The output is:
This script will ask you for numbers and print them back to you in order.
Enter how many numbers you will input: 4
Please type each number.
Number 0 : 10
Number 1 : 2
Number 2 : 8
Number 3 : 3
These are your numbers, in order:
2 3 8 10

I am almost there but program can not recognize negatives

Program has to count positive and negative numbers and compute the average. I feel like i have the right code but maybe something is off. This was done on python idle 3.5. I would appreciate any and all help.
#Variables
total=0
pos=0
neg=0
avg=0
i=eval(input("Enter an integer, the input ends if it is 0:"))
#main
while (i!=0):
total=total+i
i=eval(input("Enter an integer, the input ends if it is 0:"))
if(i>0):
pos+=1
elif(i<0):
neg+=1
print("The number of positives is ", pos)
print("The number of negatives is ", neg)
print("The total is",total)
print("The average is ", avg)
avg=total/(pos+neg)
One Problem your code has is, that the first number you are entering does not count towards either the positive or negative counts in your loop because it is outside of it. As soon as you enter the loop you do add it to the total, but then you ask for the next number. This way your first number is never evaluated.
What you could do is a while loop that has the condition "True", so it runs every time you start the program. The evaluation on whether your input is a zero can be (and in this case must be) handled in your else/elif/else block.
If you don't include a break there you are getting an infinite loop.
You should not us eval(). The Documentation on python states this:
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()’s return value will be None.
If you use int() the program knows if it is negative or not since you compare the input to zero in your if statements.
Maybe do something like this:
#Variables
total = 0
pos = 0
neg = 0
# avg = 0 (you don't have to declare this variable since you calculate it
# anyway later on)
# removed the input from here since it did not contribute to the pos/neg count
#main
while (True):
# maybe use a while loop with the condition "True" so it runs every time
i = int(input("Enter an integer, the input ends if it is 0: "))
total = total + i
if(i > 0):
# counts 1 up if integer is positive
pos += 1
elif(i < 0):
# counts 1 up if integer is negative
neg += 1
else:
# break out of the loop as soon as none of the above conditions is true
# (since it hits a 0 as input)
# else you get an infinite loop
break
avg = total / (pos + neg)
print("The number of positives is ", pos)
print("The number of negatives is ", neg)
print("The total is ", total)
print("The average is ", avg)

Resources