By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,100 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

Output file in Python

P: 52
Hello, I'm back.

After lots of tinkering, and asking guys here at the forum, we made a program that could successfully create a dungeons and dragons role playing character. In the end, the output looks like this:

----------------------------------------------------------------
Your character's sex is: Male
Your character's name is: Charlie
Your character's race is: Gnome
Your character's class is: Warrior
----------------------------------------------------------------
.............Physical Traits............
strength = 14
decterity = 15
constitution = 10
.............Mental Traits...............
intelligence = 10
charisma = 9
wisdom = 8
----------------------------------------------------------------
Alignment: Chaotic Neutral



And that is in cmd of course.
The thing I was wondering was this, is it possible to write something into the python script to make it save this output as a .txt file?

Thanks, now I'm off to a birthday!
Jun 2 '07 #1
Share this Question
Share on Google+
16 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Hello, I'm back.

After lots of tinkering, and asking guys here at the forum, we made a program that could successfully create a dungeons and dragons role playing character. In the end, the output looks like this:

----------------------------------------------------------------
Your character's sex is: Male
Your character's name is: Charlie
Your character's race is: Gnome
Your character's class is: Warrior
----------------------------------------------------------------
.............Physical Traits............
strength = 14
decterity = 15
constitution = 10
.............Mental Traits...............
intelligence = 10
charisma = 9
wisdom = 8
----------------------------------------------------------------
Alignment: Chaotic Neutral



And that is in cmd of course.
The thing I was wondering was this, is it possible to write something into the python script to make it save this output as a .txt file?

Thanks, now I'm off to a birthday!
Yes. This code
Expand|Select|Wrap|Line Numbers
  1. fn = r'X:\subdirectory\data.txt'
  2. data = ['sex', 'name', 'race', 'class', 'strength', 'dexterity', 'constitution', 'intelligence', 'charisma', 'wisdom']
  3. dd = dict.fromkeys(data, 'XX')
  4. outList = ['%s = %s' % (item, dd[item]) for item in data]
  5. f = open(fn, 'w')
  6. f.write('\n'.join(outList))
  7. f.close()
yields a file like this:

sex = XX
name = XX
race = XX
class = XX
strength = XX
dexterity = XX
constitution = XX
intelligence = XX
charisma = XX
wisdom = XX


I'll leave it to you to pretty up the output.
Jun 2 '07 #2

Expert 100+
P: 511
or if its just one file, do it from the command line
Expand|Select|Wrap|Line Numbers
  1. # python script.py > outfile.txt
  2.  
Jun 2 '07 #3

P: 52
Yes. This code
Expand|Select|Wrap|Line Numbers
  1. fn = r'X:\subdirectory\data.txt'
  2. data = ['sex', 'name', 'race', 'class', 'strength', 'dexterity', 'constitution', 'intelligence', 'charisma', 'wisdom']
  3. dd = dict.fromkeys(data, 'XX')
  4. outList = ['%s = %s' % (item, dd[item]) for item in data]
  5. f = open(fn, 'w')
  6. f.write('\n'.join(outList))
  7. f.close()
yields a file like this:

sex = XX
name = XX
race = XX
class = XX
strength = XX
dexterity = XX
constitution = XX
intelligence = XX
charisma = XX
wisdom = XX


I'll leave it to you to pretty up the output.
That is probably good and all, but I have this insane theory that I will not get better at programming by just copying and pasting... Is that crazy? If you would please explain the different parts of that? Like the ones that are one step beyond basic? I'm a newbie, like it says under my name... If that saounded rude, it was unintentional.

Thanks
Jun 2 '07 #4

bvdet
Expert Mod 2.5K+
P: 2,851
That is probably good and all, but I have this insane theory that I will not get better at programming by just copying and pasting... Is that crazy? If you would please explain the different parts of that? Like the ones that are one step beyond basic? I'm a newbie, like it says under my name... If that sounded rude, it was unintentional.

Thanks
You seem to have the right attitude, wanting to learn how it works. Writing information to a file is easy. Compiling the information to write to a file in a structured manner is not so easy (sometimes). Do you want to be able to read in the data at a later date? If so, it must be organized in a manner that will be easy to parse. I will explain my code, line for line.

This is the name of the file that we will write to:
Expand|Select|Wrap|Line Numbers
  1. fn = r'X:\subdirectory\data.txt'
This is a list of variable names:
Expand|Select|Wrap|Line Numbers
  1. data = ['sex', 'name', 'race', 'class', 'strength', 'dexterity', 'constitution', 'intelligence', 'charisma', 'wisdom']
A dictionary is probably the best way to organize data in many cases. The dictionary is Python's built-in mapping type object. The mapping type of object is also known as a hash table or associative array. We can initialize a dictionary to maintain your data in your program like this:
Expand|Select|Wrap|Line Numbers
  1. dd = dict.fromkeys(data, 'XX')
A player's attributes can be set like this:
Expand|Select|Wrap|Line Numbers
  1. >>> dd
  2. {'dexterity': 'XX', 'strength': 'XX', 'name': 'XX', 'intelligence': 'XX', 'sex': 'XX', 'charisma': 'XX', 'race': 'XX', 'wisdom': 'XX', 'class': 'XX', 'constitution': 'XX'}
  3. >>> dd['strength']=10
  4. >>> dd
  5. {'dexterity': 'XX', 'strength': 10, 'name': 'XX', 'intelligence': 'XX', 'sex': 'XX', 'charisma': 'XX', 'race': 'XX', 'wisdom': 'XX', 'class': 'XX', 'constitution': 'XX'}
  6. >>> print dd['strength']
  7. 10
  8. >>> 
When you have gathered all of the player's data, create a list of formatted strings suitable for writing to disk:
Expand|Select|Wrap|Line Numbers
  1. >>> outList = ['%s = %s' % (item, dd[item]) for item in data]
  2. >>> outList[4]
  3. 'strength = 10'
  4. >>> 
