Python Forum
new and looking for specific type of help
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
new and looking for specific type of help
#1
so, the general request for this thread is for other coder's to expound upon the code and comments which i will include below. i am teaching myself py3X, and i am hoping to learn in a specific way. the way i wish to learn is through examples of code which contain comments explaining every piece of the code as it happens, and what each piece does. the point of this method is to give a better understanding of what statements and commands and operand's in general do.
i have read many tutorials and watched many videos and read much documentation on this particular language. through all of my research and practice i have noticed a common theme among them which makes learning the code, without a teacher, very hard. the theme is that either the tutorial will show me what to do without explaining why each piece is doing these things, or the code will explain each piece without showing how it is used, or it will do both, but it will only show a single use for the snippet of code, and leaves many versatile uses and variations of the code unexplained.
so i have written a small block of code with an example of what i am trying to ask people to do. please feel free to re-write the code i post more efficiently, please change the comments to more properly explain the actual uses and applications of the parts of the code, and please add to the code and the comments, while explaining what is happening and why.i also ask for fellow coder's of more experience to show multiple uses of a single type or snippet of code. i know it seems strange, but so far this has been my most effective for of learning.

this is the sample of what i am looking for, written by me.
# imports and from are used to reference tools from libraries and documents
# to be used in your program.
# import references another document directly.
# from references blocks of code based on class name within the document.
import sys
import time
from time import sleep
import math
from math import pi
import random
from random import randint
from datetime import datetime

# Variables are strings, ints, floats, bytes, bools, and other values
# assigned to a chosen codeword in the form of Variable = ('content')
now = datetime.now()
print(datetime.now())
print(now)
#the sleep command pauses the program and "sleeps" it for the time specified
sleep(1)
#opening and character name
#input is a function that allows a user to choose their own return of a variable.
#print is a function that tells the computer what to display.
maincharname = input("please tell us your name? ")
#the command statement .upper or .lower annotate the case of the string being printed.
#if .upper() the words or string will be translated to UPPERCASE
#if .lower() the string or word\'s will be translated to lowercase.
#using [0] or [1:] as an arguement allows the programmer to choose specific letter ranges within a string to be translated to the chosen case sensitivity. 
print ("nice to meet you " + maincharname[0].upper()+maincharname[1:].lower())
#while is a command that allows the programmer to assign code blocks to only run
#within the limitations of a while loop.
#class choice
classChoice = 0
#the while loop here uses the variable "classChoice" to choose whether to display the if statements below.
while classChoice <= 0:
    classChoiceInput = input("would you like to play a fighter, a rogue,  or a mage?")
#if is a command that tells the computer to do something "if" a set limitation is met by the user.
#the variable "classChoiceInput" is created for the if and elif statements to determine the input
#and decide whether to replay the loop or start the next block of code
#by using the input to change the true or false value of the while loop boolean by changing the value of "class Choice"
    if classChoiceInput.lower() == "fighter":
        print("You wish to play a fighter!")
        classChoice = 1
#elif is short for "else if" allowing more than one "if" statement in a block.
    elif classChoiceInput.lower() == "rogue":
        print("you wish to play a rogue!")
        classChoice = 2
    elif classChoiceInput.lower() == "mage":
        print("you wish to play a mage!")
        classChoice = 3
#else is a command that tells the computer what to do when none of the "if" limitations are met.
#using a \ under a ' is escaping a ' apostrophy so the ' does not end your variables string content
    else:
        print("well isn\'t it exciting, how about one from the list?")

    
print("what would you like your weapon to be?")

#weapon selection
charweapon = 0
while charweapon <= 0:
    maincharweapon = input("What do you choose to weild?\nSword? Staff? Shield?")

    if maincharweapon.lower() == "sword":
        print("Valiant Warrior, you have choosen the Blade!")
        charweapon = 1
    elif maincharweapon.lower() == "staff":
        print("Wise Adventurer, You have choosen the Sceptre!")
        charweapon = 2
    elif maincharweapon.lower() == "sheild":
        print("Bold Defender, you have choosen the Bulwark!")
        charweapon = 3
    else:
        print("Whaddaya want from us? a gun?!?")


