Return to “Scripting & Modding”

Post

Re: How to program in Python + Paste Code for review/help

#46
Just some nice code for generating IP Addresses.
No error catching, so for some reason, typing "sd" instead of a number gives some crazy errors (details below) unless I add "sd = ' ' " at the start.
As Grumblesaur pointed out, input returns a string, so why if I enter "sd", does it crash out?

This is the working code - copy/paste - run in python, it works for numbers only.

Code: Select all

# Next version use case statements to ask what store you want
# Provide a list of the available stores

print ""
Store_IP = '10.25.'
# This is for testing of "sd" being entered for Third and Fourth
# sd = ''

def Create_IP_Address(Store_IP, Third, Fourth):
	# print Store_IP + Third + "." + Fourth
	print "Your IP Address is %s%s.%s" % (Store_IP, Third, Fourth)
	

def main():
	Third = input("Enter the 3rd octet: ")
	Fourth = input("Enter the 4th octet: ")
	print ""
	# raw_input on it's own acts like a pause
	# raw_input("Press ENTER to continue. . .")
	# print ""
	Create_IP_Address(Store_IP, Third, Fourth)
	print ""
	
main()

This is the error message if I type in a non-number:

Code: Select all

P:\>python IPAddress-Ver-3.py

Enter the 3rd octet: sd
Traceback (most recent call last):
  File "IPAddress-Ver-3.py", line 24, in <module>
    main()
  File "IPAddress-Ver-3.py", line 15, in main
    Third = input("Enter the 3rd octet: ")
  File "<string>", line 1, in <module>
NameError: name 'sd' is not defined

P:\>python IPAddress-Ver-3.py

Enter the 3rd octet: 23
Enter the 4th octet: sd
Traceback (most recent call last):
  File "IPAddress-Ver-3.py", line 24, in <module>
    main()
  File "IPAddress-Ver-3.py", line 16, in main
    Fourth = input("Enter the 4th octet: ")
  File "<string>", line 1, in <module>
NameError: name 'sd' is not defined
But if I uncomment "sd = ' ' ", it doesn't give an error:

Code: Select all

P:\>python IPAddress-Ver-3.py

Enter the 3rd octet: 23
Enter the 4th octet: sd

Your IP Address is 10.25.23.
This is how it is supposed to work :)

Code: Select all

P:\>python IPAddress-Ver-3.py

Enter the 3rd octet: 23
Enter the 4th octet: 45

Your IP Address is 10.25.23.45
YAY PYTHON \o/

In Josh We Trust
-=326.3827=-
Post

Re: How to program in Python + Paste Code for review/help

#47
input() reads and evaluates a string of input. So it tries to evaluate 'sd', but you never defined sd, so Python is confused. Numbers, on the other hand, are perfectly valid.
What you're looking for is raw_input(), which only returns the exact string that was inputted.
(input() is equivalent to eval(raw_input()); read input, and evaluate it (execute it as if it were python code).)

