how can i rearrange the letters in the name with this code - python

there are 3 errors in the code, can you guys please help me find them, I am just a beginner. I need to append (concatenate) the letter from Var1 to namelist variable, which is a list variable. But there seems to be a problem as i is a string.
namelist = []
var1 = input( "Enter the name you want to validate ").upper()
namelist.append(var1[0])
for i in var1[1:]:
for j in (namelist):
if(j>=i):
namelist.insert(i,namelist.index(j))
break
else:
i.append(namelist)
print(namelist)
expected result: to run the code swiftly to rearrange letters in the name

its seems like you vwant to reverse string
there are several ways, here are some with basic for loop
namelist = []
var1 = input( "Enter the name you want to validate ").upper()
for i in range(1, len(var1) + 1):
namelist.append(var1[len(var1) - i])
print (namelist)
print ("".join(namelist))
output:
Enter the name you want to validate Hello
['O', 'L', 'L', 'E', 'H']
OLLEH
.
namelist = ''
var1 = input( "Enter the name you want to validate ").upper()
for i in range(1, len(var1) + 1):
namelist = namelist + var1[len(var1) - i]
print (namelist)
output:
Enter the name you want to validate hello
OLLEH
.
def reverse(text):
rev_text = ""
for char in text:
rev_text = char + rev_text
return rev_text
print (reverse("hello"))
output:
olleh

First of all, please use clear names for variables.
What exactly do you want to reach with your code?
You can use this code to get an list of the letters:
NameList = []
Input = input("Enter the name you want to validate:\n").upper()
for Character in Input:
NameList.append(Character)
print(NameList)
And set a variable to the reverse with:
NameList = []
Input = input("Enter the name you want to validate:\n").upper()
for Character in Input:
NameList.append(Character)
Output = "".join(NameList[::-1])

Related

How to write a function to print out a item in dictionary?

I am trying to define and call a function but I am stuck on what to put all I know currently is that I definitely need a for loop .
I want my output to be 867-5309
from an input of
Input 1: Joe 123-5432 Linda 983-4123 Frank 867-5309
Input 2: Frank
Though obviously I need it to work for any input that is placed into the name input
def get_phone_number(my_dict, contact_name):
phone_number = ''
return phone_number
if __name__ == '__main__':
word_pairs = input()
my_list = word_pairs.split()
name = input()
my_dict = {}
for i in range(0, len(my_list), 2):
my_dict[my_list[i]] = my_list[i + 1]
print(get_phone_number(dict, name))
I already know my dictionary works fine my only problem is with formatting a function that will give me the output I want, I am struggling with functions and just need a little help to get the result I want.
You don't need a function for this. And least of all a loop. You can just call the entry of my_dict using the key:
if __name__ == '__main__':
word_pairs = input("Enter Words: ")
my_list = word_pairs.split()
name = input("Enter Name: ")
my_dict = {}
for i in range(0, len(my_list), 2):
my_dict[my_list[i]] = my_list[i + 1]
print(my_dict[name])

How to generate random string? [duplicate]

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))

Adding items to a list until keypress

I have got it to work, except the list doesn't save the inputs properly; it just lists them as three periods. This is the code:
names = []
i=0
while 1:
i+=1
name=input("Please enter the name")
if name==" ":
break
names.append(names)
print(names)
Change names.append(names) to names.append(name), since you want to append name to the list names (just a typo I guess).
Also if name == " " must be changed to if name == "", since if the user presses enter without providing any name, the input is an empty string, not a white space.
Correct code here:
names = []
i = 0
while True:
i += 1
name = input("Please enter the name ")
if name == "":
break
names.append(name)
print(names)

How to write in new line in a file?