Create a file object for writing:
Expand|Select|Wrap|Line Numbers
  1. f = open(fn, 'w')
join is a string method that is used to assemble a list of strings into a single string. I have chosen this method to further prepare the data for writing. Here's an example of the use of join:
Expand|Select|Wrap|Line Numbers
  1. >>> strList = ["This is one sentence.", "This is another sentence."]
  2. >>>'\n'.join(strList)
  3. >>> print '\n'.join(strList)
  4. This is one sentence.
  5. This is another sentence.
  6. >>> 
I am now writing the data to the file:
Expand|Select|Wrap|Line Numbers
  1. f.write('\n'.join(outList))
Close the file object:
Expand|Select|Wrap|Line Numbers
  1. f.close()
This will read the data back in:
Expand|Select|Wrap|Line Numbers
  1. >>> dd1 = {}
  2. >>> for item in open(fn).readlines():
  3. ...     key, value = item.strip().split(' = ')
  4. ...     dd1[key] = value
  5. ...     
  6. >>> for key in dd1:
  7. ...     print '%s=%s' % (key, dd1[key])
  8. ...     
  9. dexterity=XX
  10. strength=10
  11. name=XX
  12. intelligence=XX
  13. sex=XX
  14. charisma=XX
  15. race=XX
  16. wisdom=XX
  17. class=XX
  18. constitution=XX
  19. >>> 
Jun 3 '07 #5

P: 52
Expand|Select|Wrap|Line Numbers
  1. '%s'='%s'
... is the only thing that I still don't understand. I was without internet for some time, and bored out of my mind I tried to force pyton into telling me what those things did... it wasn't all easy... was rather hard to get the exact __doc__ for write, since it just wrote to the file, instead of giving info... This is what I made when I gave up understanding " '%s'='%s' ":

I'm posting the entire script, so it's rather a lot


