Deleting numbers from lists.PYTHON - python

I am creating a python program, to allow a user to input numbers and find the total, average, highest and lowest of the numbers inputted. my teacher has told me to improve the program by removing the first and last number inputted into the list.I am confused on how doing so,as the list does not exist until the user has inputted the numbers into it.
THIS IS MY CODE SO FAR:
totalList=[]
totalList = totalList[1:-1]
TotalNum = int(input("Please enter how many numbers are to be entered:"))
Change=TotalNum
Input=0
Total=0
while TotalNum>0:
TotalNum = TotalNum - 1
Input = int(input("Enter Number: "))
totalList.insert(-1,Input)
Total = Total +Input
print("Total:" ,Total)
print("Average:",Total/Change)
print("Highest:",max(totalList))
print("Lowest:",min(totalList))

Related

I have to generate random integers in python, but the user has to say how many integers they want to generate [duplicate]

This question already has answers here:
Generate 'n' unique random numbers within a range [duplicate]
(4 answers)
Closed 2 years ago.
I have to ask the user how many numbers they want to generate and then i can generate integers according to them in the range of 0 to a 100. If the user wants 5 numbers I have to generate 5 random numbers, but have no clue how.
input("How many numbers should the string consist of? ") #The user gives a number
for i in range(4): # I used a 4 but its going to be the users input
print(random.randint(0, 100)) #The integers will print
Afterwards I have to calculate the total of all the integers generated,
The total is: sum of generated integers.
from random import randint
def random_generate(count: int):
for _ in range(count):
yield randint(0, 100)
for num in random_generate(20):
print("random number is:", num)
Change the for i in range loop iteration count to the number of integers the user wants:
num = int(input("How many numbers should the string consist of? "))
for i in range(num):
print(random.randint(0, 100)) #The integers will print
Afterwards I have to calculate the total of all the integers generated, The total is: sum of generated integers.
Add a variable to count all the integers, in this case it is count:
num = int(input("How many numbers should the string consist of? "))
count=0
for i in range(num):
randomnumber = random.randint(0, 100)
print(randomnumber)
count += randomnumber
print(count)
Looks like i posted at the same time as Daniil
To add to Daniils answer:
You could also do a validation for when the user does not enter an integer it gets promted again.
import random
while True:
try:
user_input_str = input("How many numbers should the string consist of?") #The user gives a number
num = int(user_input_str)
break
except ValueError:
print(f"{user_input_str} is not an integer, please enter an integer)")
total_sum = 0
for i in range(num): # I used a 4 but its going to be the users input
random_int = random.randint(0, 100)
print(f"#{i} Random int: {random_int}")
total_sum = total_sum + random_int
print(f"Total sum: {total_sum}")

While loop user input?