print("Done.")
print("If you can count to 15 in three\'s, this game is over.")

# "for" and "in" are a numerical loop command used to create a scaling number system or an axis plane. 

for i in range (0,16,3):
   print(i)

''' Can you help me write this code and label as i have,
explaining just about every function method variable and what they do,
also trying to explain how they work together. all the tutorials and classes are cool and they work
because i have made this understanding but im trying to make my own hands on reference code, so for just about every program i make,
i can pull from my stock program which is fully build in comment tutorial to how it works.
probably going to be more than one script with some kind of references in comments showing where ones connect to others'''

i learned this method of learning coding from "learning python the hard way" however my copy is rather old 2nd edition and uses py2.7 i think or an earlier version even, not sure, and i am trying to lean python-3.X

feel free to arbitrarily add random sh** that might be useful.
Reply
#2
Basically, what you are asking for is to duplicate what is already contained in the Python Documentation. Probably an unintended mistake on your part was to try and learn from "Learning Python The Hard Way", for which you will find no fans for either the book or it's author on this forum.  Most books, tutorials, videos, etc. are geared for general knowledge and application, so no, you will seldom find one that goes "in depth".  There just isn't time or space to do this.  That's not to say the information doesn't exist, you just need to spend a little time looking for it.  A good site is Packt Publishing, which offers free downloads (in various formats) of some of the books they publish, including Python.  We also offer a list of resources on the form:Python Resources.

Is there a be all to end all resource out there...no.  Sometimes, the journey is more enjoyable than the destination.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
i see your point, and i understand the lack of fandom, most especially for an outdated version of the book. i have been hunting many tutorials and i will look into your links, what i am asking for is not the same as the python documentation, because as stated above, the documentation on the python website, while it does explain each individual part in detail, it incredibly lacks on the usage of them together in a comprehensible way, and lacks example, think of it less as work to re write what is written, and more of a fun project to write new code and label it in terms more understandable, also im not asking to repeat the textbook to me... im asking to explain the usage of what the documentation explains through showing the example and explaining as it goes, i somewhat expect functional code with explanations embedded. the documentation explains individual parts but lacks cohesion, the tutorials explain cohesion but without defining individual part, and even if they do, they only give single, or limited uses of these statements, which i have seen to be much more versitile, but with no explanation of how that versatility works. im not asking you to parrot things. im asking everyone to help me explain as we go, instead of just explaining, or just going, like 995 of the tutorials and documentations tend to do. so far out of literally over 30 tutorials and different resources of documentation, i have found ONE that comes close to what i am looking for. it is at http://anh.cs.luc.edu/handsonPythonTutorial/idle.html lines 0-39. but even that feels somewhat lacking and could be better explained as embedded comments like my example above shows.

also i want to say that group discussion and group efforts towards creating this type of "master code" (if you will) could help more than just me, find new ways and methods of understanding and applying code. it is not only for me, do i make this request. and i do want to volunteer to be an active participant in this. i will carry a shovel and dig the dirt. please do not put me in a high chair for a spoon feeding. it is not my intent. i apologize if i seem rude, i do not intend to be a waste of time.

i demand a shrubber!

maybe i am a poor salesman, but i believe in my product. if anything it will help your website compile its own documentation, open source, which would be more human comprehensible than any other in existence. like a group writing a thesaurus for a dictionary which contains no grammar. and a good source of public snippets, complete with embedded explanations. revolutionary. now may i ask what more question?

WHAT IS YOUR FAVORITE COLOR?!
Reply
#4
Is part of this code a conversion of: https://processing.org/examples/datatypeconversion.html ?
Reply
#5
#the size of the display is set here by naming the built in function "size" and
#setting the parameters of the resolution within the () separated by a comma
#to distinguish the difference between the x and y axis
#common size resolutions are (800, 600) (1280,720) (1600, 900)
size(640, 360);
#the background function sets...??? care to finish?
#it seems a bit beyond my reach, as of yet. it is like writing a public text book though.
background(0);
noStroke();
# i dont know what createFont is or how to use it. is SourceCodePro-Regular.ttf something that comes standard in the py library?
#or do i need to download the Qt library? maybe scintilla? or autopygui or pygame to use that particular ttf file?
textFont(createFont("SourceCodePro-Regular.ttf",24));
Reply
#6
http://anh.cs.luc.edu/handsonPythonTutorial/idle.html