Expand|Select|Wrap|Line Numbers
  1.  
  2. sex=raw_input("First, which sex do you want your character to be? ")
  3. name=raw_input('What do you want to call your character? ')
  4.  
  5. import random
  6.  
  7. print ""
  8. print ""
  9.  
  10.     figures=[]
  11.     for n in range(6):
  12.          dice=[random.randint(1,6) for i in range(4)]
  13.          dice.sort()
  14.          d2=dice[1:]
  15.          figures.append(d2[0]+d2[1]+d2[2])
  16.  
  17. print figures
  18.  
  19. print ""
  20.  
  21. print """These are random numbers given by the dice,
  22. you must now chose where to put them.
  23. This will affect your game, and you should bear in mind
  24. what kind of character you want to create."""
  25.  
  26.  
  27. print ""
  28. print ""
  29.  
  30. strength=int(raw_input("""Which one of them will you assign to strength? 
  31. Strength is a measure of muscle, endurance and stamina combined.
  32. Strength affects the ability of characters to lift and carry weights and make effective melee attacks. """))
  33.  
  34. if int(strength) in figures:
  35.     figures.remove(strength)
  36. else:
  37.      print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
  38.      while 1<2:
  39.           print "Cheater!"
  40.           print ""
  41.  
  42. print ""
  43. print ""
  44. print figures
  45. print ""
  46. print ""
  47.  
  48.  
  49. dexterity=int(raw_input("""Which of them will you assign to Dexterity?
  50. Dexterity encompasses a number of physical attributes including
  51. hand-eye coordination, agility, reflexes, fine motor skills,
  52. balance and speed of movement;
  53. a high dexterity score indicates superiority in all these attributes.
  54. Dexterity affects characters with regard to initiative in attack,
  55. the projection of missiles from hand or other means,
  56. and in defensive measures. Dexterity is the ability most influenced by
  57. outside influences (such as armor) """))
  58.  
  59. if int(dexterity) in figures:
  60.      figures.remove(dexterity)
  61. else:
  62.      print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
  63.      while 1<2:
  64.      print "Cheater!"
  65.      print ""
  66.  
  67. print ""
  68. print ""
  69. print figures
  70. print ""
  71. print ""
  72.  
  73.  
  74.  
  75. constitution=int(raw_input("""Which of them will you assign to Constitution?
  76. Constitution is a term which encompasses the character's physique,
  77. toughness, health and resistance to disease and poison.
  78. The higher a character's Constitution, the more hit points
  79. that character will have. Unlike the other ability scores,
  80. which knock the character unconscious when they hit 0,
  81. having 0 Constitution is fatal. """))
  82.  
  83. if int(constitution) in figures:
  84.      figures.remove(constitution)
  85. else:
  86.      print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
  87.      while 1<2:
  88.       print "Cheater!"
  89.       print ""
  90.  
  91.  
  92. print ""
  93. print ""
  94. print figures
  95. print ""
  96. print ""
  97.  
  98.  
  99.  
  100. intelligence=int(raw_input("""Which of them will to assign to Intelligence? 
  101. Intelligence is similar to IQ, but also includes mnemonic ability,
  102. reasoning and learning ability outside those measured by the written word.
  103. Intelligence dictates the number of languages a character
  104. can learn and the number of spells a Wizard may know. """))
  105.  
  106. if int(intelligence) in figures:
  107.      figures.remove(intelligence)
  108. else:
  109.      print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
  110.      while 1<2:
  111.           print "Cheater!"
  112.           print ""
  113.  
  114.  
  115. print ""
  116. print ""
  117. print figures
  118. print ""
  119. print ""
  120.  
  121.  
  122.  
  123. wisdom=int(raw_input("""Which of them will you assign to Wisdom?
  124. Wisdom is a composite term for the characters enlightenment,
  125. judgement, wile, willpower and intuitiveness. """))
  126.  
  127. if int(wisdom) in figures:
  128.      figures.remove(wisdom)
  129. else:
  130.      print "Don't try to cheat! Naughty! Everlasting curses upon thee!!"
  131.      while 1<2:
  132.           print "Cheater!"
  133.           print ""
  134.  
  135.  
  136. print ""
  137. print ""
  138. print figures
  139. print ""
  140. print ""
  141.  
  142.  
  143.  
  144. print "Then the last one will be your character's Charisma."
  145. print """Charisma is the measure of the character's combined physical attractiveness,
  146. persuasiveness, and personal magnetism. A generally non-beautiful character
  147. can have a very high charisma due to strong measures of
  148. the other two aspects of charisma."""
  149. charisma=figures[0]
  150. del figures
  151.  
  152. print ''
  153. print ''
  154. print ''
  155. print ''
  156. print ''
  157. print ''
  158. print ''
  159. print ''
  160. print ''
  161. print ''
  162. print ''
  163. print ''
  164. print ''
  165. print ''
  166. print ''
  167. print ''
  168. print ''
  169. print ''
  170. print ''
  171. print ''
  172. print ''
  173. print ''
  174. print ''
  175. print ''
  176. print ''
  177.  
  178.  
  179. print '....... Physical Traits .......'
  180. print 'strength = %s ' % strength
  181. print 'dexterity = %s ' % dexterity 
  182. print 'constitution = %s ' % constitution
  183. print '....... Mental Traits .......'
  184. print 'intelligence = %s ' % intelligence
  185. print 'charisma = %s ' % charisma  
  186. print 'wisdom = %s ' % wisdom    
  187. print ''
  188.  
  189. if strength in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and dexterity in (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17) and constitution in (11, 12, 13, 14, 15, 16, 17, 18) and charisma in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17):
  190.      print 'You are eligible to be a dwarf.'
  191.  
  192. if dexterity in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and charisma in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17):
  193.      print 'You are eligible to be an elf.'
  194.  
  195. if strength in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
  196.      print 'You are eligilbe to be a gnome.'
  197.  
  198. if dexterity in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
  199.      print 'You are eligilbe to be a half-elf.'
  200.  
  201. if strength in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and dexterity in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and constitution in (10, 11, 12, 13, 14, 15, 16, 17, 18) and intelligence in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) and wisdom in (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17):
  202.      print 'You are eligilbe to be a halfling.'
  203.  
  204. print 'You are eligible to be a human.'
  205.  
  206. print ''
  207.  
  208. race=raw_input('Which race do you want your character to be? ')
  209.  
  210. if race is 'dwarf' or 'Dwarf':
  211.      constitution==constitution+1
  212.      charisma==charisma-1
  213.  
  214. if race is 'elf' or 'Elf':
  215.      dexterity=dexterity+1
  216.      constitution=constitution-1
  217.  
  218. if race is 'gnome' or 'Gnome':
  219.      intelligence=intelligence+1
  220.      wisdom=wisdom-1
  221.  
  222. if race is 'halfling' or 'Halfling':
  223.      dexterity=dexterity+1
  224.      strength=strength-1
  225.  
  226. print ''
  227. print ''
  228. print ''
  229. print ''
  230. print ''
  231. print ''
  232. print ''
  233. print ''
  234. print ''
  235. print ''
  236. print ''
  237. print ''
  238. print ''
  239. print ''
  240. print ''
  241. print ''
  242. print ''
  243. print ''
  244. print ''
  245. print ''
  246. print ''
  247. print ''
  248. print ''
  249. print ''
  250. print ''
  251.  
  252. print "your character's sex is %s" % sex
  253. print "your character's race is %s" % race
  254. print ''
  255. print '....... Physical Traits .......'
  256. print 'strength = %s ' % strength
  257. print 'dexterity = %s ' % dexterity 
  258. print 'constitution = %s ' % constitution
  259. print '....... Mental Traits .......'
  260. print 'intelligence = %s ' % intelligence
  261. print 'charisma = %s ' % charisma  
  262. print 'wisdom = %s ' % wisdom    
  263. print ''
  264.  
  265.  
  266. if strength in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
  267.      print 'you are eligible to be a warrior.'
  268.  
  269. if intelligence in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
  270.      print 'you are eligilbe to be a mage.'
  271.  
  272. if wisdom in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
  273.      print 'you are eligilbe to be a cleric.'
  274.  
  275. if dexterity in (9, 10, 11, 12, 13, 14, 15, 16, 17, 18):
  276.      print 'you are eligilbe to be a thief.'
  277.  
  278. print ''
  279.  
  280.     class1=raw_input('Which class do you want to be? ')
  281.  
  282. print ''
  283. print ''
  284. print ''
  285. print ''
  286. print ''
  287. print ''
  288. print ''
  289. print ''
  290. print ''
  291. print ''
  292. print ''
  293. print ''
  294. print ''
  295. print ''
  296. print ''
  297. print ''
  298. print ''
  299. print ''
  300. print ''
  301. print ''
  302. print ''
  303. print ''
  304. print ''
  305. print '--------------------------------------'
  306. print "Your character's sex is: %s" % sex
  307. print "Your character's name is: %s" % name
  308. print "Your character's race is: %s" % race
  309. print "Your character's class is: %s" % class1
  310. print '--------------------------------------'
  311. print '....... Physical Traits .......'
  312. print 'strength = %s ' % strength
  313. print 'dexterity = %s ' % dexterity 
  314. print 'constitution = %s ' % constitution
  315. print '....... Mental Traits .......'
  316. print 'intelligence = %s ' % intelligence
  317. print 'charisma = %s ' % charisma  
  318. print 'wisdom = %s ' % wisdom
  319. print ''
  320. yes="yes"
  321. name2=raw_input("Now that you know this, do you wish to change your character's name? yes / no. ")
  322.  
  323. if name2==yes:
  324.      name=raw_input(" What do you wish to name your character? ")
  325. else:
  326.      print ''
  327.  
  328.  
  329. print ''
  330. print ''
  331. print ''
  332. print ''
  333. print ''
  334. print ''
  335. print ''
  336. print ''
  337. print ''
  338. print ''
  339. print ''
  340. print ''
  341. print ''
  342. print ''
  343. print ''
  344. print ''
  345. print ''
  346. print ''
  347. print ''
  348. print ''
  349. print ''
  350.  
  351.  
  352. Lawful="Lawful"
  353. Chaotic="Chaotic"
  354. Neutral="Neutral"
  355. Good="Good"
  356. Evil="Evil"
  357. lawful="lawful"
  358. chaotic="chaotic"
  359. neutral="neutral"
  360. good="good"
  361. evil="evil"
  362.  
  363. print '.......... Alignments 1: Law and Chaos .............'
  364. print ''
  365.  
  366.  
  367.  
  368. for n in range(1,50):
  369.      aligninfo=raw_input("You may choose to be Lawful, Neutral or Chaotic. For more information, type in the alignment you want more information about. If you do not want any information and just want to get on with choosing, just press enter. ")
  370.  
  371.  
  372.      if aligninfo==Lawful:
  373.           print ""
  374.           print 'Lawful characters tell the truth, keep their words, respect authority, honor tradition and judge those who fall short of their duties.'
  375.           print ""
  376.           print ""
  377.  
  378.      elif aligninfo==Chaotic:
  379.           print ""
  380.           print 'Chaotic characters follow their consciences, resent being told what to do, favor new ideas over tradition and do what they promise if they feel like it.'
  381.           print ""
  382.           print ""
  383.  
  384.      elif aligninfo==Neutral:
  385.           print ""
  386.           print 'People who are neutral with respect to law and chaos have a normal respect for authority and feel neither a compulsion to obey nor to rebel, they are honest, but can be tempted into lying or decieving others.'
  387.           print ""
  388.           print ""
  389.  
  390.      elif aligninfo==lawful:
  391.           print ""
  392.           print 'Lawful characters tell the truth, keep their words, respect authority, honor tradition and judge those who fall short of their duties.'
  393.           print ""
  394.           print ""
  395.  
  396.      elif aligninfo==chaotic:
  397.           print ""
  398.           print 'Chaotic characters follow their consciences, resent being told what to do, favor new ideas over tradition and do what they promise if they feel like it.'
  399.           print ""
  400.           print ""
  401.  
  402.      elif aligninfo==neutral:
  403.           print ""
  404.           print 'People who are neutral with respect to law and chaos have a normal respect for authority and feel neither a compulsion to obey nor to rebel, they are honest, but can be tempted into lying or decieving others.'
  405.           print ""
  406.           print ""
  407.  
  408.  
  409.      else:
  410.           print ""
  411.           print ""
  412.           break
  413.  
  414. al1=raw_input("Enter the alignment you have chosen. ")
  415. print ""
  416. print "Thank you! Moving on!"
  417.  
  418.  
  419.  
  420.  
  421. print ""
  422. print ""
  423. print ".......... Alignments 2: Good versus Evil .........."
  424. print ""
  425.  
  426.  
  427.  
  428.  
  429. for n in range(1,50):
  430.      aligninfo=raw_input("You may choose to be either Good, Neutral or Evil. If you want some general info on the different alignments; type either Good, Neutral or Evil. If not, simply press enter. ")
  431.  
  432.  
  433.  
  434.      if aligninfo==Good:
  435.           print ""
  436.           print '"Good" implies altruism, respect for life, and a concern for the dignity of sentinent beings. Good characters make personal sacrifises to help others.'
  437.           print ""
  438.           print ""
  439.  
  440.      elif aligninfo==Neutral:
  441.           print ""
  442.           print "People who are neutral with respect to good and evil have compunctions against killing the innocent but lack the commitment to make sacrifices to protect or help others. Neutral people are committed to others through personal relationships. A neutral person may sacrifice himself to protect his family or even his homeland, but he would not do so for strangers who are not related to him."
  443.           print ""
  444.           print ""
  445.  
  446.      elif aligninfo==Evil:
  447.           print ""
  448.           print '"Evil" implies hurting, oppressing and killing others. Some evil creatures simply have no compassion for others and would kill without qualms if doing so is convenient. Others actively pursue evil, killing for sport or out of duty to some evil deity or master'
  449.           print ""
  450.           print ""
  451.  
  452.      elif aligninfo==good:
  453.           print ""
  454.           print '"Good" implies altruism, respect for life, and a concern for the dignity of sentinent beings. Good characters make personal sacrifises to help others.'
  455.           print ""
  456.           print ""
  457.  
  458.      elif aligninfo==neutral:
  459.           print ""
  460.           print "People who are neutral with respect to good and evil have compunctions against killing the innocent but lack the commitment to make sacrifices to protect or help others. Neutral people are committed to others through personal relationships. A neutral person may sacrifice himself to protect his family or even his homeland, but he would not do so for strangers who are not related to him."
  461.           print ""
  462.           print ""
  463.  
  464.      elif aligninfo==evil:
  465.           print ""
  466.           print '"Evil" implies hurting, oppressing and killing others. Some evil creatures simply have no compassion for others and would kill without qualms if doing so is convenient. Others actively pursue evil, killing for sport or out of duty to some evil deity or master'
  467.           print ""
  468.           print ""
  469.  
  470.      else:
  471.           print ""
  472.           print ""
  473.           break
  474.  
  475. al2=raw_input("Type the alignment which you have chosen. ")
  476. print ""
  477. print ""
  478. print ""
  479.  
  480.  
  481.  
  482.  
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491. print ''
  492. print ''
  493. print ''
  494. print ''
  495. print 'Congratulations, you have successfully created a dungeons and dragons character.'
  496. print '--------------------------------------'
  497. print "Your character's sex is: %s" % sex
  498. print "Your character's name is: %s" % name
  499. print "Your character's race is: %s" % race
  500. print "Your character's class is: %s" % class1
  501. print '--------------------------------------'
  502. print '....... Physical Traits .......'
  503. print 'strength = %s ' % strength
  504. print 'dexterity = %s ' % dexterity 
  505. print 'constitution = %s ' % constitution
  506. print '....... Mental Traits .......'
  507. print 'intelligence = %s ' % intelligence
  508. print 'charisma = %s ' % charisma  
  509. print 'wisdom = %s ' % wisdom
  510. print '--------------------------------------'
  511. print 'Alignment:' , al1 , al2
  512. print ''
  513. print ''
  514. print ''
  515.  
  516.  
  517.  
  518.  
  519.  
  520. fn=r'c:\programfiler\python script\characters.txt'
  521. outlist=[name,sex,race,class1,strength,dexterity,constitution,intelligence,charisma,wisdom,(al1+" "+al2)]
  522. stuff=["Name","Sex","Race","Class","Strength","Dexterity","Constitution","Intelligence","Charisma","Wisdom","Alignment"]
  523. finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff))]
  524. f=open(fn,'a')
  525. f.write('\n'.join(finallist))
  526. f.close()
  527.  
  528.  
  529. fn=r'c:\programfiler\python script\characters.txt'
  530. f=open(fn,'a')
  531. f.write('\n'.join('\n'))
  532. f.close()
  533.  
  534.  
  535.  
  536. fn=r'c:\programfiler\python script\characters.txt'
  537. f=open(fn,'a')
  538. f.write('\n'.join('\n'))
  539. f.close()
  540.  
  541.  
  542. fn=r'c:\programfiler\python script\characters.txt'
  543. f=open(fn,'a')
  544. f.write('\n'.join('\n'))
  545. f.close()
  546.  
  547.  
  548.  
  549.  
  550.  
  551.  
  552.  
  553. for n in range(20):
  554.      if strength is n:
  555.           strength=str(n)
  556.  
  557.      if dexterity is n:
  558.           dexterity=str(n)
  559.  
  560.      if constitution is n:
  561.           constitution=str(n)
  562.  
  563.      if intelligence is n:
  564.           intelligence=str(n)
  565.  
  566.      if wisdom is n:
  567.           wisdom=str(n)
  568.  
  569.      if charisma is n:
  570.           charisma=str(n)
  571.  
  572.  
  573.  
  574.  
  575.  
  576.  
  577.  
  578.  
  579. fn=r'c:\programfiler\python script\character-pro.txt'
  580.  
  581.  
  582. f=open(fn, 'a')
  583. f.write('\n'.join('\n'))
  584. f.close()
  585.  
  586. f=open(fn, 'a')
  587. f.write("--------------------------------")
  588. f.close()
  589.  
  590. f=open(fn, 'a')
  591. f.write('\n'.join('\n'))
  592. f.close()
  593.  
  594. f=open(fn, 'a')
  595. f.write("This character's name is: ")
  596. f.close()
  597.  
  598.  
  599. f=open(fn, 'a')
  600. f.write(name)
  601. f.close()
  602.  
  603.  
  604. f=open(fn, 'a')
  605. f.write('\n'.join('\n'))
  606. f.close()
  607.  
  608.  
  609. f=open(fn, 'a')
  610. f.write("It is a: ")
  611. f.close()
  612.  
  613.  
  614. f=open(fn, 'a')
  615. f.write(race)
  616. f.close()
  617.  
  618.  
  619. f=open(fn, 'a')
  620. f.write('\n'.join('\n'))
  621. f.close()
  622.  
  623. f=open(fn, 'a')
  624. f.write("It's sex is: ")
  625. f.close()
  626.  
  627.  
  628. f=open(fn, 'a')
  629. f.write(sex)
  630. f.close()
  631.  
  632.  
  633. f=open(fn, 'a')
  634. f.write('\n'.join('\n'))
  635. f.close()
  636.  
  637.  
  638. if sex=="female":
  639.  
  640.  
  641.      f=open(fn, 'a')
  642.      f.write("She is a: ")
  643.      f.close()
  644.  
  645.  
  646.      f=open(fn, 'a')
  647.      f.write(class1)
  648.      f.close()
  649.  
  650.  
  651. elif sex=="Female":
  652.  
  653.  
  654.      f=open(fn, 'a')
  655.      f.write("She is a: ")
  656.      f.close()
  657.  
  658.  
  659.      f=open(fn, 'a')
  660.      f.write(class1)
  661.      f.close()
  662.  
  663.  
  664. elif sex=="male":
  665.  
  666.  
  667.      f=open(fn, 'a')
  668.      f.write("He is a: ")
  669.      f.close()
  670.  
  671.  
  672.      f=open(fn, 'a')
  673.      f.write(class1)
  674.      f.close()
  675.  
  676.  
  677. elif sex=="Male":
  678.  
  679.  
  680.      f=open(fn, 'a')
  681.      f.write("He is a: ")
  682.      f.close()
  683.  
  684.  
  685.      f=open(fn, 'a')
  686.      f.write(class1)
  687.      f.close()
  688.  
  689.  
  690. f=open(fn, 'a')
  691. f.write('\n'.join('\n'))
  692. f.close()
  693.  
  694.  
  695. f=open(fn, 'a')
  696. f.write("--------------------------------")
  697. f.close()
  698.  
  699.  
  700. f=open(fn, 'a')
  701. f.write('\n'.join('\n'))
  702. f.close()
  703.  
  704.  
  705. f=open(fn, 'a')
  706. f.write("....... Physical Traits .......")
  707. f.close()
  708.  
  709.  
  710. f=open(fn, 'a')
  711. f.write('\n'.join('\n'))
  712. f.close()
  713.  
  714.  
  715. f=open(fn, 'a')
  716. f.write("Strength: ")
  717. f.close()
  718.  
  719.  
  720. f=open(fn, 'a')
  721. f.write(strength)
  722. f.close()
  723.  
  724.  
  725. f=open(fn, 'a')
  726. f.write('\n'.join('\n'))
  727. f.close()
  728.  
  729.  
  730. f=open(fn, 'a')
  731. f.write("Dexterity: ")
  732. f.close()
  733.  
  734.  
  735. f=open(fn, 'a')
  736. f.write(dexterity)
  737. f.close()
  738.  
  739.  
  740. f=open(fn, 'a')
  741. f.write('\n'.join('\n'))
  742. f.close()
  743.  
  744.  
  745. f=open(fn, 'a')
  746. f.write("Constitution: ")
  747. f.close()
  748.  
  749.  
  750. f=open(fn, 'a')
  751. f.write(constitution)
  752. f.close()
  753.  
  754.  
  755. f=open(fn, 'a')
  756. f.write('\n'.join('\n'))
  757. f.close()
  758.  
  759.  
  760. f=open(fn, 'a')
  761. f.write("........ Mental Traits ........")
  762. f.close()
  763.  
  764.  
  765. f=open(fn, 'a')
  766. f.write('\n'.join('\n'))
  767. f.close()
  768.  
  769.  
  770. f=open(fn, 'a')
  771. f.write("Intelligence: ")
  772. f.close()
  773.  
  774.  
  775. f=open(fn, 'a')
  776. f.write(intelligence)
  777. f.close()
  778.  
  779.  
  780. f=open(fn, 'a')
  781. f.write('\n'.join('\n'))
  782. f.close()
  783.  
  784.  
  785. f=open(fn, 'a')
  786. f.write("Charisma: ")
  787. f.close()
  788.  
  789.  
  790. f=open(fn, 'a')
  791. f.write(charisma)
  792. f.close()
  793.  
  794.  
  795. f=open(fn, 'a')
  796. f.write('\n'.join('\n'))
  797. f.close()
  798.  
  799.  
  800. f=open(fn, 'a')
  801. f.write("Wisdom: ")
  802. f.close()
  803.  
  804.  
  805. f=open(fn, 'a')
  806. f.write(wisdom)
  807. f.close()
  808.  
  809.  
  810. f=open(fn, 'a')
  811. f.write('\n'.join('\n'))
  812. f.close()
  813.  
  814.  
  815. f=open(fn, 'a')
  816. f.write("--------------------------------")
  817. f.close()
  818.  
  819.  
  820. f=open(fn, 'a')
  821. f.write('\n'.join('\n'))
  822. f.close()
  823.  
  824.  
  825. f=open(fn, 'a')
  826. f.write("Alignment: ")
  827. f.close()
  828.  
  829.  
  830. f=open(fn, 'a')
  831. f.write(al1)
  832. f.close()
  833.  
  834.  
  835. f=open(fn, 'a')
  836. f.write(" ")
  837. f.close()
  838.  
  839.  
  840. f=open(fn, 'a')
  841. f.write(al2)
  842. f.close()
  843.  
  844.  
  845. f=open(fn, 'a')
  846. f.write('\n'.join('\n'))
  847. f.close()
  848.  
  849.  
  850. f=open(fn, 'a')
  851. f.write('\n'.join('\n'))
  852. f.close()
  853.  
  854.  
  855. f=open(fn, 'a')
  856. f.write('\n'.join('\n'))
  857. f.close()
  858.  
  859.  
  860. raw_input("You are finished! To quit this character-creator; press enter.")
  861.  
  862.  