Instructions: Create a program that asks a user to enter a series of numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.
I am using Python 2, Python IDLE
I'm using a while loop for this assignment. So far, I made a program that is saying, while the user enters a positive number under the while loop, collect that number and keep adding it until the user enters a negative number. I am trying to find a way to include the first user input into the program.
print('This program calculates the sum of the numbers entered and ends
after inputting a negative number')
total = 0.00
number = float(input('Enter a number: '))
while number >= 0:
print('Enter another positive value if you wish to continue. Enter a
negative number to calculate the sum.')
number = float(input('Enter a number: '))
total = total + number
print('The sum is', total)
Have reduced your code to the below.
Performs checking of input in while loop and exits upon negative value.
total = 0.00
while True:
print('Enter another positive value if you wish to continue. Enter a negative number to calculate the sum.')
number = float(input('Enter a number: '))
if number >= 0: # Check for positive numbers in loop
total += number
else:
break
print('The sum is', total)
I assume you're a beginner, so firstly welcome to Python! I hope you're having fun. Now, as far as your code goes, there are two things I noticed off the bat:
You can simply put this 'Enter another positive value if you wish to continue.
Enter a negative number to calculate the sum.' inside your input, why bother
with an extra print statement?
You don't have to call the input() function twice.
Here's how I'd do it:
print('This program calculates the sum of the numbers entered and ends
after inputting a negative number')
total = 0.00
while True:
number = float(input("Enter a positive number(Negative number if you wish to terminate program"))
if number >=0:
total += number #equivalent to total=total + sum
else:
break # break out of while loop
print('The sum is', total)
P.S - Why are you using Python 2 btw ?

Calculating averages with inputted numbers using for loop

I'm trying to calculate an average of the numbers that are inputted following the "Enter the number" part. I don't know how to add the inputted numbers as they aren't set variables. When I run it, it says 'int object is not iterable'
I thought about asking for each number separately, but I wouldn't know how to make it repeat the set number of times for each time the question is asked. So I use the for loop, but by using the for loop, I can't set numbers to variables, so I can't add them.
Apparently sum function can help, but nothing I've looked at shows me how to use it very well.
how_many = int(input("How many numbers are there?"))
for counter in range (1, (how_many + 1)):
numbers = int(input("Enter number:"))
sum1 = sum(numbers)
av = sum1 / how_many
The result of the code is supposed to show the average of the numbers inputted but I can't figure out how to work out the total?
You can do it like this.
how_many = int(input("How many numbers are there?"))
total_sum=0
for counter in range (1, (how_many + 1)):
number = int(input("Enter number:"))
total_sum = total_sum+number
avg = total_sum / how_many
print(avg)
sum calculates the total in an iterable, eg list.
If we loop, and add the number to a list each time, we can calculate the average at the end.
This should do the trick:
how_many = int(input("How many numbers are there?"))
numbers = []
for counter in range (how_many):
numbers.append(int(input("Enter number:")))
total = sum(numbers)
av = total / how_many
print("Average:", av)
Output:
How many numbers are there?5
Enter number:1
Enter number:2
Enter number:3
Enter number:4
Enter number:5
Average: 3.0

While loop won't terminate

Learning Python. This task is to allow the user to enter numbers as long as the number isn't -99. If the sentinel -99 is entered, the user will no longer be able to enter numbers, and the largest and smallest numbers that have already been entered will be displayed. When I enter the number -99, however, the loop continues to ask for new numbers.
#main module
def main():
#Instructions for user
print ("This program will allow the user to enter several numbers,
positive ")
print ("or negative, and sort the largest and smallest numbers from
them.")
#First number entered by user
inputNum = input ("Enter a number other than -99 to be sorted: ")
#variables
number = inputNum
small=number
large=number
#while loop for getting/sorting numbers
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = input("Enter a number other than -99 to be sorted: ")
lgSm()
#Module for displaying large and small numbers
def lgSm():
print ("The largest number you entered is: ", large)
print ("The smallest number you entered is: ", small)
main()
Edit:
Solved. I forgot to add the variables inside the ()...I'm not sure what these are called, but I do understood their function. Are they called placeholder variables?
#main module
def main():
#Instructions for user
print ("This program will allow the user to enter several numbers, positive ")
print ("or negative, and sort the largest and smallest numbers from them.")
#First number entered by user
inputNum = int (input ("Enter a number other than -99 to be sorted: "))
#variables
number=inputNum
small=number
large=number
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = int (input("Enter a number other than -99 to be sorted: "))
number = inputNum
lgSm(large, small)
#Module for displaying large and small numbers
def lgSm(lg, sm):
print ("The largest number you entered is: ", lg)
print ("The smallest number you entered is: ", sm)
main()
Modify your while loop to update number variable; the value of number is not changing inside the loop
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = int(input("Enter a number other than -99 to be sorted: "))
number = inputNum ## this line in particular

How can I add the same variable multiple times in python?

This is my code (Python 3.2)
Total = eval(input("How many numbers do you want to enter? "))
#say the user enters 3
for i in range(Total):
Numbers = input("Please enter a number ")
#User enters in 1
#User enters in 2
#User enters in 3
print ("The sum of the numbers you entered is", Numbers)
#It displays 3 instead of 6
How do i get it to add up properly?
Just a quick and dirty rewrite of your lines:
Total = int(input("How many numbers do you want to enter? "))
#say the user enters 3
Numbers=[]
for i in range(Total):
Numbers.append(int(input("Please enter a number "))
#User enters in 1
#User enters in 2
#User enters in 3
print ("The sum of the numbers you entered is", sum(Numbers))
#It displays 3 instead of 6
I assume that you use Python 3 because of the way you print, but if you use Python 2 use raw_input instead of input.
This code will fix your problem:
total = int(input("How many numbers do you want to enter? "))
#say the user enters 3
sum_input = 0
for i in range(total):
sum_input += int(input("Please enter a number "))
#User enters in 1
#User enters in 2
#User enters in 3
print ("The sum of the numbers you entered are", sum_input)
A number of comments:
You should stick to pep8 for styling and variable names. Specifically, use under_store for variable names and function names, and CapWords for class names.
The use of eval is questionable here. This article explains very well on why you shouldn't use eval in most cases.
You need to declare your variable outside the for loop, and keep on adding input numbers to it in the loop..
numbers = 0
for i in range(Total):
numbers += int(input("Please enter a number "))
print ("The sum of the numbers you entered are", numbers)

Categories

Resources