Need to print 10 different question booklets(aka Forms) but not able to print 9 of them as only the last one gets created and printed - python-3.x

import random
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'NewMexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia'}
for quizNum in range(10):
quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
for questionNum in range(40):
correctAnswer = capitals[states[questionNum]]
wrongAnswers = list(capitals.values())
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer]
random.shuffle(answerOptions)
quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1,states[questionNum]))
for i in range(4):
quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerKeyFile.close()
The remaining 9 booklets are created as .txt files but are blank. Where am I going wrong ?
Questions involve the capital cities of U.S.A
Expected file form is :
Name:
Date:
Period:
State Capitals Quiz (Form 1)
What is the capital of West Virginia?
A. Hartford
B. Santa Fe
C. Harrisburg
D. Charleston
What is the capital of Colorado?
A. Raleigh
B. Harrisburg
C. Denver
D. Lincoln
3......
and so on . Like that for all the other files(remaining 9 .txt files which get created) questions would have to be printed.But they just turn out to be blank.
Each question booklets has the same questions but are in different order(to prevent cheating)

You questions loop is outside of the file loop. This is causing all of the files to be opened before any questions are written, then the last opened file is what gets the questions 👍
I can post the fix later if needed, just on my phone right now.

Related

Best way to handle element of dict that has multiple key/value pairs inside it

[{'id': 2, 'Registered Address': 'Line 1: 1 Any Street Line 2: Any locale City: Any City Region / State: Any Region Postcode / Zip code: BA2 2SA Country: GB Jurisdiction: Any Jurisdiction'}]
I have the above read into a dataframe and that is the output so far. The issue is I need to break out the individual elements - due to names of places etc the values may or may not have spaces in them - looking at the above my keys are Line 1, Line 2, City, Region / State, Postcode / Zip, Country, Jurisdiction.
Output required for the "Registered Address"-'key'is the keys and values
"Line 1": "1 Any Street"
"Line 2": "Any locale"
"City": "Any City"
"Region / State": "Any Region"
"Postcode / Zip code": "BA2 2SA"
"Country": "GB"
"Jurisdiction": "Any Jurisdiction"
Just struggling to find a way to get to the end result.I have tried to pop out and use urllib.prse but fell short - is anypone able to point me in the best direction please?
Tried to write a code that generalizes your question, but there were some limitations, regarding your data format. Anyway I would do this:
def address_spliter(my_data, my_keys):
address_data = my_data[0]['Registered Address']
key_address = {}
for i,k in enumerate(keys):
print(k)
if k == 'Jurisdiction:':
key_address[k] = address_data.split('Jurisdiction:')[1].removeprefix(' ').removesuffix(' ')
else:
key_address[k] = address_data.split(k)[1].split(keys[i+1])[0].removeprefix(' ').removesuffix(' ')
return key_address
were you can call this function like this:
my_data = [{'id': 2, 'Registered Address': 'Line 1: 1 Any Street Line 2: Any locale City: Any City Region / State: Any Region Postcode / Zip code: BA2 2SA Country: GB Jurisdiction: Any Jurisdiction'}]
and
my_keys = ['Line 1:','Line 2:','City:', 'Region / State:', 'Postcode / Zip code:', 'Country:', 'Jurisdiction']
As you can see It'll work if only the sequence of keys is not changed. But anyway, you can work around this idea and change it base on your problem accordingly if it doesn't go as expected.

I want to print the country capitals if the country is chosen