I'm sorry for the lack of comments. It is a dice-based game, and this is a program for creating characters. I do not think the rules need be explained. The problem is the lower half, which I expect is vastly useless, and can be written in much shorter ways...
Jun 5 '07 #6

P: 52
Expand|Select|Wrap|Line Numbers
  1. '%s'='%s'

... is the only thing that I still don't understand. I was without internet for some time, and bored out of my mind I tried to force pyton into telling me what those things did... it wasn't all easy... was rather hard to get the exact __doc__ for write, since it just wrote to the file, instead of giving info... This is what I made when I gave up understanding " '%s'='%s' ":

I'm posting the entire script, so it's rather a lot


I'm sorry for the lack of comments. It is a dice-based game, and this is a program for creating characters. I do not think the rules need be explained. The problem is the lower half, which I expect is vastly useless, and can be written in much shorter ways...

And of course it doesn't allow me... I'll post it as a .txt file in case anyone of you are interested...
Attached Files
File Type: txt DungeonsAndDragons.txt (19.1 KB, 315 views)
Jun 5 '07 #7

ilikepython
Expert 100+
P: 844
Expand|Select|Wrap|Line Numbers
  1. '%s'='%s'

... is the only thing that I still don't understand. I was without internet for some time, and bored out of my mind I tried to force pyton into telling me what those things did... it wasn't all easy... was rather hard to get the exact __doc__ for write, since it just wrote to the file, instead of giving info... This is what I made when I gave up understanding " '%s'='%s' ":

