python code - Wants code to accept certain numbers - python-3.x

coins = input("enter x number of numbers separrated by comma's")
while True:
if coins == 10, 20, 50, 100,:
answer = sum(map(int,coins))
print (answer)
break
else:
print ('coins not accepted try again')
Want the program to only accept numbers 10 20 50 and 100 (if numbers valid must add them together otherwise reject numbers) this code rejects all numbers

coins = input("enter x number of numbers separated by commas")
whitelist = set('10 20 50 100'.split())
while True:
if all(coin in whitelist for coin in coins.split(',')):
answer = sum(map(int,coins))
print (answer)
break
else:
print ('coins not accepted try again')
From the in-comment conversation with #adsmith, it seems that OP wants a filter. To that end, this might work better:
coins = input("enter x number of numbers separated by commas")
whitelist = set('10 20 50 100'.split())
answer = sum(int(coin) for coin in coins.split(',') if coin in whitelist)
print answer

You can try sanitizing your input as it's entered instead of cycling through afterwards. Maybe this:
coins = list()
whitelist = {"10","20","50","100"}
print("Enter any number of coins (10,20,50,100), or anything else to exit")
while True:
in_ = input(">> ")
if in_ in whitelist: coins.append(int(in_))
else: break
# coins is now a list of all valid input, terminated with the first invalid input
answer = sum(coins)

Related

Want to get input on same line for variables at different places in Python3. See the below code and text for clarification

I want to take input of how many inputs the user is going to give next and collect those inputs in a single line. For eg. if user enters '3' next he has to give 3 inputs like '4' '5' '6' on the same line.
N = int(input())
result = 0
randomlist = []
for number in range(N):
K = int(input())
for number2 in range(K):
a = int(input())
if number2 != K - 1:#Ignore these on below
result += a - 1
else:
result += a
randomlist.append(result)
result = 0
break
for num in range(N):
b = randomlist[num]
print(b)
Now I want the input for K and a (also looped inputs of a) to be on the same line. I have enclosed the whole code for the program here. Please give me a solution on how to get input in the same line with a space in between instead of hitting enter and giving inputs
Based on what I read from your question, you are trying to request input from the user and the desired format of the input is a series of numbers (both integers and floats) separated by spaces.
I see a couple of ways to accomplish this:
Use a single input statement to request the series of numbers including the count,
Just ask the user for a list of numbers separated by spaces and infer the count.
To perform these operations you can do one of the following:
#Request User to provide a count followed by the numbers
def getInputwithCount():
# Return a list Numbers entered by User
while True:
resp = input("Enter a count followed by a series of numbers: ").split(' ')
if len(resp) != int(resp[0]) + 1:
print("Your Input is incorrect, try again")
else:
break
rslt = []
for v in resp[1:]:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
or for the simpler solution just ask for the numbers as follows:
def getInput():
# Return the list of numbers entered by the user
resp = input("Enter a series of numbers: ").split(' ')
rslt = []
for v in resp:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt

noob horribly stuck on what is most likely an easy question

Flowchart
Trying to create a password generator
Cannot get if statement to work correctly, or know if this is really the right way to approach the problem. I need it to divide each letters number representation by 3 and return a # if it is a whole number.
password = input("password: ")
password = password.lower()
output = []
for character in password:
number = ord(character) - 96
output.append(number)
x = output
if x / 3:
print ("#")
print (output)
I get this error:
TypeError: can only concatenate list (not "int") to list
I don't know what you are trying to do with the divisible by 3. To get you started, here's an example code. See if this helps you get started in the right direction.
password = input('enter password :').lower()
output = []
for c in password:
num = ord(c) - 96
output.append(num)
all_div_by_3 = True
for i in output:
if i%3 != 0: #checks if remainder of i/3 is zero. if zero, then divisible, else not divisible.
all_div_by_3 = False
break
if all_div_by_3: #is same as if all_div_by_3 == True:
print ('all divisible by 3')
else:
print ('all characters are not divisible by 3')
The output from this are as follows:
enter password :cliff
all divisible by 3
enter password :rock
all characters are not divisible by 3
After much reading and research through here it became apparent I needed to use the if, elif, and else functions. below is the completed project.
password = input("password: ")
password = password.lower()
output = []
for character in password:
number = ord(character) - 96
output.append(number)
for i in output:
if(i% 3 == 0) :
print('#', end ="")
elif(i% 5 == 0) :
print('%', end ="")
else:
print(chr(i+98), end="")

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

Mastermind Python Using "ABCDEF"

Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')

Numbers Only, Rounding up, and adding

so I am still learning Python so this should be rather easy to answer for some of you experts...
1) How can you make it so only numbers are accepted as an input?
def check_only_digit():
digits = input("Please input a number ")
if digits in "0123456789":
print("Working")
else:
print("Not working")
check_only_digit()
This will print "Working" if the inputted is a number in 0123456789 but only is this order. What I am asking is there any way to make it in any order?
2) How can I make the users digit round UP to the nearest 10?
def round_up():
users_number = input("Please input a number you want rounded ")
answer = round(int(users_number), -1)
print (answer)
round_up()
3) Is there anyway to add a number onto the end of another number? For example for 1+1, instead of equaling 2, can it equal 11?
I would like to thank you all for your responses in advance.
For Answer 1:
def check_Numbers():
number=input("Enter a number: ")
try:
number=int(number)
print("Working")
except(ValueError):
print("Not Working")
For Answer 2:
def rounding_Off():
userNumber=float(input("Enter a floating point number to round off: "))
roundedOff=round(userNumber,-1)
return roundedOff
For Answer 3:
def addNumbers():
number1=input("Enter one number: ")
number2=input("Enter another one: ")
newNumber=number1+number2
return int(newNumber)
#return newNumber <----- This if you want to get your number in string format.

Resources