Here is the code:
import time
from colored import fg
import sys
clr1 = fg("red")
clr2 = fg("blue")
clr3 = fg("yellow")
clr4 = fg("green")
for x in (clr1 + "Hi,\nThis program is made to find out the capital city of countries. For now, there are only around 100 countries which you can find the capitals of.\nThe countries are:\n"):
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(0.03)
time.sleep(1)
for x in (clr2 + "Afghanistan\nAlbania\nAlgeria\nArgentina\nArmenia\nAustralia\nAustria\nAzerbaijan\nBahrain\nBangladesh\nBelgium\nBenin\nBotswana\nBrazil\nBulgaria\nCanada\nChile\nColombia\nCostaRica\nCroatia\nCuba\nDenmark\nDjibouti\nDominica\nEgypt\nEritrea\nEstonia\nEthiopia\nFiji\nFinland\nFrance\nGabon\nGermnay\nGhana\nGreece\nGrenada\nGuinea\nHaiti\nHungary\nIceland\nIndia\nIndonesia\nIran\Ireland\nItaly\nJamaica\nJapan\nJordan\nKenya\nSouthKorea\nKosovo\nKuwait\nLaos\nLativa\nLebanon\nLiberia\nLibya\nLuxembourg\nMacedonia\nMadagascar\nMalawi\nMalaysia\nMaldives\nMali\nMexico\nMoldova\nMonaco\nMongolia\nMontenegro\nMorocco\nMozambique\nNamibia\nNepal\nNetherlands\nNewZealand\nNiger\nNigeria\nNorway\nOman\nPakistan\nPanama\nPhilippines\nPoland\nPortugal\nQatar\nRomania\nRussia\nSamoa\nSaudi Arabia\nSenegal\nSerbia\nSingapore\nSlovakia\nSomalia\nSouth Africa\nSpain\nSri Lanka\nSudan\nSwitzerland\nSyria\nTaiwan\nThailand\nUganda\nUnited Arab Emirates\nUnited Kingdom\nUnited States of America\nUruguay\nVatican City\nVietnam\nYemen\nZimbabwe\n\n\n"):
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(0.003)
time.sleep(1)
countries = {
"Afghanistan": 'Kabul',
"Albania":'Tirana',
"Algeria":'Algeirs',
"Argentina":'Buenos Aires',
"Armenia":'Yerevan',
"Australia":'Cnaberra',
"Austria":'Vienna',
"Azerbaijan":'Baku',
"Bahrain":'Manama',
"Bangladesh":'Dhaka',
"Belgium":'Brussels',
"Benin":'Porto_Novo',
"Botswana":'Gaborone',
"Brazil":'Brasilia',
"Bulgaria":'Sofia',
"Canada":'Ottawa',
"Chile":'Santiago',
"Colombia":'Bogota',
"Costa Rica":'San Jose',
"Croatia":'Zagreb',
"Cuba":'Havana',
"Denmark":'Copenhagen',
"Djibouti":'Djibouti',
"Dominica":'Roseau',
"Egypt":'Cairo',
"Eritrea":'Asmara',
"Estonia":'Tallinn',
"Ethiopia":'Addis Ababa',
"Fiji":'Suva',
"Finland":'Helsinki',
"France":'Paris',
"Gabon":'Libreville',
"Germnay":'Berlin',
"Ghana":'Accra',
"Greece":'Athens',
"Grenada":'Saint Georges',
"Guinea":'Conakry',
"Haiti":'Port-au-Prince',
"Hungary":'Budapest',
"Iceland":'Reykjavik',
"India":'New Delhi',
"Indonesia":'Jakarta',
"Iran":'Tehran',
"Ireland":'Dublin',
"Italy":'Rome',
"Jamaica":'Kingston',
"Japan":'Tokyo',
"Jordan":'Amman',
"Kenya":'Nairobi',
"South Korea":'Seoul',
"Kosovo":'Pristina',
"Kuwait":'Kuwait City',
"Laos":'Vientiane',
"Lativa":'Riga',
"Lebanon":'Beirut',
"Liberia":'Monrovia',
"Libya":'Tripoli',
"Luxembourg":'Luxembourg',
"Macedonia":'Skopje',
"Madagascar":'Antananarivo',
"Malawi":'Lilongwe',
"Malaysia":'Kuala Lumpur',
"Maldives":'Male',
"Mali":'Bamako',
"Mexico":'Mexico City',
"Moldova":'Chisnau',
"Monaco":'Monaco',
"Mongolia":'Ulaanbaatar',
"Montenegro":'Podgorica',
"Morocco":'Rabat',
"Mozambique":'Maputo',
"Namibia":'Windhoek',
"Nepal":'Kathmandu',
"Netherlands":'Amsterdam',
"NewZealand":'Wellington',
"Niger":'Niamey',
"Nigeria":'Abuja',
"Norway":'Oslo',
"Oman":'Muscat',
"Pakistan":'Islamabad',
"Panama":'Panama City',
"Philippines":'Manila',
"Poland":'Warsaw',
"Portugal":'Lisbon',
"Qatar":'Doha',
"Romania":'Bucharest',
"Russia":'Moscow',
"Samoa":'Apia',
"Saudi Arabia":'Riyadh',
"Senegal":'Dakar',
"Serbia":'Belgrade',
"Singapore":'Singapore',
"Slovakia":'Bratislava',
"Somalia":'Mogadishu',
"South Africa":'Pretoria(administrative); Cape Town(legislative); Bloemfontein(judicary)',
"Spain":'Madrid',
"Sri Lanka":'Colombo; Sri Jayewardenepura Kotte(legislative)',
"Sudan":'Khartoum',
"Switzerland":'Bern',
"Syria":'Damascus',
"Taiwan":'Taipei',
"Thailand":'Bangkok or Krung Thep Maha Nakhon',
"Uganda":'Kampala',
"United Arab Emirates":'Abu Dhabi',
"United Kingdom":'London',
"United States of America":'Washington, D.C',
"Uruguay":'Montevideo',
"Vatican City":'Vatican City',
"Vietnam":'Hanoi',
"Yemen":'Sanaa',
"Zimbabwe":'Harare'
}
time.sleep(1)
user_input = input(clr3 + "What country's capital do you want to find out (That is in the list) ?\n>>> ")
So every time the user inputs a country, how do I make it so that it prints out the capital with the fewest possible lines of code. For example i enter France and it gives out Paris. I dont want to use if statements to go through every line and say if user_input == <> : print("Capital"). That way I will have to write the statements over a 100 times. Is there a way to solve this problem
try:
print(countries[user_input])
except KeyError: # If the user input wasn't found in the dictionary
print("Invalid Country!")