I'm posting the entire script, so it's rather a lot


I'm sorry for the lack of comments. It is a dice-based game, and this is a program for creating characters. I do not think the rules need be explained. The problem is the lower half, which I expect is vastly useless, and can be written in much shorter ways...

And of course it doesn't allow me... I'll post it as a .txt file in case anyone of you are interested...
"%s = %s" just means string formatting. You need to specify some strings after the last quote using the percent:
print "'%s' = '%s'" % ("strenght", "4")
That would print:
"strength = 4"

Also, you have an open() and close() call for every call to write(). You only need to open and close the file once.
Jun 5 '07 #8

P: 52

Also, you have an open() and close() call for every call to write(). You only need to open and close the file once.
Nope, I definitively do need to do it every bloody time, otherwise it claims that I haven't defined f... I know it should work without it, but it just doesn't...


*edit*= I found that by changing the f=open(fn,'a') into f=file(fn,'a'), I could write several times without having to close and redefine f...
Jun 5 '07 #9

Smygis
100+
P: 126
Nope, I definitively do need to do it every bloody time, otherwise it claims that I haven't defined f... I know it should work without it, but it just doesn't...


*edit*= I found that by changing the f=open(fn,'a') into f=file(fn,'a'), I could write several times without having to close and redefine f...
A lot of things:
Expand|Select|Wrap|Line Numbers
  1. if race is 'dwarf' or 'Dwarf':