a tutorial i am working from. it works similarly what i am trying to show, but not quite the same.
this is their example
#! /usr/bin/env python3                                  
'''                                                      
String Substitution for a Mad Lib                        
Adapted from code by Kirby Urner                         
'''                                                      
                                                         
storyFormat = '''                                        
Once upon a time, deep in an ancient jungle,             
there lived a {animal}.  This {animal}                   
liked to eat {food}, but the jungle had                  
very little {food} to offer.  One day, an               
explorer found the {animal} and discovered              
it liked {food}.  The explorer took the                 
{animal} back to {city}, where it could                 
eat as much {food} as it wanted.  However,              
the {animal} became homesick, so the                    
explorer brought it back to the jungle,                 
leaving a large supply of {food}.                       
                                                        
The End                                                 
'''                                                     
                                                        
def tellStory():                                        
    userPicks = dict()                                  
    addPick('animal', userPicks)                        
    addPick('food', userPicks)                          
    addPick('city', userPicks)                          
    story = storyFormat.format(**userPicks)             
    print(story)                                        
                                                        
def addPick(cue, dictionary):                           
    '''Prompt for a user response using the cue string, 
    and place the cue-response pair in the dictionary.  
    '''                                                 
    prompt = 'Enter an example for ' + cue + ': '       
    response = input(prompt)                            
    dictionary[cue] = response                          
                                                        
tellStory()                                             
input('Press Enter to end the program.')                
this is my example

'''
string substitution
'''
#assinging the string storyFormat is the core text of our story. the
#curly braces around certain words within the text are eventually going to be
#chosen by the user and changed in the story by auto writing
#their values into a dictionary, based on user input upon promt
storyFormat = '''
So one day theres this {person} right? aaand this {person} love to eat {food}.
and the {person} was broke in the {hood}. ya see {the man} was
keeping the {person} down. so the {person} wanted to escape the {hood} and
get back to the{wild} where he was free of {the man}.
'''
#def is short for definition. In this case we are defining a series of strings
#and variables which allow the strings to be altered later in the code
def tellStory ():
    userPicks = dict()
    addPick('person' , userPicks)
    addPick('the man' , userPicks)
    addPick('hood' , userPicks)
    addPick('wild' , userPicks)
    story = storyFormat.format(**userPicks)
    print (story)
#cue and dictionary in the definition addPick, are a tuple, where as tellStory
#allows you to choose which tuple is used by leaving it blank
def addPick(cue, dictionary):
#prompt is created to know what to ask the user to input and then
#adding response is the part that does the asking
#to the prompts for hood,the man, person, and wild,
#which will be added into the dictionary because of, def tellStory, above
    prompt = 'enter an example for ' + cue +': '
    response = input(prompt)
    dictionary[cue] = response
tellStory()
input('Press Enter to end the program')
mine is giving back a traceback error, can you help me label the rest of it so i can find the error? i have been comparing them, and tried multiple things. i am confused as to what is wrong with mine.

'''
string substitution
'''
#assinging the string storyFormat is the core text of our story. the
#curly braces around certain words within the text are eventually going to be
#chosen by the user and changed in the story by auto writing
#their values into a dictionary, based on user input upon prompt

storyFormat = '''
So one day theres this {person} right? aaand this {person} love to eat {food}.
and the {person} was broke in the {hood}. ya see {the man} was
keeping the {person} down. so the {person} wanted to escape the {hood} and
get back to the{wild} where he was free of {the man}.
'''
#def is short for definition. In this case we are defining a series of strings
#and variables which allow the strings to be altered later in the code
def tellStory ():
    userPicks = dict()