The function input() was removed from Python 3 (it's a huge security risk, you can literally make python run sudo rm -rs *) and raw_input() was renamed to input(), so your confusion might come from there.
Warning: do not ask about physics unless you really want to know about physics.
The LT IRC / Alternate link || The REKT Wiki || PUDDING
Image
Post

Re: How to program in Python + Paste Code for review/help

#50
I'm reading the following (very advanced, I know), but it doesn't show anything for me :?
Python Memory Management

So I created sizeof.py as follows:

Code: Select all

import sys

def show_sizeof(x, level=0):

    print "\t" * level, x.__class__, sys.getsizeof(x), x

    if hasattr(x, '__iter__'):
        if hasattr(x, 'items'):
            for xx in x.items():
                show_sizeof(xx, level + 1)
        else:
            for xx in x:
                show_sizeof(xx, level + 1)

show_sizeof(None)
show_sizeof(3)
show_sizeof(2**63)
show_sizeof(102947298469128649161972364837164)
show_sizeof(918659326943756134897561304875610348756384756193485761304875613948576297485698417)
And when I run it, I get no response:
p:\>.run-python-script.cmd sizeof.py

p:\>
What I should see:
8 None
12 3
22 9223372036854775808
28 102947298469128649161972364837164
48 918659326943756134897561304875610348756384756193485761304875613948576297485698417

Josh, any snippets on how LT manages memory? :geek:
I got it working by removing the Carriage returns and line feeds that were copied from the browser.
derp!

The responses I get are:
p:\>.run-python-script.cmd sizeof.py
<type 'NoneType'> 16 None
<type 'int'> 24 3
<type 'long'> 36 9223372036854775808
<type 'long'> 40 102947298469128649161972364837164
<type 'long'> 60 918659326943756134897561304875610348756384756193485761304875613948576297485698417
And in case you're wondering, .run-python-script.cmd contains:

Code: Select all

p:\>type .run-python-script.cmd
@python %1 %2 %3 %4 %5 %6 %7 %8 %9
Last edited by FormalMoss on Fri Apr 15, 2016 12:29 pm, edited 1 time in total.
YAY PYTHON \o/

In Josh We Trust
-=326.3827=-
Post

Re: How to program in Python + Paste Code for review/help

#51
Just to be certain, you did add

Code: Select all

show_sizeof(None)
show_sizeof(3)
show_sizeof(2**63)
show_sizeof(102947298469128649161972364837164)
show_sizeof(918659326943756134897561304875610348756384756193485761304875613948576297485698417)
to the bottom of sizeof.py right? :ghost:

Edit: derp, didn't see the scrollbar. Nevermiiiiind
Edit 2: works for me :think:
Warning: do not ask about physics unless you really want to know about physics.
The LT IRC / Alternate link || The REKT Wiki || PUDDING
Image
Post

Re: How to program in Python + Paste Code for review/help

#52
This took me ages, but hey, I'm over the moon :)
Spoiler:      SHOW

Code: Select all


# Version.txt contains a simple number, 1
_file = 'Version.txt'

# Open the file and print its contents to the user
file_name = open(_file)
print ""
print "Old Version: %s " % file_name.read()

# Ask the user for a new version number
Custom_Version = raw_input("Current Version Number: ")

# open the file in "write" mode
file_name = open(_file, 'w')
# Write the number entered by the user to the file
file_name.write(Custom_Version)
# NB: Close the file
file_name.close()

print ""
print "Alright, all done."
And the script in action:
Spoiler:      SHOW
PS P:\_ex17.py> ..\.run-python-script.cmd .\ex17-ver3.py

Old Version: 3
Current Version Number: 5

Alright, all done.
PS P:\_ex17.py>
PS P:\_ex17.py>
PS P:\_ex17.py> ..\.run-python-script.cmd .\ex17-ver3.py

Old Version: 5
Current Version Number: 2

Alright, all done.
PS P:\_ex17.py> ..\.run-python-script.cmd .\ex17-ver3.py

Old Version: 2
Current Version Number: 3

Alright, all done.
PS P:\_ex17.py>
Last edited by FormalMoss on Fri Apr 15, 2016 10:29 pm, edited 1 time in total.
YAY PYTHON \o/

In Josh We Trust
-=326.3827=-
Post

Re: How to program in Python + Paste Code for review/help

#53
3 hours later, and I'm feeling like I know what Josh is talking about when it comes to graphics.. time flies :) but very little headway :(

So, in this code, Version.txt contains a number: 1

Python file: IncrementVersion-Auto.py
Spoiler:      SHOW

Code: Select all

n = 0
print n

_file = 'Version.txt'

def Auto_ver():
  global n
  for line in open(_file):
      if line.strip():
		n = int(line)
		print "Inside Loop (n), n = %i" %n
		n += 1
		print "Inside Loop (n+1), n = %i" % n
		 
Auto_ver()
print ""
print "Outside Loop (n+1), n = %i" %n

print ""
file_name = open(_file)
print "Contents of Version.txt: %s" % file_name.read()
file_name.close()

# file_name = open(_file, 'w')
# file_name.write(n)
# file_name.close()


print ""
print "Alright, all done."
The results work, but it doesn't update Variable.txt:
Spoiler:      SHOW
p:\_ex17.py>type Version.txt
1

p:\_ex17.py>..\.run-python-script.cmd test.py
0
Inside Loop (n), n = 1
Inside Loop (n+1), n = 2

Outside Loop (n+1), n = 2

Contents of Version.txt: 1

Alright, all done.

p:\_ex17.py>type Version.txt
1
I have tried adding extra lines to open the file with 'w'rite options, but the value ends up being empty, and Variable.txt is updated as ' '.

Code: Select all

file_name = open(_file, 'w')
file_name.write(int(n))
file_name.close()
And these are the results:
Spoiler:      SHOW
p:\_ex17.py>type Version.txt
1
p:\_ex17.py>..\.run-python-script.cmd test.py
0
Inside Loop (n), n = 1
Inside Loop (n+1), n = 2

Outside Loop (n+1), n = 2

Contents of Version.txt: 1
Traceback (most recent call last):
File "test.py", line 26, in <module>
file_name.write(n)
TypeError: expected a character buffer object

p:\_ex17.py>type Version.txt

p:\_ex17.py>
EDIT: Yay, I fixed this error: ValueError: invalid literal for int() with base 10: '\xff\xfe2'
Turns out if Version.txt contains any special characters, it gives this error.
Notepad doesn't fix it, but a custom shell editor (bbnote.exe, from blackbox window manager), sees these extra characters and I can remove them.

EDIT2: And I fixed it! It works as intended - wow - what a rite of passage that was!

File: Version.txt, contains a value of 24
File: test.py
Spoiler:      SHOW

Code: Select all


n = 0
print ""
print "Initial Value of n: %i" % n

_file = 'Version.txt'

def Increment_Version():
  global n
  for line in open(_file):
      if line.strip():
		n = int(line)
		print "Inside Loop (Read from _file), n = %i" %n
		n += 1
		print "Inside Loop (n+1), n = %i" % n
		 
Increment_Version()
print ""
print "Outside Loop (n+1), n = %i" %n

print ""
file_name = open(_file)
print "Contents of Version.txt (Before Write): %s" % file_name.read()

Output = str(n)

file_name = open(_file, 'w')
file_name.write(Output)
file_name.close()

print ""
file_name = open(_file)
print "Contents of Version.txt (After Write): %s" % file_name.read()

print ""
print "Alright, all done."
file_name.close()

# import os
# file_name.seek(0, os.SEEK_CUR)
And the Results:
Spoiler:      SHOW
p:\_ex17.py>..\.run-python-script.cmd test.py

Initial Value of n: 0
Inside Loop (Read from _file), n = 24
Inside Loop (n+1), n = 25

Outside Loop (n+1), n = 25

Contents of Version.txt (Before Write): 24

Contents of Version.txt (After Write): 25

Alright, all done.

p:\_ex17.py>..\.run-python-script.cmd test.py

Initial Value of n: 0
Inside Loop (Read from _file), n = 25
Inside Loop (n+1), n = 26

Outside Loop (n+1), n = 26

Contents of Version.txt (Before Write): 25

Contents of Version.txt (After Write): 26

Alright, all done.

p:\_ex17.py>
YAY PYTHON \o/

In Josh We Trust
-=326.3827=-
Post

Re: How to program in Python + Paste Code for review/help

#54
How to program in functions, answer to Chapter 21 from
Learn Python The Hard Way - Chapter 21 - Functions can return something
Spoiler:      SHOW

Code: Select all

def add (a,b):
	# print "ADDING %d + %d" % (a,b)
	return a + b
	
def subtract(a,b):
	# print "SUBTRACTING %d - %d " % (a,b)
	return a - b

def multiply(a,b):
	# print "MULTIPLYING %d * %d " % (a,b)
	return a * b
	
def divide(a,b):
	# print "DIVIDING %d / %d " % (a,b)
	return a / b
	
def puzzle(age, height, weight, iq):
	total = divide(iq, 2)
	total = multiply(weight, total)
	total = subtract(height, total)
	total = add(age, total)
	return total

#####################
#  Start of Program #
print ""
print "Let's do some math with just functions!"

#######################################################
# This is where the action happens, setting variables #
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

#######################################################
# Both of these work the same, just one is easier to  #
# read and uses a function \o/                        #
what = puzzle(age, height, weight, iq)
# what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print ""
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

# A puzzle for the extra credit, type it in anyway.
print ""
print "Here is a puzzle."
print ""
print "That becomes: ", what, "Can you do it by hand?"

#######################################################

YAY PYTHON \o/

In Josh We Trust
-=326.3827=-

Online Now

Users browsing this forum: Bing [Bot] and 1 guest

cron