Is not what you want.
Expand|Select|Wrap|Line Numbers
  1. if race in ('dwarf', 'Dwarf'):
Is what you want.

and if your realy clever, You use:

Expand|Select|Wrap|Line Numbers
  1. if race.lower() == 'dwarf':
Then "dWaRF" would also be true.

And in the dwarf sction you got:
Expand|Select|Wrap|Line Numbers
  1. constitution==constitution+1
Thats bad. As you can se you are using the == operator.

Preferably you shuld use the += operator.

Expand|Select|Wrap|Line Numbers
  1. constitution += 1

And your fine:
Expand|Select|Wrap|Line Numbers
  1. strength in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
Looks realy bad.
you can use the "in between" construction:

Expand|Select|Wrap|Line Numbers
  1. if 7 <= strength <= 18:
and as you use:
Expand|Select|Wrap|Line Numbers
  1. print ''
  2. print ''
  3. print ''
  4. print ''
  5. print ''
  6. print ''
  7. print ''
  8. print ''
  9. print ''
  10. print ''
  11. print ''
  12. print ''
  13. print ''
  14. print ''
  15. print ''
  16. print ''
  17. print ''
  18. print ''
  19. print ''
  20. print ''
  21. print ''
  22. print ''
  23. print ''
  24.  
A lot.

