Python not summing list correctly - python

Python is not summing all items in the list. What did I do wrong?
I'm trying to make a program that calculates the average of inputed numbers and it seems like the len() is working correctly but sum() is only summing some numbers.
numbers = []
More = True
while More:
xInp = input('Number: ')
yInp = input('Again?(y/n) ')
if yInp == 'y':
numbers.append(int(xInp))
elif yInp == 'n':
break
print(sum(numbers))
print(len(numbers) + 1)
print(sum(numbers) / int(len(numbers) + 1))

The problem is the order, you are exiting the program without considering the last value being input. Altering the order a bit will help you solve the issue. Furthermore be careful with apostrophes and doble apostrophes, I've edited that in the answer too, as it will return a SyntaxError otherwise:
numbers = []
while True:
xInp = input('Number: ')
numbers.append(int(xInp))
yInp = input('Again?(y/n) ')
if yInp == 'y':
pass
elif yInp == 'n':
break
print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

Your code will only add the most recently-entered number to the array if the user selects y at the next prompt. Once they enter n, the last number entered is not appended to the list.
You need to append the number right after it has been entered, then check if the user wants to add more.
numbers = []
while True: # No need for a variable here
xInp = input("Number: ")
numbers.append(int(xInp))
yInp = input("Again? (y/n): ")
if yInp == "y":
pass
elif yInp == "n":
break
print(sum(numbers))
By convention, variables start with lowercase letters. Uppercase first letters are for class definitions (not instances). I had originally changed More to more, but as mentioned in the comments, it is not even necessary, so I replaced it with while True.

You missed the last value in more than one values.
numbers = []
More = True
while More:
xInp = input('Number: ')
yInp = input('Again?(y/n) ')
if yInp == 'y':
numbers.append(int(xInp))
elif yInp == 'n':
if xInp:
numbers.append(int(xInp))
break
print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

Related

How to change a range in a while loop with input in Python?

