Python: Select Only Parts of an input? - python

Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?

Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True

Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!

My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.

Related

How can I write a string inside of an input?

I'm having a problem of printing a string inside an input. I made a for loop for automatic numbering based on how many elements that the user wants to input.
list = []
n = int(input("How many elements you want to input: "))
for i in range(0, n):
element = int(input(i+1))
if n == element:
print("hello")
break
list.append(element)
For example, I inputted 3 in the number of elements. I want to make my program output be like this:
input
input
input
(input is the user will type once the number is shown)
But my program looks like:
1input
2input
3input
I just want to work up with the design, but I don't know how to do it.
What you need is called string formatting, and you might use .format by replacing
element = int(input(i+1))
using
element = int(input("{}. ".format(i+1)))
or using so-called f-strings (this requires Python 3.6 or newer):
element = int(input(f"{i+1}. "))
If you want to know more, I suggest reading realpython's guide.
Try:
input(str(i+1)+'. ')
This should append a point and a space to your Text. It converts the number of the input to a String, at which you can append another String, e.g. '. '.
You have to edit the input in the loop to something like this:
element = int(input(str(i+1) + ". "))
You are close. Convert i+1 to a string and concatenate a . to it and accept input.
Note: Do not use list as a variable name. It is a Python reserved word.
lst = []
n = int(input("How many elements you want to input: \n"))
for i in range(n):
element = int((input(str(i+1) + '. ')))
if n == element:
print("hello")
break
lst.append(element)
How many elements you want to input:
5
1. 1
2. 6
3. 7
4. 4
5. 6
n = int(input("How many elements you want to input: "))
for i in range(0, n):
print(str(i+1) + ". " + str(n))
This should do.
I used the same code shape as yours, and that way it is easier for you to understand.

How to display an integer many times

I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

Writing a program that accepts a two digit # that breaks it down

I am currently using Python to create a program that accepts user input for a two digit number and will output the numbers on a single line.
For Example:
My program will get a number from the user, lets just use 27
I want my program to be able to print "The first digit is 2" and "The second digit is 7"
I know I will have to use modules (%) but I am new to this and a little confused!
Try this:
val = raw_input("Type your number please: ")
for i, x in enumerate(val, 1):
print "#{0} digit is {1}".format(i, x)
It was not clear from your question whether you are looking to use % for string substitution, or % for remainder.
For completeness, the mathsy way using modulus operator on ints would look like this:
>>> val = None
>>> while val is None:
... try:
... val = int(raw_input("Type your number please: "))
... except ValueError:
... pass
...
Type your number please: potato
Type your number please: 27
>>> print 'The first digit is {}'.format(val // 10)
The first digit is 2
>>> print 'The second digit is {}'.format(val % 10)
The second digit is 7
Think about the two digit number as though it were a string. It is easier to grab each digit this way. Using str() will change the integer to a string. Modulos allow you to place these strings into your text.
Assuming the user inputs 27 into the variable called num, the code is:
print 'The first digit is %s and the second digit is %s' % (str(num)[0], str(num)[1])
Another way of coding Python:
val = raw_input("Type your number please: ")
for i in list(val):
print i
Note: val is read as string. For integer manipulation, use list(str(integer-value)) instead
two_digit_number = input("Type a two digit number: ")
print("The first digit is " + two_digit_number[0] + " The second digit is " +
two_digit_number[1])
You don't need modules to solve this question.

Using random.randint help in python

The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

Categories

Resources