It be good if you did something like:
Expand|Select|Wrap|Line Numbers
  1. newlines = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  2. # And then when you want a lot of newlines:
  3. print newlines
  4.  
And the print statements always (unless you use ",") end with a linebreak.
so:
Expand|Select|Wrap|Line Numbers
  1. print ''
  2. # and
  3. print
  4.  
do the same thing.

And if you want to use:
Expand|Select|Wrap|Line Numbers
  1. while 1<2:
  2. # a statement that is alwas true. Use:
  3. while True:
  4.  
And you dont need:
Expand|Select|Wrap|Line Numbers
  1. if int(wisdom) in figures:
  2. #when its already an int. Do:
  3. if wisdom in figures:
  4.  

Keep it up ;)
you can only get better.
Jun 5 '07 #10

bvdet
Expert Mod 2.5K+
P: 2,851
You can also print multiple new lines this way:
Expand|Select|Wrap|Line Numbers
  1. >>> print '\n'*8
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11. >>> 
This works for any character or string.
Jun 5 '07 #11

bvdet
Expert Mod 2.5K+
P: 2,851
Nope, I definitively do need to do it every bloody time, otherwise it claims that I haven't defined f... I know it should work without it, but it just doesn't...


*edit*= I found that by changing the f=open(fn,'a') into f=file(fn,'a'), I could write several times without having to close and redefine f...
Instead of doing this:
Expand|Select|Wrap|Line Numbers
  1. fn=r'c:\programfiler\python script\characters.txt'
  2. outlist=[name,sex,race,class1,strength,dexterity,constitution,intelligence,charisma,wisdom,(al1+" "+al2)]
  3. stuff=["Name","Sex","Race","Class","Strength","Dexterity","Constitution","Intelligence","Charisma","Wisdom","Alignment"]
  4. finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff))]
  5.  
  6. f=open(fn,'a')
  7. f.write('\n'.join(finallist))
  8. f.close()
  9.  
  10.  
  11. fn=r'c:\programfiler\python script\characters.txt'
  12. f=open(fn,'a')
  13. f.write('\n'.join('\n'))
  14. f.close()
You can do this:
Expand|Select|Wrap|Line Numbers
  1. fn=r'c:\programfiler\python script\characters.txt'
  2. outlist=[name,sex,race,class1,strength,dexterity,constitution,intelligence,charisma,wisdom,(al1+" "+al2)]
  3. stuff=["Name","Sex","Race","Class","Strength","Dexterity","Constitution","Intelligence","Charisma","Wisdom","Alignment"]
  4. finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff))]
  5.  
  6. f = open(fn,'a') # open a file in append mode, create the file if it does not exist
  7. f.write('\n'.join(finallist))
  8. f.write('\n')
  9. ...do other stuff...
  10.  
  11. f.write('\nsome string\n')
  12. f.writelines([s1, s1,s3]) # this writes a list of strings
  13. f.close()
  14.  
There is no difference in the use of open() and file(). From Python docs:
The file() constructor is new in Python 2.2. The previous spelling, open(), is retained for compatibility, and is an alias for file().
Jun 5 '07 #12

P: 52
Instead of doing this:
Expand|Select|Wrap|Line Numbers
  1. fn=r'c:\programfiler\python script\characters.txt'
  2. outlist=[name,sex,race,class1,strength,dexterity,constitution,intelligence,charisma,wisdom,(al1+" "+al2)]
  3. stuff=["Name","Sex","Race","Class","Strength","Dexterity","Constitution","Intelligence","Charisma","Wisdom","Alignment"]
  4. finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff))]
  5.  
  6. f=open(fn,'a')
  7. f.write('\n'.join(finallist))
  8. f.close()
  9.  
  10.  
  11. fn=r'c:\programfiler\python script\characters.txt'
  12. f=open(fn,'a')
  13. f.write('\n'.join('\n'))
  14. f.close()