#make sure you add a new pick option for every object in the string above, or you may have traceback error
    addPick('person' , userPicks)
    addPick('the man' , userPicks)
    addPick('hood' , userPicks)
    addPick('wild' , userPicks)
    addPick('food' , userPicks)
    story = storyFormat.format(**userPicks)
    print (story)
#cue and dictionary in the definition addPick, are a tuple, where as tellStory
#allows you to choose which tuple is used by leaving it blank
def addPick(cue, dictionary):
#prompt is created to know what to ask the user to input and then
#adding response is the part that does the asking
#to the prompts for hood,the man, person, and wild,
#which will be added into the dictionary because of, def tellStory, above
    prompt = 'enter an example for ' + cue +': '
    response = input(prompt)
    dictionary[cue] = response
tellStory()
input('Press Enter to end the program')
Reply
#7
(Aug-29-2017, 05:54 PM)Larz60+ Wrote: Is part of this code a conversion of: https://processing.org/examples/datatypeconversion.html ?

also i dont what khat language that is, but it looks like c#, ive been through processing.org and most of it uses void alot. py3 doesnt have void, i dont know what language that is in.
Reply
#8
That is 'C' but has verbatim comments as in your code.
Reply
#9
this is a sum of my practice, as i log it. i really need some guidance dude\'s and i am not alone

import pygame
import shelve
import time
import random
import datetime
import math
import sys
from time import sleep
from random import randint
from datetime import datetime
from math import pi
now = datetime.now()
print (now)


sleep (1)
#Player 1 Account Name
accoName = input("Please choose a Name for your Account: ")
print ("nice to meet you " + accoName[0].upper() + accoName[1:].lower())

#Player 1 Account Password

passVerify = 0
while passVerify <=0:
    accoPass = input("Please choose a Password: ")
    accoPassVerify = input("Please type the Password again: ")
    accoPass = accoPass.lower()
    accoPassVerify = accoPassVerify.lower()
    if accoPass == accoPassVerify:
        print ("Your password is set to be: " + accoPassVerify)
        passVerify = 1
    else:
        print("your passwords do not match please try again")
#player 1 Account Email
accoEmail = input("Please enter a valid email: ")

#player 1 Account verify number
sleep (1.5)

emailVerify = 0
while emailVerify <= 0:
    print ("A Number has been Emailed to you at "+ accoEmail)
    makeVerNum = random.randint(1001,1990)
    dudePi = pi // 1
    makeVerNum = makeVerNum + dudePi
    makeVerNum = int(makeVerNum)
    print (makeVerNum)
    verifyNumReturn = int(input("Please enter the number from your Email: "))
   # verifyNumReturn = int(verifyNumReturn)
    if verifyNumReturn == makeVerNum:
        emailVerify = 1
        print("Enjoy the game!")
    else:
        print("the number is invalid, cannot verify account.")

sleep (1.5)

#Player 1 Toon Name
toonName = input("Please enter a Name for your Toon: ")
print (toonName[0].upper()+toonName[1:].lower())

#Player 1 Gender
gender = 0
while gender <= 0:
    toonSex = input("Please tell us if you are a Man or a Woman. Type M for Man and W for Woman. ")
    if toonSex.lower() == "m" or toonSex.lower() == "man":
        print ("you have chosen ro be male")
        gender = 1

    elif toonSex.lower() == "w" or toonSex.lower() == "woman":
        print ("you have chosen to be female.")
        gender = 2
    elif toonSex.lower() == "apache attack helicoper" or toonSex.lower() == "apacheattackhelicopter" or toonSex.lower() == "aah":
        print ("oh really? me too!!!!")
        gender = 3
    else:
        print(" i sexually identify as an apache attack helicopter. but i am  still a guy, try again!")
#Player 1 Class
classChoice = 0
while classChoice <= 0:
    classChoiceInput = input("would you like to play a fighter, a rogue,  or a mage?")
    if classChoiceInput.lower() == "fighter":
        print("You wish to play a fighter!")
        classChoice = 1
    elif classChoiceInput.lower() == "rogue":
        print("you wish to play a rogue!")
        classChoice = 2
    elif classChoiceInput.lower() == "mage":
        print("you wish to play a mage!")
        classChoice = 3
    else:
        print("well isn\'t it exciting, how about one from the list?")

