got a error while compiling the code.
I tried to find smallest and largest value from user's input by storing the input in lists. After 'int' object not iterate problem, couldn't proceed further
largest=0
smallest=0
num=[]
while True:
num = int(input("Please enter a number: "))
for i in num:
if i>largest:
largest=i
for j in num:
if j<smallest:
smallest=j
if num==12:
break
print(largest)
print(smallest)
The moment you issue below code line num is no longer a list, instead its an int type of data.
num = int(input("Please enter a number: "))
As you can understand, there is nothing to iterate over in case of a single integer value.
The right solution is to read your input to a separate variable and append to your list.
input_num = int(input("Please enter a number: "))
num.append(input_num)
Further you will have to change value of your exit clause
if num==12:
break
If you desire to stop the loop after 12 inputs, then use len(num) == 12 in the if condition. In case you want to break loop if input number is 12 then change if condition to if input_num == 12
Note: Your algorithm has logical errors as well. You are assigning smallest to 0 . In case user enters all positive integers as input, your result will incorrect.
You are trying to iterate through a number which is wrong, you have overwritten your num list to an integer. Instead of the following:
num = int(input("Please enter a number: "))
You should save the number in some other variable and add to num list like:
x = int(input("Please enter a number: "))
num.append(x)
Related
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')
I'm a teacher, not a student, I promise :)
Exercise: Declare an array. Use manual input to add integers to array. If the user enters -1, stop accepting input and do not add -1 to the array.
Other requirements: this must be as simple as possible, as it is a very early exercise for students who are just starting to program, and must be compatible with iGCSE PseudoCode, which does not allow for breaks/interrupts.
The three versions we are debating at the moment are:
1. Break
elements = []
while True:
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
if user_input == -1: break
elements.append(user_input)
Argument against: break is not compatible with pseudocode
2. Repeat Input
elements = []
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
while user_input != -1:
elements.append(user_input)
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
Argument against: repeating the input line is inelegant, and a source of errors when you take this approach on larger programs.
3. Repeat Condition
elements = []
user_input = 0
while user_input != -1:
user_input = int(input("Please enter a whole number. When you want to stop type -1 "))
if user_input != -1:
elements.append(user_input)
Argument against: repeating the condition is inelegant, and this is the longest of the three options
Are there any more elegant solutions that still preserve simplicity?
My opinion is that using builtin functions is more pythonic:
list(iter(lambda: int(input("Please enter a whole number. When you want to stop type -1 ")), -1))
Explanation of iter(callable, sentinel): Returns an iterator which calls callable until it returns sentinel (In our case -1).
list() is used to cycle through the iterator and save the elements in a list.
You can also use a function instead of a lambda if you want to do some validation:
def input_number():
value = input("Please enter a whole number. When you want to stop type -1 ")
try:
return int(value)
except ValueError:
return -1
x = list(iter(input_number, -1))
Question: Create a program that allows the user to enter 10 different integers. If the user tries to enter
an integer that has already been entered, the program will alert the user immediately and
prompt the user to enter another integer. When 10 different integers have been entered,
the average of these 10 integers is displayed.
This is my code:
mylist = []
number = int(input("Enter value: "))
mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
if number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
else:
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
This kind of works but I need to create a loop that will keep on asking the user for another number if the number is in the array. Can you help?
What about:
mylist = []
number = int(input("Enter value: ")) mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
while number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
Code:
loop = 0
def main():
while loop == 0:
Num = input("Please Enter The Number Of People That Need The Cocktails ")
print()
print(" Type END if you want to end the program ")
print()
for count in range (Num):
with open("Cocktails.txt",mode="w",encoding="utf-8") as myFile:
print()
User = input("Please Enter What Cocktails You Would Like ")
if User == "END":
print(Num, "Has Been Written To The File ")
exit()
else:
myFile.write(User+"/n")
myFile.write(Num+"/n")
print()
print(User, "Has Been Written To The File ")
Error:
line 9, in main for count in range (Num): TypeError: 'str' object
cannot be interpreted as an integer
I'm trying to set the variable as the number of times it will repeat how many cocktails they would like.
Example:
How many cocktails ? 6
The script should then ask the user to enter what cocktails he wants six times.
In Python, input() returns a string by default. Change Num to:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
Also
MyFile.write(Num + "\n")
should read:
MyFile.write(str(Num) + "\n")
And just for the record, you can replace:
loop = 0
while (loop == 0):
with:
while True:
Cast int() on your input to make Num a workable integer. This has to be done because in Python 3, input always returns a string:
Num = int(input("Please Enter The Number Of People That Need The Cocktails "))
With your code in it's current state, you are trying to construct a range from a string, which will not work at all as range() requires an integer.
EDIT:
Now you must replace:
myFile.write(Num+"/n")
with:
myFile.write(str(Num)+"/n")
Num is an integer at this point, so you must explicitly make a string to concatenate it with a newline character.