This question already has answers here:
Random string generation with upper case letters and digits
(36 answers)
Closed 5 years ago.
I just want to ask that like taking random number from: Random.randint(a, b)
I just want to ask that how to take random string just like randint but this time with random string. Is there anyway?
#This program will play a little game
import random
a = ''
b = ''
c = ''
d = ''
e = ''
f = ''
print('Hi. Please enter your name in letters')
name = str(input())
print('Hi ' + name + '. I am going to play a little game. In this game you have to guess a specific name i am thinking right now.')
print('But do not worry. I am going to let you to enter 6 names and i will choose one of them.')
print('After that you have to answer the correct name that i am thinking right now')
print('Please enter the first name in letters')
name1 = str(input())
print('Please enter the second name in letters')
name2 = str(input())
print('Please enter the third name in letters')
name3 = str(input())
print('Please enter the fourth name in letters')
name4 = str(input())
print('Please enter the fifth name in letters')
name5 = str(input())
print('Please enter the sixth name in letters')
name6 = str(input())
name1 = a
name2 = b
name3 = c
name4 = d
name5 = e
name6 = f
print('Alright ' + name + ' . Thank you for entering the names.')
secretname = random.randint(a, f)
for i in range(2):
print('Now enter the name that i am thinking of.')
ans = str(input())
if ans != secretname:
print('Wrong. Guess another name')
if ans == secretname:
print('Good job ' + name)
else:
print('Wrong. The name i was thinking of was ' + secretname)
This is a little game which request from you to enter 6 names and then the game will guess a number between those 6 numbers you have entered but it always gaves me an error. want to do it with random string.
My Working Version
import random
print('Hi. Please enter your name in letters')
yourname = str(input())
print('Hi ' + yourname + '. I am going to play a little game. In this game you have to guess a specific name i am thinking right now.\nBut do not worry. I am going to let you to enter 6 names and i will choose one of them.\nAfter that you have to answer the correct name that i am thinking right now\nPlease enter the first name in letters')
name = ["", "", "", "", "", ""]
number = ["first", "second", "third", "fourth", "fifth", "sixth"]
def insert(n):
temp = name.copy()
name[n] = str(input("name " + str(n + 1) + ": "))
if name[n] in temp:
print("[error]: ---> This name exists yet, try again")
print(">>>", end='')
insert(n)
for n in range(6):
insert(n)
print('Please enter the ' + number[n] + ' name in letters')
print('Alright ' + yourname + ' . Thank you for entering the names.')
secretname = name[random.randint(0, 6)]
print("Soluzion: ", secretname)
print("-" * 10)
for i in range(2):
print('Now enter the name that i am thinking of.')
ans = str(input())
if ans != secretname:
print('Wrong. Guess another name')
if ans == secretname:
print('Good job ' + yourname)
else:
print('Wrong. The name i was thinking of was ' + secretname)
Output
Hi. Please enter your name in letters Gio Hi Gio. I am going to play a
little game. In this game you have to guess a specific name i am
thinking right now. But do not worry. I am going to let you to enter 6
names and i will choose one of them. After that you have to answer the
correct name that i am thinking right now Please enter the first name
in letters
name 0: Giovanni
Please enter the first name in letters
name 1: Marta
Please enter the second name in letters
name 2: Giovanni
[error]: ---> This name exists yet, try again
>>>name 2: Giovanni
[error]: ---> This name exists yet, try again
>>>name 2: Carlo
Please enter the third name in letters
name 3: Mimmo Please enter the fourth name in letters
name 4: June
Please enter the fifth name in letters
name 5: Caterina Please enter the sixth name in letters
Alright Gio . Thank you for entering the names.
Solution: Mimmo
----------
Now enter the name that i am thinking of.
M
Wrong. Guess another name Now enter the name that i am thinking of.
Mimmo
Good job Gio
import string
import random
def random_string(length):
return ''.join(random.choice(string.ascii_letters) for m in xrange(length))
print random_string(10)
print random_string(5)
Output:
'oJyPiEbhka'
'XXwuA'
You can do it using random.randint :
my_string = "abcdefghijklmnopqrstuvwxyz"
index = random.randint(0,25)
letter = my_string[index]
You just have to loop over that to build strings from letters
Hello M. Husnain,
Chr() Function
chr(i)
Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.
Solution
Try this below code,
#This program will play a little game
import random
a = ''
b = ''
c = ''
d = ''
e = ''
f = ''
print('Hi. Please enter your name in letters')
name = raw_input()
print('Hi ' + name + '. I am going to play a little game. In this game you have to guess a specific name i am thinking right now.')
print('But do not worry. I am going to let you to enter 6 names and i will choose one of them.')
print('After that you have to answer the correct name that i am thinking right now')
print('Please enter the first name in letters')
name1 = raw_input()
print('Please enter the second name in letters')
name2 = raw_input()
print('Please enter the third name in letters')
name3 = raw_input()
print('Please enter the fourth name in letters')
name4 = raw_input()
print('Please enter the fifth name in letters')
name5 = raw_input()
print('Please enter the sixth name in letters')
name6 = raw_input()
print('Alright ' + name + ' . Thank you for entering the names.')
lists1 = [name1,name2,name3,name4,name5,name6]
secretname = lists1[random.randint(0,len(lists1))]
for i in range(2):
print('Now enter the name that i am thinking of.')
ans = raw_input()
if ans != secretname:
print('Wrong. Guess another name')
if ans == secretname:
print('Good job ' + name)
else:
print('Wrong. The name i was thinking of was ' + secretname)
I hope my answer is helpful.
If any query so comment please.
try this,
import string
alpha = string.ascii_uppercase
num = string.digits
''.join(random.choice(alpha + num) for _ in range(5)) #number you want
Instead of saving the names into different variables I'd propose a list containing the names entered. It could look something like this:
name_list = []
print('Please enter the first name in letters')
name_list.append(input())
print('Please enter the second name in letters')
name_list.append(input())
...
You can then randomly select a list item using random.choice e.g.
import random
secretname = random.choice(name_list)
Update:
For the specific case you described, you can simply create a list of characters containing all of the characters you allow. then you can use this, to create a word of length X (replace with actual length:
base_chars = [ 'a', 'b', 'c', '1', '2', '3' ]
word_length = 10 #change this to the desired word length
[random.choice(base_chars) for _ in range(word_length)]
Original:
Random string - define your characters
You should first decide what kind of characters you want to use.
For example, if you want to use ASCII chars from 0 to 127 or maybe just a-z and A-Z. Also consider digits, space etc. So you should first decide the set of characters you want to select randomly from.
Selecting a character randomly
If you would like to use 0 to 127 range in the ASCII table, you can use this:
char = chr(random.randint(0, 127))
Generating a random word
Now, to create a word, you should first decide the size of it. This can also be randomize. For example, we will randomly choose a size of a word (with limited range):
rand_str = ""
for _ in range(10):
rand_str += chr(random.randint(0, 127))
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?
I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().
You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.
You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.
You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True
So I just started learning a few basics with Python. Since I am a pretty practical person, I enjoy doing it with the book "Automate the boring stuff with Python".
No there is a chapter introducing lists in python and their advantages.
To be practical one should write a code which asks the user to enter cat names, which then will be added to the list. If no cat name is added anymore, all the cat names should be displayed.
Until now, fair enough. So I thought I should give it a try and go a small step further and extend the functionality by adding the ages of the cats. The desired result would be that the user is asked for the name input, then the age input, the name input again and the age input again and so on. If the user doesn´t put in a name again, it should list the cats with the respective ages.
I created a second list and also the second input and everything kinda works but I just dont know how to combine the both lists or rather the values.
It just gives me the two names first and then the two ages.
Is anyone happy to help me with this beginner problem?
Thanks in advance
catNames = []
catAges = []
while True:
print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter
nothing to stop.)")
name = input()
while name !="":
print("Enter the age of cat ")
age = input()
break
if name == "":
print("The cat names and ages are: ")
for name in catNames:
print(" " + name)
for age in catAges:
print(" " + age)
break
catNames = catNames + [name]
catAges = catAges + [age]
I think you're looking for zip:
catNames = ['Fluffy', 'Whiskers', 'Bob']
catAges = [5, 18, 2]
catZip = zip(catNames, catAges)
print(list(catZip))
Out:
[('Fluffy', 5), ('Whiskers', 18), ('Bob', 2)]
In general you would use dictionaries for this kind of task.
But if you were to use lists for your problem, it could be implemented like this:
catNames = []
catAges = []
while True:
print("Enter the name of Cat " + str(len(catNames) + 1) + "(Or enter nothing to stop.)")
name = input()
while name !="":
print("Enter the age of cat ")
age = input()
break
if name == "":
print("The cat names and ages are: ")
for i in range(len(catNames)):
print("Cat number",i, "has the name", catNames[i], "and is", catAges[i], "years old")
break
catNames = catNames + [name]
catAges = catAges + [age]
If I can understand correctly you want it to print the age and the name together?
Well if thats so you can do it like this:
catNames = []
catAges = []
while True:
name = input("Enter the name of Cat {} (Or enter nothing to stop): ".format(str(len(catNames) + 1)))
while name != "":
age = input("Enter the age of {}: ".format(name)) # Takes inputted name and adds it to the print function.
catNames.append(name) # Adds the newest name the end of the catNames list.
catAges.append(age) # Adds the newest age the end of the catNames list.
break
if name == "":
print("\nThe cat names and ages are: ")
for n in range(len(catNames)):
print("\nName: {}\nAge: {}".format(catNames[n], catAges[n]))
break
Resulting output:
Enter the name of Cat 1 (Or enter nothing to stop): Cat1
Enter the age of Cat1: 5
Enter the name of Cat 2 (Or enter nothing to stop): Cat2
Enter the age of Cat2: 7
Enter the name of Cat 3 (Or enter nothing to stop): # I hit enter here so it skips.
The cat names and ages are:
Name: Cat1
Age: 5
Name: Cat2
Age: 7
If you have any issues with what I did, please just ask.
fn = input("Hello, what is your first name?")
firstname = (fn[0].upper())
ln = input("Hello, what is your last name?")
lastname = (ln.lower())
I want fn to be on a loop so that if they enter their a number instead of letters, it would repeat the question
I guess you need something like this
final_fn = ""
while True:
fn = input("Hello, what is your first name?")
if valid(fn):
final_fn = fn
break
Define you validation method before it. An example would be as Joran mentioned
def valid(fn):
return fn.isalpha()
if result.isalpha():
print "the string entered contains only letters !"
I guess ?
a="6"
while not a.isalpha():
a = raw_input("Enter your name:")
print "You entered:",a
if you just wanted to eliminate only words that contained numbers you could do
while any(ltr.isdigit() for ltr in a):
print("You may invite up to six people to your party.")
name = input("Enter invitee's name (or just press enter to finish): ")
nameList = ["","","","","",""]
currentName = 0
while name != "":
if currentName > 5:
break #If more than 6 names are input, while loop ends.
else:
nameList[currentName] = name
name = input("Enter invitee's name (or just press enter to finish): ")
currentName = currentName + 1
for i in len(nameList):
invitee = nameList[i]
print(invitee + ", please attend our party this Saturday!")
The only syntactic problem with your code is that you can't do for i in len(nameList), you have to use range() if you want to loop a certain number of times. It will work if you change the last section to:
for i in range(len(nameList)): # range(5) makes a list like [0, 1, 2, 3, 4]
invitee = nameList[i]
print(invitee + ", please attend our party this Saturday!")
len(nameList) returns an integer you should call range(len(nameList)) instead. However, the code will be cleaner if you write it like:
print("You may invite up to six people to your party.")
name_list = []
for current_name in range(6):
name = input("Enter invitee's name (or just press enter to finish): ")
if not name:
break
name_list.append(name)
for invitee in name_list:
print(invitee + ", please attend our party this Saturday!")
OK so what I need to do is make my code only allow the user to enter one letter and then one symbol at a time. The example below shows what I want in a better view.
At the moment my code allows the user to enter more than one character at a time which I don't want.
What letter would you like to add? hello
What symbol would you like to pair with hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello']
What I want is a message to be displayed like this and the pairing not to be added to the list.
What letter would you like to add? hello
What symbol would you like to pair with hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].
So far my code for this section is as follows...
It would also be great for when the user enters a number in the letter section, an error message to be printed.
def add_pairing(clues):
addClue = False
letter=input("What letter would you like to add? ").upper()
symbol=input("\nWhat symbol would you like to pair with ")
userInput= letter + symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
elif len(userInput) ==1:
print("You can only enter one character")
else:
newClue = letter + symbol
addClue = True
if addClue == True:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
The easiest way to ensure user input is with a loop:
while True:
something = raw_input(prompt)
if condition: break
Something set up like this will continue to ask prompt until condition is met. You can make condition anything you want to test for, so for you, it would be len(something) != 1
Your method can be simplified to the following if you let the user enter a letter and symbol pair:
def add_pairing(clues):
pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
clues = pairing.upper().split()
print('Your pairings are: {}'.format(clues))
return clues
Not exactly sure what you want to return but this will check all the entries:
def add_pairing(clues):
addClue = False
while True:
inp = input("Enter a letter followed by a symbol, separated by a space? ").upper().split()
if len(inp) != 2: # make sure we only have two entries
print ("Incorrect amount of characters")
continue
if not inp[0].isalpha() or len(inp[0]) > 1: # must be a letter and have a length of 1
print ("Invalid letter input")
continue
if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
print ("Invalid character input")
continue
userInput = inp[0] + inp[1] # all good add letter to symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
else:
newClue = userInput
addClue = True
if addClue:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
I am fan of raising and catching exceptions in similar cases. Might be shocking for people with 'C-ish' background (sloooow), but it is perfectly pythonic and quite readable and flexibile in my opinion.
Also, you should add check for characters outside of set you are expecting:
import string
def read_paring():
letters = string.ascii_uppercase
symbols = '*##$%^&*' # whatever you want to allow
letter = input("What letter would you like to add? ").upper()
if (len(letter) != 1) or (letter not in letters):
raise ValueError("Only a single letter is allowed")
msg = "What symbol would you like to pair with '{}'? ".format(letter)
symbol = input(msg).upper()
if (len(symbol) != 1) or (symbol not in symbols):
raise ValueError("Only one of '{}' is allowed".format(symbols))
return (letter, symbol)
def add_pairing(clues):
while True:
try:
letter, symbol = read_paring()
new_clue = letter + symbol
if new_clue in clues:
raise ValueError("This pairing already exists")
break # everything is ok
except ValueError as err:
print(err.message)
print("Try again:")
continue
# do whatever you want with letter and symbol
clues.append(new_clue)
print(new_clue)
return clues