print("what would you like your weapon to be?")

#weapon selection
charweapon = 0
while charweapon <= 0:
    maincharweapon = input("What do you choose to weild?\nSword? Staff? Shield?")

    if maincharweapon.lower() == "sword":
        print("Valiant Warrior, you have choosen the Blade!")
        charweapon = 1
    elif maincharweapon.lower() == "staff":
        print("Wise Adventurer, You have choosen the Sceptre!")
        charweapon = 2
    elif maincharweapon.lower() == "sheild":
        print("Bold Defender, you have choosen the Bulwark!")
        charweapon = 3
    else:
        print("Whaddaya want from us? a gun?!?")

#Dictionary of items
def shelve(inventory, item_list):
    for p in item_list:
        if p[0] in inventory:
            try:
                inventory[p[0]] += p[1]
                if inventory[p[0]] < 0:
                    raise ValueError('negative amount for product')
            except ValueError as ve:
                print(ve)
                inventory[p[0]] -= p[1]
        else:
            inventory[p[0]] = p[1]
    print(inventory)
weapList = {"sword":1, "dagger":2, "round shield":3}
armourItems = [("boots",4),("potion",-1),("tunic",6)]

shelve(weapList, armourItems)
shelve(weapList,[("sword",-1000)])

'''
string substitution
'''
#assinging the string storyFormat is the core text of our story. the
#curly braces around certain words within the text are eventually going to be
#chosen by the user and changed in the story by auto writing
#their values into a dictionary, based on user input upon promt
storyFormat = '''
So one day theres this {person} right? aaand this {person} love to eat {food}.
and the {person} was broke in the {hood}. ya see {the_man} was
keeping the {person} down. so the {person} wanted to escape the {hood} and
get back to the{wild} where he was free of {the_man}.
'''
#def is short for definition. In this case we are defining a series of strings
#and variables which allow the strings to be altered later in the code
def tellStory ():
    userPicks = dict()
    addPick('person' , userPicks)
    addPick('the_man' , userPicks)
    addPick('hood' , userPicks)
    addPick('wild' , userPicks)
    addPick('food' , userPicks)
    story = storyFormat.format(**userPicks)
    print (story)
#cue and dictionary in the definition addPick, are a tuple, where as tellStory
#allows you to choose which tuple is used by leaving it blank
def addPick(cue, dictionary):
#prompt is created to know what to ask the user to input and then
#adding response is the part that does the asking
#to the prompts for hood,the man, person, and wild,
#which will be added into the dictionary because of, def tellStory, above
    prompt = 'enter an example for ' + cue +': '
    response = input(prompt)
    dictionary[cue] = response
tellStory()
input('Press Enter to end the program')



#Player 1 Experience Current
expCurr = 1
#Player 1 Experience Full
expFull = 100 #increase by 25.8 + pi per lvl
#player 1 Experience Needed For Max Level
expMax = 10000

#Player 1 Health
hpCurr = 1
#player 1 Health Full
hpFull = 100
#Player 1 Mana
mpCurr = 1
#Player 1 Mana Full
mpFull = 100
#Player 1 Armor
armorBase = 1
#Player 1 Magic Resistance
mrBase = 1
#Player 1 Dodge
dodgeBase = 1
#Player 1 Accuracy
accuracyBase = 1
#player 1 Attack Damage
atkBase = 1
#Player 1 Magic Damage
magBase = 1
#player 1 Critical Magic Damage
critMagDmg = 1
#player 1 Critical Attack Damage
critAtkDmg = 1
#player 1 Critical Chance
critChance = 1
#Player 1 Class Stat Modifier
fightStatMod = (1 + atkBase)
rogueStatmod = (1 + dodgeBase)
mageStatMod = (1 + magBase)

#player 1 Movement
movement = 1


#Weapons may be one or two handed and offer an extra effect or ability upon use

#weapon modifiers define weapon name and stats