I'm new to python and I'm trying to write a program that will guess the users number.
I'm trying to change the range that's in a while loop, depending on the users answer, but i'm not sure how can I do that.
list = range(100)
half = len(list)//2
def the_guess():
guess = "n"
while guess != "y":
guess = input('is it ' + str(len(list)//2) + '? up(+) or down(-) ?\n')
if guess == 'y':
print('I knew it!!')
break #stops loop?
else:
if guess == '+':
print(list[half:])
# use second part of the range
if guess == '-':
print(list[:half])
# use first part of the range
else:
print("ok, let's try again\n")
the_guess()
The loop works, i'm just not sure how to go about changing the value of the range to something other than 100.
for example:
if the user inputs a "+" I want the range to change to 50 - 100, and will continue to dividing it depending on the users input.

How to create simple menu in Python with list functions?

Please have a look at the exercise that i was asked to do. I am struggling for hours now to make it work.
There has to be a menu with the following choices: add a number, remove number (enter placeholder), show list.
Each time choice is made program should ask if we want to re-run the script.
Tried loops, functions and it just doesn't seem to work with me.
See the code below.
Thank you in advance!
def list():
operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list
''')
mylist = []
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
else:
print('You have not chosen a valid operator, please run the program again.')
again()
def again():
list_again = input('''
Would you like to see main menu again? (Y/N)
''')
if list_again.upper() == 'Y':
list()
elif list_again.upper() == 'N':
print('OK. Bye bye. :)')
else:
again()
list()
You can use https://github.com/CITGuru/PyInquirer for than kind of menus.
As the others have pointed out, your mylist variable needs to be moved.
That said, I find that your mechanism of returning to the input query could be refined. See the code below. Here you keep everything in one function, without having to repeatedly ask the user if he/she would like to continue, it continues indefinately until you consciously break out of it.
def main():
mylist = []
while True:
operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list
[4] Exit programm
''')
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
elif operation == '4':
break
else:
print("Invalid choice. Please try again.")
main()
Sidebar: "list" is a fixed expression in python. I would refrain from using it and others like it as variable names.
Verified Code
mylist = []
def list():
operation = input('''Select operation:\n [1] Add number to the list \n [2] Remove number from the list \n [3] Display list\n ''')
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
else:
print('You have not chosen a valid operator, please run the program again.')
again()
def again():
list_again = input('''Would you like to see main menu again? (Y/N)''')
if list_again.upper() == 'Y':
list()
elif list_again.upper() == 'N':
print('OK. Bye bye. :)')
else:
again()
list()
Cheers!
Try moving mylist = [] outside of the function.

While loop with functions and if/break statement?

I’m just starting to learn functions and I am practicing on implementing some into my code. Just a simple example... how can I code this to loop properly and break out when the user wants?
def profit(i,c):
gain = c - i
print('Your profit is:' + '' + str(gain))
def beginning():
x = float(input("What was your initial investment?"))
y = float(input("What is your investment worth now?"))
profit(x,y)
beginning()
ans = 'y'
while ans == 'y' or ans == 'Y':
ans = str(input('Would you like to calculate another investment? (Y/N)'))
beginning()
if ans != 'y' or ans != 'Y':
break
There are two ways to break out of a while loop. The first way is obviously the break statement, kind of like you have done. For it to work correctly, you need to change the condition:
if ans != 'y' or ans != 'Y':
break
This will always be true, since ans cannot be "y" and "Y" at the same time. You should change it into:
if ans not in ["y", "Y"]:
Or
if ans.upper() != "Y":
In your case however, you don't need it at all. Since in both the if statement and the while condition you are checking ans, you can get rid of the if and just rely on this.
while ans.upper() == "Y":
This will end the loop automatically when ans becomes anything other than "Y" or "y".
The only reason you would use a break here is if you wanted to exit the loop immediately, and not complete the current iteration. For example:
while ans.upper() == "Y":
ans = input("Enter selection: ")
if ans == "I want to stop right now!":
break
print("Do other things, even if ans is not Y")
In this example, "Do other things" will always be printed regardless of ans, unless ans is "I want to stop", in which case it won't get printed.
One thing you can do is ans = ans.capitalize() after you get the user input. Then remove the ans != 'y' since that's causing your loop to break.

error when validating user input

I'm trying to create a menu-driven program that will generate 5 random integers between 0 and 9, and store them in a List. I want it to then allow the user to enter an integer and then search the List, reporting on the location of the integer in the List (if found) or -1 if not. Then display the result of the search to the screen and re-display the menu.
def main():
choice = displayMenu()
while choice != '4':
if choice == '1':
createList()
elif choice == '2':
print(createList)
elif choice == '3':
searchList()
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = input("Enter option-->")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print("Invalid option. Please select again.")
return myChoice
import random
def linearSearch(myList):
target = int(input("--->"))
for i in range(len(myList)):
if myList[i] == target:
return i
return -1
#This will generate the five random numbers from 0 to 9
def createList():
newList = []
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
for i in range(5):
newList.append(random.randint(0,9))
return newList
#Option two to display the list
def displayList():
myList = newList
print("Your list is: ", newList)
#Option 3 to search the list
def searchList():
target = int(input("--->"))
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
However when it prompts the user for the five numbers it says invalid no matter what you enter. Could someone please give me an example on how I could fix this?
Careful with your input parsing. Either leave input as a string and deal with strings, or initially cast it to an int and continue dealing with ints.
myChoice = str(input())
# input 1
if myChoice in ['1', '2', '3', '4']:
print(myChoice)
or
myChoice = int(input())
# input 1
if myChoice in [1, 2, 3, 4]:
print(myChoice)
In createList, you are taking the input twice then referring to an undefined variable a
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
...
if any([num < 0 for num in a]):
Exception
should be something like
text_input = input("Give me five numbers: ")
numbers = [int(num) for num in text_input.split(' ')]
if any([num < 0 for num in numbers]):
raise ValueError
Your programme has a number of other oddities, but perhaps you're still working on these:
You don't do anything with the numbers you have input in createList but instead return a list of random numbers. Your description also suggests you want a list of random numbers, so why are you inputting the numbers in the first place?
You make variables myList and newList but your functions won't be able to access these unless you declare them as global or explicitly pass them as parameters
linearSearch can be written more simply using list.index:
.
def linearSearch(myList, target):
if target in myList:
return myList.index(target)
else:
return -1
OK - I found logical and syntax errors at multiple places. I will try to list them as possible.
Commented out redundent block of choices in displayMenu() function.
fixed main() function. You were not catching values/list returned by
functions
Defined myList as global list that needed to be passed
linearSearch(myList,target) had extra user input and tweaked logic
to work. It was only working for finding number at first index.Ideally you can use list.index(value) method to get index #
Commented out extra loop in createList() function
Tweaked functions to receive global list to work properly.
I've tweaked your code as little as possible. Commented out lines not required.
I believe it works as intended.
Working Code:
def main():
myList = []
choice = displayMenu()
while choice != '4':
if choice == '1':
myList =createList()
elif choice == '2':
#print(myList)
displayList(myList)
elif choice == '3':
searchList(myList)
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = str(input("Enter option-->"))
"""
if myChoice != 1 and myChoice != 2 and \
myChoice != 3 and myChoice != 4:
print("Invalid option. Please select again.")
"""
return myChoice
import random
def linearSearch(myList,target):
#target = int(input("--->"))
found = False
for i in range(len(myList)):
if myList[i] == target:
found = True
return i
if found == False:
return -1
#This will generate the five random numbers from 0 to 9
def createList():
print "Creating list..............."
newList = []
"""
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
"""
for i in range(5):
newList.append(random.randint(0,9))
#print newList
return newList
#Option two to display the list
def displayList(myList):
#myList = newList
print("Your list is: ", myList)
#Option 3 to search the list
def searchList(myList):
target = int(input("--->"))
#print("Searching for" , target)
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
Output
>>>
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->1
Creating list...............
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->2
('Your list is: ', [1, 4, 6, 9, 3])
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->4
('Found at', 1)
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->9
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->10
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->10
Not found...
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->4
Thanks for playing!
>>>
Final notes,
You may want to start with something simple such create a menu that prints different sentences for different choices to see if it works and then go as complex as you wish.
Change
myChoice = input("Enter option-->")
to
myChoice = str(input("Enter option-->"))
Function input returns an integer, and comparison with str will allways return False.

Double or quit/while loop

I know how to use a while loop, but I'm not sure about the part where I need to make a command to double the previous score.
The task is to double or quit.
And this is my code at the moment:
import random
play = 'y'
Original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
newnumber = Original*2
print (newnumber)
play = input("Play again?[y/n]: ")
No need for defining a new var newnumber, just rewrite the Original
by doing original = original*2
import random
play = 'y'
original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
original = original*2
print (original)
play = input("Play again?[y/n]: ")
No need to bring in variable newnumber. Also, dont use mix of upper and lower case variables.
import random
play = 'y'
original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
original= original*2 # or shorthand: original *= 2
print (original)
play = input("Play again?[y/n]: ")
You were assigning the new variable value (original * 2) to a locally scoped variable to the loop, so every iteration, original is still 1.
import random
play = 'y'
original = 1
while play.lower() == 'y':
if (random.randint(0, 3) == 0):
print('Unlucky... better luck next time')
else:
original *= 2; print(original)
play = input('Play again? [y/n]: ')
If you are trying to get the Original variable to be doubled, there's no need for bringing newNumber into the mix. Just use
Original = Original * 2 (or Original *= 2, for short).

Categories