I have a task to write a program which for a sequence number as a result give a geometric mean. I have to write this program without any package.
The introduction of the program end, when users give a 0.
The program should report an error if the first number is 0 and if the user gives a negative number.
def sequence():
prod=1
i=-1
x=1
n = int(input("Give a number: "))
while True:
if n == 0:
break
elif i==0:
print("Error")
else:
prod=prod*n
i=i+1
result=prod**(1/i)
print(" Średnia wartośc ciągu ", result)
return i, suma
sequence()
My program doesn't return anything.
I don't want to post the solution, I'd rather point out several problems with the code. Figuring them out on your own will make you a better coder. There are several problems with your algorithm:
You'd better start with i=0
elif i==0: won't work as you expect it has to be an if i==0: under if n==0:, so that you exit the loop when you get 0 from the user and you print Error when it is the first iteration.
n = int(input("Give a number: ")) has to be within the loop, so that it gets assigned on every iteration of your algorithm.
return i, suma should be outside the while loop.
Related
I am working on a function that sums up the amount of positive and negative numbers a user inputs. It has to be in a loop and has to have two functions(on for pos, one for neg) to return True or False. I have tried everything and am so lost and don't even know where to start anymore. This is what I have so far:
pos = 0
neg = 0
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
while num > -100 or num < 100:
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
if num > 100 or num < -100:
print("Please only enter integers between -100 to 100")
num = int(input("Please enter a positive or negative number. Or 0 to quit"))
elif num == 0:
print("Here is your summary: ")
print("You entered: ", pos, "positives number(s) and", neg, "negative number(s)")
def if_positive(pos):
if num > 0:
pos = pos + 1
def if_negative(neg):
if num < 0:
neg = neg + 1
if_positive(pos)
if_negative(neg)
Every time I try something, I get one part correct and then the other wrong. Python for Everybody hasn't helped at all and I've done hours of research and nothing helps. Please help me. Every time I post a question on here it gets removed! I have no idea what I'm doing wrong, I am just trying to ask a simple question :( So I will try for the third time!
Lets do it as follow
Lets have while loop then if the num is zero just break it otherwise check the conditions
I have added two lists but if you just count how many numbers positive and negative then you don't need lists you can use integer count variables
postive_numbers =[]
negative_numbers =[]
while True:
num = int(input("Please enter a positive or negative number. Or 0 to quit\n Enter the number: "))
if num>100 or num < -100:
print("Please only enter integers between -100 to 100")
continue
if num == 0:
print("Here is your summary:\n ")
print("You entered: \npositives number(s) {} \nnegative number(s){} ".format(len(postive_numbers),len(negative_numbers)))
break
elif num< 0:
negative_numbers.append(num)
else:
postive_numbers.append(num)
If I had to guess, I'd say your questions are being removed because they sound like school assignments, and people tend to sour a little at the idea of people going to StackOverflow to have others do their homework for them. That said, it seems to me like you've put in a good-faith effort based on what you've already written, and there's nothing wrong with asking for help when you don't understand something after trying to figure it out yourself.
Try this:
def is_positive(number):
"""
This could be shortened to simply:
`return number > 0`
"""
if number > 0:
return True
else:
return False
def is_negative(number):
"""
Similarly, this could be shortened to:
`return number < 0`
"""
if number < 0:
return True
else:
return False
n_positive = 0
n_negative = 0
while True:
num_entered = int(input("Please enter a positive or negative number. Or 0 to quit"))
if not -100 < num_entered < 100:
print("Please only enter integers between -100 to 100")
elif is_positive(num_entered):
# this is a shortcut for `n_positive = n_positive + 1`
n_positive += 1
elif is_negative(num_entered):
n_negative += 1
else:
break
print("Here is your summary:")
# this is equivalent to what you had in your question, but uses "f-strings",
# which were implemented in Python 3.6 and are super convenient
print(f"You entered {n_positive} positive number(s) and {n_negative} negative number(s)")
A few extra notes you might find helpful:
if not -100 < num_entered < 100: is equivalent to if num > 100 or num < -100:, but just a cleaner way of writing it
while True is an idiom in Python that essentially means "keep looping forever until I break out of it or exit the program." From the code you had written, it seems like you want to keep allowing the user to input numbers until they enter "0 to quit". That's the condition upon which you want to break out of the loop.
"def" itself isn't a function -- def is a keyword that defines a function, which is a snippet of code that performs a single task that can be re-used later. You said your two functions needed to return True or False. In Python, the return keyword causes a function to exit and "return" the value specified.
This is why you're able to use those pre-defined functions directly in the the if and elif statements later. You can think of the way "if" works as taking the code between if and : and evaluating it. If it evaluates to True, then the block of code inside (i.e., indented under) the if statement is executed and any elif or else statements you may or may not have after that are skipped. Or, if it evaluates to False, then Python "moves on," and if you have an elif statement after the if, it repeats the same process there. Finally, if neither or if or elif blocks evaluate to True and you have an else block, that code is run.
This is a very long way of saying that in your case, the logical flow is: "if the number isn't between -100 and 100, remind the user of the acceptable range of values. Otherwise, if the number is_positive, add 1 to the running count of positive numbers entered. Or, if the number is_negative, add 1 to the count of negative numbers. Otherwise, the only remaining possibility is that the number is 0, so the user is finished entering numbers and we should break out of the loop and show them their summary.
Hope this helps! Feel free to comment with any other questions you have.
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.
Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue
I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))
New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.
import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the while loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).
Here's an example:
counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
The value printed will be the number of times the while loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.
You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:
print('The while loop ran {} times'.format(counter))
Calling the format function on a string allows you replace each instance of {} within the string with an argument.
Edit: Changed to reassignment operator