New string every time a loop runs - python

Looking to prove a sibling wrong about how long it can take a computer to guess a specific string by using Brute Force even with the correct number of characters put in. I can get the code to run but I cannot figure out how to get it to print a new string every time it runs. I'm sure I'm over looking something simple. Below are a couple examples of the code I've tried.
import string
import random
random=''.join([random.choice(string.ascii_letters+string.digits) for n in xrange(5)])
while True:
if random != "Steve":
print(random)
if random == "Steve":
print("Found")
This will continually print the same string over and over. I've also tried this without the while statement just the if and it doesn't seem to work.
I know enough that once random picks those 5 randoms characters it won't change until something makes it change but like I said I'm not sure how to do that. I've tried moving random to different places but doesn't work I just get different error messages.
Can someone help me out.

random=''.join([random.choice(string.ascii_letters+string.digits) for n in xrange(5)])
This doesn't create a new random string each time. At this point random is just a randomly generated string that doesn't change while your while loop runs. Referencing random doesn't create a new string, but rather just gets the first string your generated, since random is just a string in your memory not a function.
Move the random string creation into a function:
import string
from random import choice
def make_random():
return ''.join([choice(string.ascii_letters+string.digits) for n in xrange(5)])
Then run the loop:
while True:
random = make_random()
if random != "Steve":
print(random)
if random == "Steve":
print("Found")
EDIT:
Switched import random to from random import choice because random (the variable) was overwriting random (the library) and throwing an attribute error when you try to call random.choice.

You have two problems here. As #Primusa pointed out, your random generation should be moved inside your loop otherwise it'll only run once. However, your other problem is that you're importing random and you're also setting a variable to random. This is where your NameError is coming from. You've defined random to be a string, which works on the first iteration of your loop. However, on the second iteration, random won't have a function called choice declared for it because it's a string at that point. Rename your random variable or import the random package under an alias, like this:
import random as rnd

Related

How could i know the random number generated in python?

Here is my code. I am just starting to learn Python.
I am trying to generate a random number and guess it. If the answer is 7, then my program will print "lucky". If not, then "unlucky". I try to run my simple code many times. Every time I get "unlucky". Is there anybody who knows whether the problem is in my algorithm or somewhere else. BTW, I really want to know how could I know specifically know what is the number randomly generated in python? I just wonder if the same number, that is being generated every time, is the same one or not.
from random import randint
z = input("What's the max number you want me to guess?")
choice = f"randint(1,{z})"
if choice == 7:
print("lucky")
else:
print("unlucky")
The reason you're getting unlucky every time has nothing to do with randomness.
Try running your code in the debugger, or adding a print(choice), to what what you're getting.
If you enter, say, 10, then choice is the string "randint(1,'10')". That string is never going to be equal to the number 7.
To make this work, you need to change two things:
Actually call randint, instead of making a string that looks like the source code to call it.
Call it on a number, like 10, not a string, like '10'.
So:
choice = randint(1, int(z))
Once you fix this, the random numbers will be random. Technically, they're created by a PRNG (pseudo random number generator), a fancy algorithm that takes a bunch of state information and spits out a sequence of numbers that look random, but are actually predictable from that state. But, as explained under seed, by default, Python seeds that generator with os.urrandom (which, on most platforms, is another PRNG, but is itself seeded by whatever actual random data is available).
If you want the sequence to be repeatable, for testing, you can call the seed function manually. For example, this program:
from random import randint, seed
seed(42)
z = input("What's the max number you want me to guess?")
choice = randint(1, int(z))
print(choice)
… will give you 2 every time you ask for a random number between 1 and 10.
If you want to check whether the same number is being guessed by random, just use print, to check it. Here:
from random import *
z = int(input("What's the max number you want me to guess?"))
choice = randint(1,z)
print("The number that I guessed:",choice)
if choice == z:
print("I gussed it! I got lucky.")
else:
print("I couldn't guess it, I got unlucky.")

Why Python random is generating the same numbers?

