I am teaching myself python. I was thinking of small programs, and came up with an idea to do a keno number generator. For any who don't know, you can pick 4-12 numbers, ranged 1-80, to match. So the first is part asks how many numbers, the second generates them. I came up with
x = raw_input('How many numbers do you want to play?')
for i in x:
random.randrange(1,81)
print i
Which doesn't work, it prints x. So I am wondering the best way to do this. Make a random.randrange function? And how do i call it x times based on user input.
As always, thank you in advance for the help
This should do what you want:
x = raw_input('How many numbers do you want to play?')
for i in xrange(int(x)):
print random.randrange(1,81)
In Python indentation matters. It is the way it knows when you're in a specific block of code. So basically we use the xrange function to create a range to loop through (we call int on x because it expects an integer while raw_input returns a string). We then print the randrange return value inside the for block.
Related
I found this Python 3 code template in a coding website. The site claims that t will be a string of n integers.
n = int(input())
for i in input().split():
t = int(i)
I understand input.split() is for taking multiple inputs, like in a, b = input.split() will raise a ValueError until I give two inputs like 1 2.
What I don't understand is how it is implemented in a for-loop. Like, what value does i take on? And how Python is supposed to know that t will have n integers?
NOTE: I tried printing t. The result is as same as t = int(input()). I am not getting this. Please help.
I found this Python 3 code template in a coding website. The site claims that t will be a string of n integers.
If this is really the case, I recommend you to contact the owner of the website, because this statement is wrong, already by definition : A string is the contrary of an integer in Python. For an explanation of the code see below.
n = int(input())
for i in input().split():
t = int(i)
This code lets you first input a number n, which is never used.
Then, it lets you input a string containing numbers separated by spaces, splits the string at spaces and loops over the resulting list. Each item is converted to int, and assigned to a variable t, which, in the end, get's garbage collected because it is never used.
So for a while now i've been trying to complete this exercise. The idea is to store inputs of numbers in a list, until the word 'done' is entered. Then print the minimal and maximal values of integers. And it seems i can't get it to work however many solutions i've tried, and it raised some stupid questions i would love to get answers for. So here's my best try i guess:
while True:
mylist=[]
mylist=[mylist.append(input('Please enter a number'))]
if 'done' in mylist:
print(min(mylist[:len(mylist)-4]))
print(max(mylist[:len(mylist)-4]))
break
And unsurprisingly it doesn't work, and i've no idea why, and i've exhausted all of my ideas to get it to work. But i have i stupid question. If i declare a list in a loop like i did it here, will the declaration make it empty again while it loops a second time? If it does, then how do i declare list and use it in a loop when Python doesn't want me to use global variables? Also i might have used 'break' here incorrectly, but it doesn't really matter, since the code doesn't go that far, it's just reading inputs.
store inputs of numbers in a list, until the word 'done' is entered.
1) Create an empty list before the loop. Otherwise, you are clearing the list every iteration.
2) Stop the loop when you see "done" (use break). Don't append to the list unless you have some other input. It would also help to add try-except around the int(x)
numbers = []
while True:
x = input("Enter a number: ")
if x == "done":
break
numbers.append(int(x))
Then print the minimal and maximal values of integers
Outside the loop (or before the break), you can print the values. You don't need any list slicing to check mins and maxes
print("Min", min(numbers))
print("Max", max(numbers))
If i declare a list in a loop like i did it here, will the declaration make it empty again while it loops a second time?
Yes. The line mylist=[] creates a new empty list, and makes mylist into a name for that new empty list (forgetting whatever it used to be a name for), every time it gets executed.
If it does, then how do i declare list and use it in a loop…
Just do it outside the loop:
mylist=[]
while True:
… when Python doesn't want me to use global variables?
The distinction is between local variables, defined inside a function body, and global variables, defined outside of any function body. Since you haven't written any function definitions at all, all of your variables are global variables anyway.
And, if you moved all of this inside a function, all of your variables would be local variables, whether they're inside the loop or not.
Anyway, this still isn't going to fix your code, because of a number of other problems:
mylist.append(…) modifies the list in-place, and returns None.
mylist=[mylist.append(…)] throws away the existing list and replaces it with the useless list [None].
mylist is (supposed to be) a list of strings, not a string, so mylist[:len(mylist)-4] isn't throwing away the final 4-character string, it's throwing away the last 4 strings, whatever they are.
min on a list of strings will compare them as strings, in dictionary order, not as numbers. You have to convert them to numbers if you want to compare them as numbers. But you can do this on the fly, using key=float. (See the Sorting HOWTO for more.)
While we're at it, you can simplify a few things:
x[:len(x)-4] does the same thing as x[:-4].
But, instead of adding the new string to the list and then checking whether 'done' is anywhere in the list, and then looping over the whole list except for the done, why not just check the new string?
So, here's some code that does what you want:
mylist = []
while True:
number = input('Please enter a number')
if number == 'done':
print(min(mylist, key=float))
print(max(mylist, key=float))
break
else:
mylist.append(number)
I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))
I'm new to Python and have been working through some tutorials to try to get to grips with different aspects of programming.
I'm stuck on an exercise that is most likely very simple however I am unable to find the solution.
How do I create a program that reads one line of input and prints out the same line two times?
For example if the input was Echo it would print:
Echo
Echo
Any help with this would be hugely appreciated. I think I'm making a simple logic error but don't yet have the skills in place to recognise what it is.
The other answers seem logical enough, but what if you wanted to print it let's say a 1000 times or a million times? Are you really going to be typing print(variable) a million types? Here is a faster way:
j=input("Enter anything.")
for i in range(2):
print(j)
Here, I can change the value of range to whatever I want, and J will be printed that many times.
What happens here, is that the variable i loops upwards (an increment) to the number 2, so to explain it to a beginner, i travels t=from number to number. Where I put print(j) for every number i loops through until it gets to 2, J will be printed.
It sounds like you've been doing the input and output in one go:
print(input())
That works for doing a single echo of the input, but makes it a bit harder to repeat the same thing twice. An easy workaround would be to save the inputted text to a variable, which you can print twice:
text = input()
print(text)
print(text)
If you needed to do the input and doubled output with a single statement, you could use string formatting to duplicate the text with a newline in the middle:
print("{0}\n{0}".format(input()))
way complex right?(:D)
inp = input("Input something would ya? ")
print(inp)
print(inp)
How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters?
t=int(input())
while t>0:
n=int(input())
s=sum(1/(2.0*i+1) for i in range(n))
print "%.15f"%s
t-=1
You're welcome
for t in range(int(input()), 0, -1): print '%.15f' % sum(1/(2.0*i+1) for i in range(int(input())))
EDIT (explanation):
Firstly, instead of a while loop you can use a for loop in a range. The last argument in the for loop is a -1 to subtract 1 every time instead of the default of plus 1 every time.
If there is only one statement in an if statement, or loop, you can keep the one statement in the same line without going to the next line.
Instead of creating the variable of n, you can simply plug it in since it's only being used once. Same goes for s.
for _ in range(input()):print"%.15f"%sum(1/(2.0*i+1)for i in range(input()))
exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()
I know I am too late for answering this question.but above code gives same result.
It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4