I need some help creating a python program that does the following:
Execution:
Enter an integer: 10
Enter an integer: 5
Enter an integer: 3
Enter an integer: 0
Numbers entered: 4
Sum: 18
Max: 10
Min: 0
I currently have this and I am stuck:
user_input = " "
while user_input != "":
user_input = input("Enter a number, or nothing to quit: ")
if user_input != "":
user_input = int(user_input)
user_input += 1
print(user_input)
Help would be much appreciated!
You can first collect the inputs in a list, and then print the results, where f-strings are handy:
lst = []
while (user_input := input("Enter a number (blank to quit): ").strip()):
lst.append(int(user_input))
print(f"You have entered {len(lst)} numbers:", *lst)
print(f"Sum: {sum(lst)}")
print(f"Max: {max(lst)}")
print(f"Min: {min(lst)}")
If you are not familiar with walrus operator :=, then
lst = []
user_input = input("Enter a number: ").strip() # ask for input
while user_input != '': # check whether it is empty (!= '' can be omitted)
lst.append(int(user_input))
user_input = input("Enter a number (blank to quit): ").strip() # ask for input
Example:
Enter a number (blank to quit): 1
Enter a number (blank to quit): 2
Enter a number (blank to quit): 3
Enter a number (blank to quit):
You have entered 3 numbers: 1 2 3
Sum: 6
Max: 3
Min: 1
Detailed version:
user_inputs_values = []
user_inputs_count = 0 # (a)
user_input = input("Enter a number: ")
user_inputs_values.append(int(user_input))
user_inputs_count += 1 # (a)
while True:
user_input = input("Enter another number, or enter to quit: ")
if not user_input:
break
user_inputs_values.append(int(user_input))
user_inputs_count += 1 # (a)
print(f"Numbers entered: {user_inputs_count}") # (b)
print(f"Sum: {sum(user_inputs_values)}")
print(f"Max: {max(user_inputs_values)}")
print(f"Min: {min(user_inputs_values)}")
Note that the first input message is different than the following ones.
Note using a count of entries is also possible, taas the count is equal to len(user_inputs_values). So you can remove lines marked (a) and replace line marked (b) with:
print(f"Numbers entered: {len(user_inputs_values)}")
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 21 days ago.
Don't know how to convert strings to integers.
I tried putting int around it and it still didn't work frstn = int(input("Type first number: "))
import math
# frstn means first number
# scndn means second number
op = input("What operator do you want? + - / *: ")
if op == "+":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn + scndn)
elif op == "-":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn - scndn)
elif op == "/":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn / scndn)
elif op == "*":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn * scndn)
else:
print("Invalid operator, reboot calculator.")
You are looking to cast the user input into an int.
firstn = int(input("Type the first number: "))
This will take the user input and turn it into a number that you can now use it for arithmetic operations.
You could probably move your input statements outside the if statements. If you would like to keep the same style then you could think of something along the lines of
firstn = int(input("Type the first number: "))
op = input("What operator do you want? + - / *: ")
secondn = int(input("Type the second number: "))
if op == "+":
print(firstn + secondn)
....
This is my assigned task :
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. Enter 7, 2, bob, 10, and 4 and having as output:
Invalid input
Maximum is 10
Minimum is 2
This is what I have so far but is not showing me the maximum neither the minimum of the inputs , as is not showing the Invalid input whenever the user try to put any word in it .
list = []
for i in range(2,10):
list.append(int(input('Ingrese un nĂºmero\n')))
# Ordenar lista
list.sort()
# Numero menor
print(list[0])
# Numero mayor
print(list[-1])
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
Code:-
lis = []
while True:
try:
num=int(input("Enter a number: "))
lis.append(num)
except ValueError:
print("It is not a number.. please verify!! Invalid input\n")
check=input("If you want to continue to write number please enter. if you are done please write done:\n")
if check.lower() == "done":
break
print("Maximum", max(lis))
print("Minimum",min(lis))
Output:-
Enter a number: 7
If you want to continue to write number please enter. if you are done please write done:
Enter a number: 2
If you want to continue to write number please enter. if you are done please write done:
Enter a number: bob
It is not a number.. please verify!! Invalid input
If you want to continue to write number please enter. if you are done please write done:
Enter a number: 10
If you want to continue to write number please enter. if you are done please write done:
done
Maximum 10
Minimum 2
You can use walrus operator (:=) to prompt and check if num equals 'done' or not. Catch invalid num using try except and add num to numlist if it can be casted to int. Print out the largest and the smallest num of numlist using max() and min().
numlist = []
while (num := input('Enter a number: ')) != 'done':
try: numlist += [int(num)]
except ValueError: print('Invalid input')
print('Maximum is', max(numlist))
print('Minimum is', min(numlist))
Output:
Enter a number: 7
Enter a number: 2
Enter a number: bob
Invalid input
Enter a number: 10
Enter a number: 4
Enter a number: done
Maximum is 10
Minimum is 2
I need to write a program that asks the user to enter a number, n, which is -6
The numbers needed to be printed using a field width of 2 and need to be right justified. Fields must be seperated by a single space, with no space after the final field.
so far this is what i have got to this:
n = int(input("Enter the start number: "))
if n>-6 and n<93:
for i in range(n, n+7):
print("{:>2}".format(i), end=" ")
But I still seem to be getting spacing issues, any help would be much appreciated!
n = int(input("Enter the start number: "))
if n>-6 and n<93:
for i in range(n, n+7):
if i < n + 6:
print("{:>2}".format(i), end=" ")
else:
print("{:>2}".format(i))
Solution
n = int(input("Enter the start number: "))
width = int(input('Enter width : '))
if n>-6 and n<93:
for i,val in enumerate(range(n,n+width)):
if i==(width-1):
print("{}".format(val))
else:
print("{}".format(val),
end=" ")
Output
Enter the start number: 5
Enter width : 5
5 6 7 8 9
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)))
the program asks user to enter 5 unique number, if the number is already in the list, ask for a new number. after 5 unique numbers have been entered, display the list
numbers = ['1','2','3','4','5']
count = 0
index = 0
while count <6:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
if user not in numbers:
print "unique"
count += 1
numbers = numbers.replace(index,user)
index +=1
print numbers
when the program gets to the replace method, it raise an attribute error
You can use:
numbers[index] = user
A list doesn't have a replace() method. A string does have a replace method however.
If you wish to append a number to the end of a list, you can use append():
numbers.append(user)
If you wish to insert a number at a given position, you can use insert() (for example, position 0):
numbers.insert(0, user)
You don't have to initialize a list in Python:
numbers = []
while len(numbers) != 5:
num = raw_input('Enter a number: ')
if num not in numbers:
numbers.append(num)
else:
print('{} is already added'.format(num))
print(numbers)
You can replace it with Subscript notation, like this
numbers[index] = user
Apart from that your program can be improved, like this
numbers = []
while len(numbers) < 5:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
else:
print "unique"
numbers.append(user)
print numbers
If you don't care about the order of the numbers, you should probably look into sets. Addidionally, if you want to work with numbers, not strings, you should cast the string to an int. I would've written something like this.
nums = set()
while len(nums) < 5:
try:
nums.add(int(raw_input("Enter a number: ")))
except ValueError:
print 'That is not a number!'
print 'Numbers entered: {}'.format(', '.join(str(x) for x in nums))
Output:
Enter a number: 5
Numbers entered: 5
Enter a number: 3
Numbers entered: 3, 5
Enter a number: 1
Numbers entered: 1, 3, 5
Enter a number: 7
Numbers entered: 1, 3, 5, 7
Enter a number: 9
Numbers entered: 1, 3, 9, 5, 7