I wrote this code for my homework:
import random
score=[]
random.seed(1)
for i in range(0,100):
score.append(random.randrange(0,21))
for k in range(20, -1, -1):
print("Who get %2d score in test? : "%(k), end='')
while score.count(k)!=0:
j = score.index(k)
print("%3s" % (j), end=" ")
score.remove(k)
score.insert(j,25)
print("\n")
I ran it on my computer many times and the results were the same. Ironically, in other computers, the results are different from my computer, but also also getting repeated at each execution.
What's wrong with my code?
random.seed(n) starts the random number generator off from the same point each time the program is run.
That is you get the same sequence of random numbers. It is like taking a video of a dice being thrown and then playing it back each time - the numbers are random (pseudo random to be accurate) but you are playing back the sequence.
This is useful for testing, for example: you can run different versions of your program with the same random numbers, so you are sure differences in your results are only due to the program, not to chance.
Take random.seed out and you will get a sequence that starts at a random location. (On most computers, if you don't specify a seed, the clock time the program started is implicitely used as seed.)
When you write
random.seed(1)
You are saying to always use the same sequence of randomly generated numbers, therefore you always have the same results.
It happens when I run it on my computer too.
Simply remove the line and you should have different randomly generated numbers every time.
See this answer for an explanation of the seed.
And the python documentation for the random library

Random Evens function

I'm fairly new to coding, picking it up as a hobby, because its so far, fun, engaging, and challenging. Started out learning Python.
Just for the heck of it, I'm trying to write a function that will generate random integers, only print the even integers, and stop when it finally prints the number 28 (picked it at random.)
I've tried everything I could think of to get the function to loop, but the only thing I've been able to do successfully is just print out a single random even number once before the function stops.
Is there a way to have a function iterate through randint generated numbers between a user defined range, e.g.(0,x), and then apply if/elif/else's to the number(s) generated?
I've probably tried rewriting that same function 30-40 times, but I either get a single even number, a myriad of syntax errors, or some blue script that says "random.randint object at- and then a bunch of numbers.."???
Perhaps I just need to keep delving deeper into tutorials to find the answer, but this seemed like a more productive option. Perhaps there's something I'm not thinking of, or perhaps the concepts I need to employ I just haven't learned yet. Any advice/tips/actual lines of code GREATLY APPRECIATED!
Thanks in advance
Mike
Turns out, I was using the for loop incorrectly, and placing the num = randint(0,x) in the wrong place(wrong line). I've included the final function:
from random import randint
def random_even(x):
for i in range(x):
num = randint(0,x)
if num==28:
print(num,"\n DONE")
break
elif num%2==0:
print(num)

How to use the output of randint in an if statement (Python)

I'm learning Python (3.6.3) and making a silly (and very linear) chatbot to get started. At one point the chatbot asks you to guess its age, I used randint to generate a number between 1-1000 and want to use the outputted random integer in an if statement (so the chat bot is either happy or upset by your answer, depending on whether you thought it was older than it really is).
The user's input is a var called guess and I assumed (as I cannot find a similar example online) that I could just reference guess and the randint in an if statement to print the desired output, but I get an error advising radint is not defined when I run the prog -
print('guess how old I am')
guess = input()
import random
for x in range(1):
time.sleep(0.4)
print ('nope, I\'m ' + (str(random.randint(1,1000))) + ' actually')
time.sleep(0.88)
if randint <= guess
print('(so rude...)')
else:
print('aw thanks')
Apologies if my StackExchange syntax is broken too, any help appreciated, thanks
- you need to define your randint variable
- import time
- fix: you left out colon after "if randint <= guess"
- you need to make your input guess an integer in order to perform comparison
print('guess how old I am')
guess = int(input())
import random
import time
randint = random.randint(1,1000)
for x in range(1):
time.sleep(0.4)
print ('nope, I\'m %s actually' % randint)
time.sleep(0.88)
if randint <= guess:
print('(so rude...)')
else:
print('aw thanks')
here is a corrected version of your chatbot:
import time
import random
guess = input('guess how old I am: ')
random_guess = random.randint(1,1000)
time.sleep(0.4)
print ('nope, I\'m {} actually'.format(random_guess))
time.sleep(0.88)
if random_guess <= guess:
print('(so rude...)')
else:
print('aw thanks')
I'm just going to note down the things that were wrong and some good practices so that you can follow it since you are learning python (I just learnt it as well):
In the if statement you were comparing randint <= guess which is not possible because randint is not saved as variable anywhere. The 1st time you used random.randint(1, 1000) it was statically added only to be used in the print statement. So what I did here is save the random.randint(1,1000) (as you can see randint is a method inside the random module of python) into a variable called random_guess for comparison. It returns a random integer as stated in random.randint.
Coming to the print statement since your random_guess will be of
type int, using formatted string will be a nice and pretty option.
Always use import statement at the top of the file so that it'll be
a one stop place for altering imports.
Take a look at this input() method as well, I have passed in a
string which automatically prints out the string passed instead of a
separate print statement
I also removed the for loop since it was looping once anyways (I
know you need to call it many times, anywho..)
Edit: Oh, and you missed a colon in the if statement!
I hope this cleared your doubts.

How to generate a new random number in python without running the program again or add up new variable?

For so far, I've learnt how to use randrange() and choice.random() to generate random number. But there is something confusing me, that everytime I can only generate a fixed random number, like:
import random
x = [1,2,3,4]
chance = random.choice(x)
while chance < 5:
print chance
At this example, the random number generate by chance is fixed. If I want to generate a new random number, I have to run this program again or to add up a new variable.
is there a method, that I can build something which I use it to generate new random numbers without to run the program again or add up a new variable?
Thank you very much!
while True:
chance = random.choice(x)
print chance
The line chance = random.choice(x) evaluates the expression random.choice(x) once, and assigns the result to the variable chance. After that, in your code you're just looking at chance repeatedly. That won't evaluate the expression random.choice(x) again.
is there a method, that I can build something which I use it to generate new random numbers without to run the program again or add up a new variable?
Well, yes, you could generate a lazy infinite iterator of random values and fetch them one at a time. But you don't want to do that.*
The key to avoiding having to "add up a new variable" each time is to just reuse the same variable:
chance = random.choice(x)
while chance < 5:
print chance
chance = random.choice(x)
* In case you're wondering: for chance in takewhile(lambda i: i<5, (random.choice(x) for _ in count()):. But notice that it's still doing the "reusing chance over and over, because that's the part that actually solves your problem.

Categories