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.
Related
I'm trying to get an if statement to recognize a randomly generated number but I don't know what is going wrong, it just ends the program as soon as i hit start and does not print anything, so far I have this.
import random
random.randint(1,3)
if random.randint == ('1'):
print('message')
I have tried changing the random.randint(1,3) into a variable by making it "a == ('random.randint(1,3)" but that did not work either. Does anyone know whats going wrong with it?
P.S: Sorry if the question is asked badly, I don't use this site much.
There are several problem with your code.
randint() creates a number like 1. It will never make a string like '1'. Additionally random.randint is a function. random.randint == ('1') will never be true, because a function is never never be equal to a number or a string. You want to compare the result of calling the function to an integer.
import random
num = random.randint(1,3)
if num == 1:
print('message')
random.randint() is a function - therefore, you have to save its output in a variable, or else the value will be lost. For instance:
import random
rand_num = random.randint(1,3)
if rand_num == 1:
print('message')
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
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.")
This is I'm sure a fairly rudimentary questions involving Python, but I've only recently started using the program. Here is the challenge:
"Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it's run."
My approach was to assign five distinct variables their own individual fortunes:
fortune_1 = str("Good things come to those who wait.")
fortune_2 = str("Patience is a virtue.")
fortune_3 = str("The early bird gets the worm.")
fortune_4 = str("A wise man once said, everything in its own time and place.")
fortune_5 = str("Fortune cookies rarely share fortunes.")
What I am not clear on is how to generate the fortunes at random. Is there a way to utilize the random. module to pick one of the five predetermined fortunes uniquely each time? For example, could I set those five fortunes as numbers and then say something like:
user_fortune = random.randfortune(1,5)
? I hope this makes sense. As I am new to Python and posting in this forum it may take me some time to communicate more clearly.
Thanks!
My first instinct was to tell you to put your fortunes into a sequence of some kind (e.g., list, tuple). Then, you just need to pick a random element. I did the following at the Python prompt:
>>> import random
>>> help(random)
Help on module random:
NAME
random - Random variable generators.
FILE
/usr/lib/python2.7/random.py
MODULE DOCS
http://docs.python.org/library/random
DESCRIPTION
integers
--------
uniform within range
sequences
---------
**pick random element**
pick random sample
generate random permutation
distributions on the real line:
Aha! "pick random element" sounds good. So, I keep scrolling:
| **choice**(self, seq)
| Choose a random element from a non-empty sequence.
|
Aha again! I suppose I should have just known this, but it's good to know how to look this stuff up when you need it.
Possible solution (Python 2.7):
import random
fortunes = ["Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."]
print random.choice(fortunes)
You can add the fortunes to a list and select a random item from the list using choice:
import random
fortunes = [fortune_1, fortune_2, fortune_3, fortune_4, fortune_5]
print random.choice(fortunes)
Thank you very much!
I also noticed that I could try the following:
import random
fortune = random.randint(1,5)
if fortune == 1:
print("Good things come to those who wait.")
elif fortune == 2:
print("Patience is a virtue.")
elif fortune == 3:
print("The early bird gets the worm.")
elif fortune == 4:
print("A wise man once said, everything in its own time and place.")
elif fortune == 5:
print("Fortune cookies rarely share fortunes.")
imort random
fortune_cookie = random.choice([""Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."])
print(fortune_cookie)
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.