#player 1 Weapon Name
#player 1 Weapon Cost Buy
#player 1 Weapon Cost Sell
#player 1 Attack Damage Modifier
#player 1 Magic Damage Modifier
#player 1 Accuracy Modifier
#player 1 Critical Chance Modifier
#player 1 Critical Attack Damage Modifier
#player 1 Critical Magic Damage Modifier
#player 1 Weapon Range
#player 1 One or Two Handed
#player 1 Main or Off Hand
#player 1 Weapons Special Effects

'''Shields may be a Weapon or an Armor, and 1 or 2 handed.
When a two handed Shield is equipped as an Armor, it takes the Cape slot
When a shield is one handed it can be equipped to the main or offhand slot
if a shield is equipped to the main or off or both hand slots, it may be used as a weapon.
'''

#Holding a weapon in the offhand offers an Armor/M.R./Dodge Modifier, even if it isnt a shield.

#Armor in Light, which offers the most Magic Resist and the least Armor
#Or in Medium, Which offers the most Dodge and the least Magic Resist,
#Or in Heavy, which offers the most Armor and the least Dodge

#player 1 Armor Name
#player 1 Armor Cost Buy
#player 1 Armor Cost Sell
#player 1 Armor Type (Light, Medium, Heavy)
#player 1 Bonus Armor Modifier
#player 1 Magic Resistance Modifier
#player 1 Dodge Modifier
#player 1 Armor Special Effects
#player 1 Armor Slot Used
#Head, Chest, Legs, Belt, Boots, Gloves, Shield, Neck, Ring, Wrist, Cape, Quiver.

''' Ammo and Quivers have their own stat modifiers seperate from regular armor or weapon stats.
Ammo effects all damage based stats. Ammo Capacity is dependant on the Quiver.
Quivers do not effect critical damage. only base damages.
Quivers are always light armor. Quivers effect only some Damage stats and all Armor stats
Quivers Replace the Belt or Cape Armor slot.'''

#player 1 Ammo Type
#player 1 Ammo Name
#player 1 Ammo Cost Buy
#player 1 Ammo Cost Sell
#player 1 Ammo Attack Damage Modifier
#player 1 Ammo Magic Damage Modifier
#player 1 Ammo Critical Chance Modifier
#player 1 Ammo Critical Magic Damage Modifier
#player 1 Ammo Critical Attack Damage Modifier
#player 1 Ammo Accuracy Modifier
#player 1 Ammo Special Effects


#player 1 Quiver Name
#player 1 Quiver Cost Buy
#player 1 Quiver Cost Sell
#player 1 Quiver Capacity Full
#player 1 Quiver Capacity Current
#player 1 Quiver Attack Damage Modifier
#player 1 Quiver Magic Damage Modifier
#player 1 Quiver Critical Chance Modifier
#player 1 Quiver Armor Modifier
#player 1 Quiver Magic Resist Modifier
#player 1 Quiver Dodge Modifier
#player 1 Quiver Accuracy Modifier
#player 1 Quiver Special Effects
total = 0
for i in range(5):
    new_number = int(input("Enter a number: " ))
    total += new_number
print("The total is: ", total)
print("Done.")
print("If you can count to 15 in three\'s, this game is over.")
for i in range (0,16,3):
   print(i)

hello world. what a big place, where do i go, anywhere i want? im not sure how to get there? you gotta try to get there. well i am, but what do i do next, im stumbling. walls all around. all i know is good code is like fine poetry.

so should i move the two dictionaries to a json file separate of the main game code?
if i do make the dict a diff file, do i use def_init_ to reference it, do i import it? im not sure how that works yet, trying to get there.

can i put the stat values of the characters stats into a slowly growing advancement, like a for loop that does a (1,3) range every time it fills exp current to match exp full?

how do i use/make dictionaries for menu's ones that will display items added or removed? i want to learn these things, i am asking for programmers to help me by writing annotations into my code, and examples of possible improvements, or other ways to use the code. is'nt this what forums are for?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  search a list or tuple for a specific type ot class Skaperen 8 2,013 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  Type hinting - return type based on parameter micseydel 2 2,532 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Delete specific lines contain specific words mannyi 2 4,203 Nov-04-2019, 04:50 PM
Last Post: mannyi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020