Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
As the title says, I have created a program that does the following until the user presses the 'X' key. Which then stops and prints out all values in order. I also would like to mention that I can only use a specific compiler through my university, which registers the program as an error/wrong even though it should be correct.
Edit: Added the Status of the compiler.
My question is, what other alternatives can I use to code a similar program, or any recommendations in general.
The requested input:
1
2
X
The requested output:
result:[1, 2]
average:1.50
min:1.00
max:2.00
list1 = []
asknumber = str(0)
while asknumber != 'X':
asknumber = input("Enter number: ")
if asknumber == 'X':
break
list1.append(int(asknumber))
big_value = max(list1)
min_value = min(list1)
average = sum(list1) / len(list1)
print("result:", sorted(list1))
print("average:", f'{average:.2f}')
print("min:", f'{min_value:.2f}')
print("max:", f'{big_value:.2f}')
Since a computer is grading your work, the error is likely because you have spaces after your colons.
Someone suggested to use the following to resolve that issue:
print("result:", sorted(list1), sep='')
However, since you are already using f strings in your print statement, you might as well use them for all of it.
You also do not need to calculate the min, max, and average until the loop ends—and since you break the loop manually, you can just use while True:.
list1 = []
asknumber = str(0)
while True:
asknumber = input("Enter number: ")
if asknumber == 'X':
break
list1.append(int(asknumber))
big_value = max(list1)
min_value = min(list1)
average = sum(list1) / len(list1)
print(f'result:{sorted(list1)}')
print(f'average:{average:.2f}')
print(f'min:{min_value:.2f}')
print(f'max:{big_value:.2f}')
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Please help me.
I am a noob and the code does not run. The input should be a number which indicates the index where the 0 turns to an 1.
board2 =[0,0,0,0,0,0,0,0,0]
inp = input('Input Number 0-8:')
if inp == int():
a = inp
for i in board2:
board2.replace(i[a],1)
return board2
You can check if the value input is both an int and if it is in range that you described.
Then you can use the index to replace the value in board2 to 1.
Also, the input() function defaults to string.
board2 =[0,0,0,0,0,0,0,0,0]
inp = input('Input Number 0-8:')
if 0 <= int(inp) < len(board2):
board2[int(inp)] = 1
print(board2)
Almost there! you don't really need to use "replace" here; you can just modify the element which resides at the index provided directly. The only criteria you would need to consider is that the number is greater than zero AND within the range of the "board2" list provided.
board2 =[0,0,0,0,0,0,0,0,0]
inp = input('Input Number 0-8:')
if (0 < int(inp) < len(board2)):
board2[int(inp)] = 1
print(*board2)
This code snippet should solve your question:
board2 = [0,0,0,0,0,0,0,0,0]
index = int(input('Input Number 0-8:'))
if index in range(len(board2)):
board2[index] = 1
print(board2)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Write a function to enter from the keyboard a series of numbers between 1 and 20 and save them in a list.In case of entering an out-of-range value the program will display an error message and ask for a new number.To finish loading you must enter -1.La function does not receive any parameters, and returns the loaded list (or empty, if the user did not enter anything) as the return value.
def funcion():
list = []
num = 0
while num != -1:
num = int(input("Enter a number between 1 and 20: "))
while num > 20 :
num = int(input("Please re-enter the number: "))
list.append(num)
return lista
result = funcion()
print(result)
My question is how I do not show the -1 in the list
It's easier to have an infinite loop and break out of it when the user enters -1:
def funcion():
lista = []
num = 0
while True:
num = int(input("Enter a number between 1 and 20: "))
while num > 20:
num = int(input("Please re-enter the number: "))
if num == -1:
break
else:
lista.append(num)
return lista
result = funcion()
print(result)
The trick is saving the list except the last item like this:
return lista[:-1]
you can read more here:
https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
The minimal change to your code would just use the list slicing syntax to return all elements of lista apart from the last one:
return lista[:-1]
See [1] below. This is a pythonic way of writing the slightly more intuitive, but more verbose statement:
return lista[:len(lista)-1]
... which in turn is short for the even longer:
return lista[0:len(lista)-1]
You seem to be new to python. I really recommend looking up "list slicing" and "list comprehensions": if you already know a programming language that doesn't have these, once you learn these, you'll wonder how you ever did without them!
[1] http://knowledgehills.com/python/negative-indexing-slicing-stepping-comparing-lists.htm
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to get this input to become a function to use later on when buying/selling shares in a program. Is this possible? For example, later on I might do:
if shareOne >= 50 //where >= is shareQuestionBuy or shareQuestionSell
CODE BELOW
#Input of share code
shareCode = str(input("What is your share code? "))
if isValid(shareCode):
print("\nShare code", str(shareCode), "is valid\n")
else:
print("\nERROR! Share code", str(shareCode), " invalid. Share code too short/long or contains alpha/unicode characters.\n Program will now terminate\n")
quit()
shareQuestionBuy = bool(input("Are shares bought by" + str(shareCode) + "bought when they are below the limit price (True) or greater than/equal to the limit price (False)? (True/False only): "))
if shareQuestionBuy == True:
print("Shares will now only be bought if they are below the limit price")
shareQuestionBuy = <
elif shareQuestionBuy == False:
print("Shares will now only be bought if they are greater than/equal to the limit price")
shareQuestionBuy = <=
operator
3>> import operator
3>> foo = operator.gt
3>> foo(3, 2)
True
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to create a variable inside an if statement but it won't allow it. Is there any other way to do what I'm trying?
print ('Type numbers 1 or 2')
c = int(input())
if c == 1:
answer = (90) #so the variable "answer" will be set to '90' if the user types "1"
if c == 2:
answer = (50)
print (answer)
The code will run in the expected way if either 1 or 2 are entered as input. But if user inputs another number, you will get an Exception:
NameError: name 'answer' is not defined
To avoid this, you could declare the variable answer before the if statements:
answer = 0 # or a reasonable number
if c == 1:
answer = 90
# ...
Note: The () in answer = (90) are not necessary since it's a single number.
You need to allow the possibility that your input() might be out of your preconceived options:
c = int(input("Type no. 1 or 2: "))
if c==1:
answer=90
print(answer)
elif c==2:
answer =50
print(answer)
else:
print("you input neither 1 nor 2")
Here's a more compact solution using assert:
c = int(input("Type no. 1 or 2: "))
assert c in [1,2], "You input neither 1 nor 2."
answer = 90 if c == 1 else 50
print(answer)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i am writing a program about coin flips i want the user to enter number and for the program to flip a coin that many times.
once the user gives number the program stops
this is what i have
import random
flips = 0
heads=0
tails=0
numFlips = raw_input("Flips ")
while flips < numFlips:
flips += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
heads+=1
if coin == 2:
print ('Tails')
tails+=1
total = flips
print(total)
print tails
print heads
numFlips is a str. You have to convert it to an int first.
numFlips = int(raw_input("Flips "))
Otherwise, your check flips < numFlips will not work, since all ints are 'less than' any string.
(Also, you want to add some error-handling for the case the user enters something other than an integer)
On line
numFlips = raw_input("Flips ")
raw_input() reads a string : http://docs.python.org/2/library/functions.html#raw_input
Convert it to integer by doing int(raw_input("Flips "))
You can also use input() evaluates the string to a python expression, which in this case would evaluate to an int.
EDIT: As pointed out by #bruno desthuilliers, it is unsafe to use input() and should rather just convert the raw_input() to int.