I have used the sum function for the array.I need to use that so that if the list gets bigger, the total is still right. But I keep getting error.
This is the code I have:
print("please enter your 5 marks below")
#read 5 inputs
mark1 = input("enter mark 1: ")
mark2 = input("enter mark 2: ")
mark3 = input("enter mark 3: ")
mark4 = input("enter mark 4: ")
mark5 = input("enter mark 5: ")
#create array/list with five marks
marksList = [mark1, mark2, mark3, mark4, mark5]
#print the array/list
print(marksList)
#calculate the sum and average
sumOfMarks = sum(marksList)
averageOfMarks = sum(marks_ist)/5
#display results
print("The sum of your marks is: "+str(sumOfMarks))
print("The average of your marks is: "+str(averageOfMarks))
Thats because you get the input as a string and not int.
mark1 = int(input("enter mark 1: "))
Related
Here's the code i did:
list = input("Enter the number: ")
p = print("Trailing zeroes = ")
print(p, list.count("0"))
Output:
Enter the number: 10000
Trailing zeroes =
None 4
The output i wanted:
Enter the number: 10000
Trailing zeroes = 4
To count trailing zeroes you could do this:
num = input('Enter number: ')
ntz = len(s)-len(s.rstrip('0'))
print(f'Your input has {ntz} trailing zeroes')
Taking into account #OldBill 's comment & answer:
I corrected the code so that it gives an answer taking into account both of Op's problem.
The counting of the trailing zero is #OldBill 's code and not mine.
With
list = input("Enter the number: ")
p = print("Trailing zeroes = ")
print(p, list.count("0"))
What you do is p = print("Trailing zeroes = ") which is not a value. That explains the Nonewhen you print p.
Plus your counting of trailing zero doesn't work, and count all zeroes.
To have your code working, either you should have
num = input('Enter number: ')
ntz = len(num)-len(num.rstrip('0'))
print(f'Your input has {ntz} trailing zeroes')
or
num = input('Enter number: ')
print('Your input has', len(num)-len(num.rstrip('0')),' trailing zeroes')
Here is a working example of the code:
i = input("Enter the number: ")
p = "Trailing zeroes = " + str(i.count("0"))
print(p)
Output:
Enter the number: 1000
Trailing zeroes = 3
Another way to do this:
NB1: the input is a string not a list.
NB2: This will count all zeroes - not just trailing – (By #OldBill)
text= input("Enter the number: ")
print("Trailing zeroes = ", text.count("0"))
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)}")
I am trying to write a program which asks an input of two numbers and then prints the sum, product and average by running it. I wrote a program but it asks an input for 2 numbers everytime i need a sum or average or product. How can I get all 3 at once, just making two inputs once.
sum = int(input("Please enter the first Value: ")) + \
int(input("Please enter another number: "))
print("sum = {}".format(sum))
product = int(input("Please enter the first Value: ")) * \
int(input("Please enter another number: "))
print ("product = {}".format(product))
Use variables to store the input:
first_number = int(input("Please enter the first Value: "))
second_number = int(input("Please enter another number: "))
sum = first_number + second_number
product = first_number * second_number
average = (first_number + second_number) / 2
print('Sum is {}'.format(sum))
print('product is {}'.format(product))
print('average is {}'.format(average))
You need to assign your numbers to variables and then reuse them for the operations.
Example
x = int(input("Please enter the first Value: "))
y = int(input("Please enter another number: "))
print("sum = {}".format(x+y))
print("product = {}".format(x*y))
print("average = {}".format((x+y)/2))
You're going to want to get the numbers first, then do your operation on them. Otherwise you're relying on the user to alway input the same two numbers:
a = int(input("Please enter the first Value: "))
b = int(input("Please enter the second Value: "))
print ("sum = {}".format(a+b))
print ("product = {}".format(a*b))
print ("average = {}".format((a*b)/2))
I am quite new to programming and I am trying to make a leader board for a number guessing game in python 3 where you have the score then the name sorted by the lowest score first:
leaderboard_list = [0,0,0,0,0]
while True:
leaderboard_list.sort()
print("This in the leaderboard",leaderboard_list)
name = ("What is your name?")
while user_num != answer:
user_num = input("Guess a number: ")
if user_num = answer:
print("YAY")
else:
score = score + 1
leaderboard_list.append(score+" "+name)
I have tried many different ways and have figured out that if you get a score of 11, then it will say you are higher in the leader board than someone with a score of 2, which it shouldn't. I have also tried to change the score to an int type however you can't have an int and a string in the same list. How can I get around this?
Dictionary solution
dictionaries are well suited for the task of storing the scores and linking them to the user name. Dictionaries can't be directly sorted. However, there is an easy solution in this other post.
Moreover, in the OP, the name declaration is wrong, as it is not getting any value from the user. With the following code, it works perfectly. A condition for ending the while loop should added as well.
import operator
#Store the names and scores in a dictionary
leaderboard_dict = {}
#Random number
answer = 3
while True:
#Sort the dictionary elements by value
sorted_x = sorted(leaderboard_dict.items(), key=operator.itemgetter(1))
#Rewrite the leaderboard_dict
leaderboard_dict = dict(sorted_x)
print("This in the leaderboard",leaderboard_dict)
name = input("What is your name?")
#initialize score and user_num for avois crashes
user_num = -1
score = 0
while user_num != answer:
user_num = input("Guess a number: ")
if user_num is answer:
print("YAY")
else:
score += 1
leaderboard_dict[name] = score
NumPy array solution
EDIT: In case that you want to store more than one score for each player, I would user NumPy arrays, as they let you do plenty of operations, like ordering indexes by slicing and getting their numeric order, that is the request of the OP. Besides, their syntax is very understandable and Pythonic:
import numpy as np
#Random number
answer = 3
ranking = np.array([])
while True:
name = input("What is your name?")
user_num = -1
score = 1
while user_num != answer:
user_num = input("Guess a number: ")
if user_num is answer:
print("YAY")
else:
score += 1
#The first iteration the array is created
if not len(ranking):
ranking = np.array([name, score])
else:
ranking = np.vstack((ranking, [name,score]))
#Get the index order of the scores
order = np.argsort(ranking[:,1])
#Apply the obtained order to the ranking array
ranking = ranking[order]
And an example of its use:
>> run game.py
What is your name?'Sandra'
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sarah'
Guess a number: 1
Guess a number: 5
Guess a number: 78
Guess a number: 6
Guess a number: 3
YAY
What is your name?'Sandra'
Guess a number: 2
Guess a number: 4
Guess a number: 3
YAY
What is your name?'Paul'
Guess a number: 1
Guess a number: 3
YAY
Being the output:
print ranking
[['Sandra' '1']
['Paul' '2']
['Paul' '2']
['Sandra' '3']
['Sarah' '5']]
The leaderboard itself should store more structured data; use strings only to display the data.
# Store a list of (name, score) tuples
leaderboard = []
while True:
# Print the leaderboard
print("This in the leaderboard")
for name, score in leaderboard:
print("{} {}".format(score, name))
name = ("What is your name?")
score = 0
while user_num != answer:
user_num = input("Guess a number: ")
if user_num == answer:
print("YAY")
else:
score = score + 1
# Store a new score
leaderboard.append((name, score))
# Sort it
leaderboard = sorted(leaderboard, key=lambda x: x[1], reverse=True)
# Optional: discard all but the top 5 scores
leaderboard = leaderboard[:5]
Note that there are better ways to maintain a sorted list than to resort the entire leaderboard after adding a new score to the end, but that's beyond the scope of this answer.
I type in seven digits to be able to work out a gtin-8 product code. But if I type in more than seven digits, the if len statement is meant to recognise that I have typed in more than seven digits, but it doesn't. I tried putting this into an variable but that did not work either... Any help would be appreciated!!! This is my code........
gtin1 = int(input("Enter your first digit... "))
gtin2 = int(input("Enter your second digit... "))
gtin3 = int(input("Enter your third digit... "))
gtin4 = int(input("Enter your fourth digit... "))
gtin5 = int(input("Enter your fifth digit... "))
gtin6 = int(input("Enter your sixth digit... "))
gtin7 = int(input("Enter your seventh digit... "))
gtin_join = (gtin1, gtin2, gtin3, gtin4, gtin5, gtin6, gtin7)
if len(gtin_join) == 7:
What you probably want to do is something like that (notice that I'm using a list here):
ls = []
while len(ls) < 7:
try: #always check the input
num = int(input("Enter your {0} digit:".format(len(ls)+1) ))
ls.append(num)
except:
print("Input couldn't be converted!")
print(ls) #ls now has 7 elements
Your created tuple always has a length of 7 so your if-statement always turns out to be True.
For the difference between list and tuple please see this question here.
Your gtin_join is tuple, and if you want list you should use square braces. You can test type of variables with this example:
gtin1 = int(input("Enter your first digit... "))
gtin2 = int(input("Enter your second digit... "))
gtin3 = int(input("Enter your third digit... "))
gtin4 = int(input("Enter your fourth digit... "))
gtin5 = int(input("Enter your fifth digit... "))
gtin6 = int(input("Enter your sixth digit... "))
gtin7 = int(input("Enter your seventh digit... "))
gtin_join = (gtin1, gtin2, gtin3, gtin4, gtin5, gtin6, gtin7)
print(type(gtin_join))
gtin_join = [gtin1, gtin2, gtin3, gtin4, gtin5, gtin6, gtin7]
print(type(gtin_join))
if len(gtin_join) == 7:
print 7
I would do the following:
gtin_list = []
while len(gtin_list) != 7:
gtin = input("Please enter all 7 digits separated by commas...")
gtin_list = [int(x) for x in gtin.split(",")]