python program will not continue [closed] - python

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.

Related

Program calculating sum, min, max values of user input [closed]

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}')

How to replace items in a list? [closed]

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)

How do I compare the first and second items of a list in python? [closed]

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
So I am trying to compare the first item in a list to the second. I want to find out if the first item is equal to, less than, or greater than the second item.Here is what I have so far. I'm stuck at this part :/
numbers = []
for i in range(0,3):
num = input("Please enter an integer: ")
numbers.append(num)
you have this code that will ask the user for 3 integers, and then you are adding them to the list numbers. You need first to convert then to integers by adding int(input(..))
numbers = []
for i in range(0,3):
num = int(input("Please enter an integer: "))
numbers.append(num)
Now we can start comparing the first and the second number of the list:
if numbers[0] > numbers[1]:
print("the first number is bigger than the second")
elif numbers[1] > numbers[0]:
print("the second number is bigger than the first")
else:
print("the first and the second numbers are equal")

As I do so as not to show the -1 in the Python list [closed]

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

Disregarding bad input within 'for' statement in Python? [closed]

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 write a program that loops a prompt 10 times or until the correct input is entered. Wrong input entered should not count towards the 10 tries to enter the correct input.
I am not sure if I should keep the prompt within the for statement or not. Here is what I have so far regarding the bad input issue:
for i in range(10):
value=input("Enter a numerical value: ")
if value.isdigit()==False:
print("Error.")
A better construct to use would be a while loop.
Instead of looping for 10 times, you could loop until you have a valid input, i.e.
while True:
value = input("Enter a number:")
if value.isdigit() == False:
print "Error"
else:
break
However, that said, if you only want to loop for a maximum of 10 times, the construct that you have is perfectly fine - you just need a way of exiting the loop when a valid number is entered,
for i in range(10):
value=input("Enter a numerical value: ")
if value.isdigit()==False:
print("Error.")
else:#is a digit
break
After seeing your comment, I would still advise using while loop, just with an extra variable (and a few changes made from DarinDouglass's comment
times_correct = 0
while times_corrent < 10:
value = input("Enter a number:")
if value.isdigit() == False:
print "Error"
else:
times_corrent += 1
You need to break the loop when you get the correct input:
for i in range(10):
value=input("Enter a numerical value: ")
if not value.isdigit(): # PEP8 says to use `not` instead of `== False`
print("Error.")
else:
break # If we get here, the input was good. So, break the loop.
See a demonstration below:
>>> for i in range(10):
... value=input("Enter a numerical value: ")
... if not value.isdigit():
... print("Error.")
... else:
... break
...
Enter a numerical value: a
Error.
Enter a numerical value: b
Error.
Enter a numerical value: 12
>>>

Categories

Resources