Extracting countries from string

I am trying to go through a column of data frame in python 3. What I need to do is take from each row the country that it is mentioned and the number of times that country is mentioned.
i.e. if I have this row:
['[Aydemir, Deniz', ' Gunduz, Gokhan', ' Asik, Nejla] Bartin Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, Turkey', ' [Wang, Alice] Lulea Univ Technol, Wood Technol, Skelleftea, Sweden']
it needs to output a list: ['Turkey', 'Sweden']
and if I have this row:
['[Fang, Qun', ' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 311300, Peoples R China', ' [Du, Guan-Ben] Southwest Forestry Univ, Kunming 650224, Yunnan, Peoples R China']
the output should be: ['China', 'China'].
I have written this code but it is not working as I want to:
from geotext import GeoText
sentence = df.iloc[0,0]
places = GeoText(sentence)
print(places.countries)
It prints only the country once and in some cases when it is USA it doesn't recognize the abbreviation. Can you help me figure out what to do?
l = [['[Aydemir, Deniz\', \' Gunduz, Gokhan\', \' Asik, Nejla] Bartin Univ, Fac Forestry, Dept Forest Ind Engn, TR-74100 Bartin, Turkey\', \' [Wang, Alice] Lulea Univ Technol, Wood Technol, Skelleftea, Sweden',1990],
['[Fang, Qun\', \' Cui, Hui-Wang] Zhejiang A&F Univ, Sch Engn, Linan 311300, Peoples R China\', \' [Du, Guan-Ben] Southwest Forestry Univ, Kunming 650224, Yunnan, Peoples R China',2005],
['[Blumentritt, Melanie\', \' Gardner, Douglas J.\', \' Shaler, Stephen M.] Univ Maine, Sch Resources, Orono, ME USA\', \' [Cole, Barbara J. W.] Univ Maine, Dept Chem, Orono, ME 04469 USA',2012]]
dataf = pd.DataFrame(l, columns = ['Authors', 'Year'])
I tried to do this code but I have the same problem, it doesn't give all the counties only one per row:
def find_country(n):
for c in pycountry.countries:
if str(c.name).lower() in n.lower():
return c.name
country1 = (dataf['Authors']
.replace(r"\bUSA\b", "United States", regex=True)
.apply(lambda x: find_country(x)))
USA does not seem to be detected correctly by geotext - it's worth trying to raise an issue with that package. As a workaround here, I replace USA with United States, which is correctly detected.
df = (dataf['Authors']
.replace(r"\bUSA\b", "United States", regex=True)
.apply(lambda x: geotext.GeoText(x).countries)
)
I'm not sure what you were doing before, but this will get the list of countries for each of the rows in Author, including duplicates.
0 [Turkey, Sweden]
1 [China, China]
2 [United States, United States]
Name: Authors, dtype: object
As mentioned in the comment, if you want to have an actual list of lists, just add tolist() to the end.
df.tolist()
[['Turkey', 'Sweden'], ['China', 'China'], ['United States', 'United States']]

Creating a table using a list of strings