I need to create a program that saves people's information e.g. their name in a text file depending on the first letter of their surname so if their surname starts with a K it goes into MyFile1.
I need it to loop like I have done because it's an unknown number of people however I want each person to be written in a different line in the text file is there a way to do this.
The code at the bottom puts each separate information into a new line and I don't want that I want each different person to be in a new line.
MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])
while 1:
SurName = input("Enter your surname name.")
if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
Title = input("Enter your title.")
myListAL.append(Title);
FirstName = input("Enter your first name.")
myListAL.append(FirstName);
myListAL.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListAL.append(Birthday);
Email = input("Enter your email.")
myListAL.append(Email);
PhoneNumber = input("Enter your phone number.")
myListAL.append(PhoneNumber);
for item in myListAL:
MyFile1.write(item+"\n")
elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
Title = input("Enter your title.")
myListMZ.insert(Title);
FirstName = input("Enter your first name.")
myListMZ.append(FirstName);
myListMZ.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListMZ.append(Birthday);
Email = input("Enter your email.")
myListMZ.append(Email);
PhoneNumber = input("Enter your phone number.")
myListMZ.append(PhoneNumber);
line.write("\n")
for item in myListMZ:
MyFile2.write(line)
elif SurName == "1":
break
MyFile1.close()
MyFile2.close()
You are looking for join.
When you have a list of items you can join them in a single string with.
l = ['a', 'b', 'c']
print(''.join(l))
produces
abc
You can not only use the empty string but also another string which will be used as separator
l = ['a', 'b', 'c']
print(', '.join(l))
which now produces
a, b, c
In your examples (for example the first write)
MyFile1.write(','.join(MyListAL) + '\n')
If you happen to have something in the list which is not a string:
MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')
(you can also use map, but a generator expression suffices)
Edit: adding the map:
MyFile1.write(','.join(map(str, MyListAL)) + '\n')
In your case I would rather use a list of dictionaries, where a person with all its infos is a dictionary. Then you can convert it to a JSON string, which is a standard format for representing data. (Otherwise you need to define your own format, with delimiters between the items.)
So something like this:
import json # at the top of your script
# I would create a function to get the information from a person:
def get_person_input():
person = {}
person["surname"] = input("Surname: ")
person["title"] = input("Title: ")
person["email"] = input("Email: ")
# TODO: do whatever you still want
return person
# Later in the script when you want to write it to a file:
new_line = json.dumps( person )
myfile.write( new_line + "\n" )
Parsing a json is also very easy after all:
person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format
You can use in your code for the decision in which array it should be written something like this:
SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
...
else:
...
This will make your script more clear and robust.

Trying to display initials in Python

I'm trying to make this so that when a person types their name just the initials display capitalized and separated by a period. I can't figure out what is wrong with this code I wrote... help pls!
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
print(name_list)
first = name[0][0]
second = name[1][0]
last = name[2][0]
print(first,'.', second,'.')
main()
If you are on Python 2.x you should exchange input for raw_input. Here's a quicker way to achieve what you're aiming for assuming you're on Python 2.x:
def main():
full_name = raw_input('Type your name and press ENTER. ')
initials = '.'.join(name[0].upper() for name in full_name.split())
print(initials)
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
print(name_list)
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]
print(first.upper(),'.', second.upper(),'.', last.upper())
main()
Here's a version similar to the one you have.
Note that you were using name instead of name_list, and some hard-coded indexes.
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
for part in name_list:
print(part[0].upper() + ". ", end="")
print()
main()
It loops over the list you created with split(), and prints the first letter (in upper case) of each part of the name.
The loop only makes sense if you want every part to be included of course.
I'll try to explain why it occurred rather than just giving you the solution.
You're using name instead of name_list when name_list is what you're intending to use.
name for 'Amanda Leigh Blount' = 'Amanda Leigh Blount'
but name_list = name.split() = ['Amanda', 'Leigh', 'Blount']
So you get a difference in the two only on the middle/last name.
The first name is equivalent for both:
name[0][0] == name_list[0][0]
The left side matches the first letter of the first letter:
'Amanda Leigh Blount'[0][0] = 'A'[0] = 'A'
The right side matches the first letter of the first word.
['Amanda', 'Leigh', 'Blount'][0][0] = 'Amanda'[0] = 'A'
But for the second:
name[1][0] != name_list[1][0]
because the first & second are:
'Amanda Leigh Blount'[1][0] = 'm'[0] = 'm'
['Amanda', 'Leigh', 'Blount'][0][0] = 'Leigh'[0] = 'L'
So just use name_list instead of name:
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]

Categories

Resources