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.
Related
I have no idea what I am doing wrong. Here is the question:
● Write a Python program called “John.py” that takes in a user’s input as a String.
● While the String is not “John”, add every String entered to a list until “John” is entered.
Then print out the list. This program basically stores all incorrectly entered Strings in a
list where “John” is the only correct String.
● Example program run (what should show up in the Python Console when you run it):
Enter your name :
Enter your name:
Enter your name:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This is what I have so far:
name_list = [" "]
valid_name = "John"
name = str(input("please enter a name: "))
if name != valid_name.upper():
#name = str(input("please enter a name: ")
name_list.append(name)
name_list += name
elif name == valid_name.upper():
name_list.append(name)
name_list += name
print("Incorrect names that you have added: ")`enter code here`
print(name_list[0:])
You almost got it! just need to use a while loop instead of a if/else:
name_list = []
valid_name = "John"
name = str(input("please enter a name: "))
while name != valid_name:
name_list.append(name)
name = str(input("Incorrect! please enter a name: "))
print(f"Correct! Incorrect names that you have added: {name_list}")
dictionary = {}
name = input("Name: ")
while name: #while the name is not blank
age = input("Age: ")
dictionary[name] = age
name = input("Name: ")
print("Thank you, bye!")
f = open("1ex.txt","w")
f.write( str(dictionary) )
f.close()
So I have this code, it does what I want, but I cant seems to figure it out how can I write the file, so that it would have not a dictionary, but smth like this:
Jane, 25
Jim, 24
I tried putting everything into a list, but it doesn't work out for me.
Try this:
dictionary = {}
name = input("Name: ")
while name: #while the name is not blank
age = input("Age: ")
dictionary[name] = age
name = input("Name: ")
print("Thank you, bye!")
# Open the file
with open("1ex.txt","w") as f:
# For each key/value pair in the dictionary:
for k, v in dictionary.items():
# Write the required string and a newline character
f.write(f"{k}, {v}\n")
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))
I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()
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!")