You can do this:
Expand|Select|Wrap|Line Numbers
  1. fn=r'c:\programfiler\python script\characters.txt'
  2. outlist=[name,sex,race,class1,strength,dexterity,constitution,intelligence,charisma,wisdom,(al1+" "+al2)]
  3. stuff=["Name","Sex","Race","Class","Strength","Dexterity","Constitution","Intelligence","Charisma","Wisdom","Alignment"]
  4. finallist=['%s=%s' % (stuff[n],outlist[n]) for n in range(len(stuff))]
  5.  
  6. f = open(fn,'a') # open a file in append mode, create the file if it does not exist
  7. f.write('\n'.join(finallist))
  8. f.write('\n')
  9. ...do other stuff...
  10.  
  11. f.write('\nsome string\n')
  12. f.writelines([s1, s1,s3]) # this writes a list of strings
  13. f.close()
  14.  
There is no difference in the use of open() and file(). From Python docs:
The file() constructor is new in Python 2.2. The previous spelling, open(), is retained for compatibility, and is an alias for file().

Well obviously there is some difference, for when I did the
Expand|Select|Wrap|Line Numbers
  1. "f = open(fn,'a') # open a file in append mode, create the file if it does not exist
  2. f.write('\n'.join(finallist))
  3. f.write('\n')
  4. ...do other stuff...
  5.  
  6. f.write('\nsome string\n')"
  7.  
  8.  
thing, it gave me the error message "Line 'something', f.write(Some stuff)
f not specified

but when I specified f at every line, like this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. f=open(fn, 'a')
  3. f.write(some stuff)
  4. f.close()
  5.  
  6. f=open(fn, 'a')
  7. f.write(some other stuff)
  8. f.close()
  9.  
  10.  
It worked perfectly, it was just annoying. When I spedified f as:

Expand|Select|Wrap|Line Numbers
  1. f=file(fn, 'a')
  2.  
It didn't have to be specified and closed every time... Maybe my version is just buggy and glitchy, but whatever the reason, that is the way it is for me.
Jun 6 '07 #13

P: 52
A lot of things:
Expand|Select|Wrap|Line Numbers
  1. if race is 'dwarf' or 'Dwarf':
Is not what you want.
Expand|Select|Wrap|Line Numbers
  1. if race in ('dwarf', 'Dwarf'):
Is what you want.

and if your realy clever, You use:

Expand|Select|Wrap|Line Numbers
  1. if race.lower() == 'dwarf':
Then "dWaRF" would also be true.

And in the dwarf sction you got:
Expand|Select|Wrap|Line Numbers
  1. constitution==constitution+1
Thats bad. As you can se you are using the == operator.

Preferably you shuld use the += operator.

Expand|Select|Wrap|Line Numbers
  1. constitution += 1

And your fine:
Expand|Select|Wrap|Line Numbers
  1. strength in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)
Looks realy bad.
you can use the "in between" construction:

Expand|Select|Wrap|Line Numbers
  1. if 7 <= strength <= 18:
and as you use:
Expand|Select|Wrap|Line Numbers
  1. print ''
  2. print ''
  3. print ''
  4. print ''
  5. print ''
  6. print ''
  7. print ''
  8. print ''
  9. print ''
  10. print ''
  11. print ''
  12. print ''
  13. print ''
  14. print ''
  15. print ''
  16. print ''
  17. print ''
  18. print ''
  19. print ''
  20. print ''
  21. print ''
  22. print ''
  23. print ''
  24.  
A lot.

It be good if you did something like:
Expand|Select|Wrap|Line Numbers
  1. newlines = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  2. # And then when you want a lot of newlines:
  3. print newlines
  4.  
And the print statements always (unless you use ",") end with a linebreak.
so:
Expand|Select|Wrap|Line Numbers
  1. print ''
  2. # and
  3. print
  4.  
do the same thing.

And if you want to use:
Expand|Select|Wrap|Line Numbers
  1. while 1<2:
  2. # a statement that is alwas true. Use:
  3. while True:
  4.  
And you dont need:
Expand|Select|Wrap|Line Numbers
  1. if int(wisdom) in figures:
  2. #when its already an int. Do:
  3. if wisdom in figures:
  4.  

Keep it up ;)
you can only get better.
Basically all of that was not made by me, and the int(wisdom) was done just because I knew it would work, and was tired of testing the entire script for every addition. The newlines="\n\n\n\n\n\n\n" was quite smart though, I shall have to remember that.

As for the operator +=... I've never seen it before, neither the race.lower()...

But thanks! You should talk to some admin or whatever and make them change the "newbie" there... It really doesn't suit you :P
Jun 6 '07 #14

P: 52
You can also print multiple new lines this way:
Expand|Select|Wrap|Line Numbers
  1. >>> print '\n'*8
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11. >>> 
This works for any character or string.
Thanks, I was kinda wondering about that... never "dared" try it tho :P
Jun 6 '07 #15

P: 52
And instead of %s, couldn't I just have used str()?
That wouldn't confuse me as much :D
Jun 6 '07 #16

bvdet
Expert Mod 2.5K+
P: 2,851
And instead of %s, couldn't I just have used str()?
That wouldn't confuse me as much :D
Sure, but if you want to learn Python, you should learn how to use the string format operator '%'. Here's an example:
Expand|Select|Wrap|Line Numbers
  1. >>> print 'The first number is', 12, 'and the second number is', 44.5689
  2. The first number is 12 and the second number is 44.5689
  3. >>> s = 'The first number is ' + str(12) + ' and the second number is ' + str(44.5689)
  4. >>> print s
  5. The first number is 12 and the second number is 44.5689
  6. >>> s = 'The first number is %s and the second number is %s' % (12,44.5689)
  7. >>> s
  8. 'The first number is 12 and the second number is 44.5689'
  9. >>> 
Jun 6 '07 #17

Post your reply

Sign in to post your reply or Sign up for a free account.