I am needing to convert a list of lists of strings into a three column table where the first column is 1 space longer than the longest string. I have figured out how to identify the longest string and how long it is, but getting the table to form has been quite tricky. Here is the program with the lists in it and it shows you that the longest one is 26 characters long.
def main():
mycities = [['Cape Girardeau', 'MO', '63780'], ['Columbia', 'MO', '65201'],
['Kansas City', 'MO', '64108'], ['Rolla', 'MO', '65402'],
['Springfield', 'MO', '65897'], ['St Joseph', 'MO', '64504'],
['St Louis', 'MO', '63111'], ['Ames', 'IA', '50010'], ['Enid',
'OK', '73773'], ['West Palm Beach', 'FL', '33412'],
['International Falls', 'MN', '56649'], ['Frostbite Falls',
'MN', '56650']]
col_width = max(len(item) for sub in mycities for item in sub)
print(col_width)
main()
Now I am just needing to get it to print off like this:
Cape Girardeau MO 63780
Columbia MO 65201
Kansas City MO 64108
Springfield MO 65897
St Joseph MO 64504
St Louis MO 63111
Ames IA 50010
Enid OK 73773
West Palm Beach FL 33412
International Falls MN 56649
Frostbite Falls MN 56650
You're off to the right start -- as an example given the specific structure to the lists you have, you can use the col_width you calculated to determine the number of spaces you'd need after the name of each city to append to the end of each city name:
for city in mycities:
# append the string with the number of spaces required
city_padded = city[0] + " " + " "*(col_width-len(city[0]))
print(city_padded + city[1] + " " + city[2])
Given your example, this will produce:
Cape Girardeau MO 63780
Columbia MO 65201
Kansas City MO 64108
Rolla MO 65402
Springfield MO 65897
St Joseph MO 64504
St Louis MO 63111
Ames IA 50010
Enid OK 73773
West Palm Beach FL 33412
International Falls MN 56649
Frostbite Falls MN 56650
Note in the original version of your question, you are missing commas in your sublists in your mycities variable, for which I've added in an edit.
As a side note, it is convention in Python that words be separated by underscores in variable names for readability, so you might rename mycities to my_cities.
pep8 ref: (https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)
"String name".ljust(26) will add spaces to the end of your string. For example,
Ames.ljust(26) will result in 'Ames (22 spaces here)', and then the next column will print after. If you are not sure what the longest city will be, you could replace the 26 with len(cities[-1]) after ordering the cities in a list by length. To do this, you can do sortedCities = sorted(cityListVariable, key=len)
def main():
cities = ['Cape Girardeau, MO 63780', 'Columbia, MO 65201', 'Kansas City, MO 64108', 'Rolla, MO 65402',
'Springfield, MO 65897', 'St Joseph, MO 64504', 'St Louis, MO 63111', 'Ames, IA 50010',
'Enid, OK 73773', 'West Palm Beach, FL 33412', 'International Falls, MN 56649', 'Frostbite Falls, MN 56650',
'Charlotte, NC 28241', 'Upper Marlboro, MD 20774', 'Camdenton, MO 65020', 'San Fransisco, CA 94016'] #create list of information
for x in cities:
col = x.split(",")
if(len(col) == 2):
city = col[0].strip()
temp = col[1].strip()
else:
city = x[:15].strip()
temp = c[15:].strip()
state = temp[:2]
zipCode = int(temp[-5::])
print("%-20s\t%s\t%d"%(city, state, zipCode))
main()

In a comma delimited String, keep all but second part

I have a bunch of addresses:
123 Main Street, PO Box 345, Chicago, IL 92921
1992 Super Way, Bakersfield, CA
234 Wonderland Lane, Attn: Daffy Duck, Orlando, FL 09922
How could I cut out the second string in there, when I do myStr.split(',') on each?
The idea is that I want to return:
123 Main Street, Chicago, IL 92921
1992 Super Way, CA
234 Wonderland Lane, Orlando, FL 09922
I could loop through each part, and build yet another string, skipping the second index, but was wondering if there's a better way to do so.
What I have now:
def filter_address(address):
print("Filtering address on",address)
updated_addr = ""
indx = 0
for section in address.split(","):
if indx != 1:
updated_addr = updated_addr + "," + section
indx += 1
updated_addr = updated_addr[1:] # This is to remove the leading `,`
new_address = filter_address("123 Main Street, Chicago, IL 92921")
You could use del in python and glue back the components of the string with ", " after splitting them.
For example:
address = "123 Main Street, PO Box 345, Chicago, IL 92921".split(",")
del address[1]
pretty_address = ", ".join(address)
print(pretty_address) # Gives 123 Main Street, Chicago, IL 92921

Resources