Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

Python Programming Error


  • Please log in to reply
5 replies to this topic

#1 razzo

razzo

  • Members
  • 13 posts
  • OFFLINE
  •  
  • Local time:07:31 PM

Posted 26 March 2010 - 06:02 PM

I'm trying to figure out a way to get my program to handle multiple inputs, all of which could handle exceptions. I have trouble programming proper except errors.

Help, please?

#Python 3.0 Version
#Converted by U.S. Industrial Gaming Applications
#http://www.atariarchives.org/bigcomputergames/showpage.php?page=12

#notes to be deleted
#http://docs.python.org/tutorial/errors.html#handling-exceptions

import math
import random

year = 1
pop = 250

badland = 0 # 0% land
minland = 0  #20
lowland = 0 # 40%
modland = 400 # 60% land
goodland = 300 # 80%
bestland = 300 # 100% land
totland = 1000

maxfarmable = 1000
farmed = 0
supply = 0 # amount fed to peasants
ratseat = 78 # rats eat
plant = 0  # the number planted

popularity = 50
starving = 0
oversupply = 0

livestock = 100
food = 4400
sinceplague = 0
castlemaint = 120
granarycosts = 0
totalmaint = 120
births = 12
natdeaths = 5
starvationd = 0
wardeaths = 0
diseasedeaths = 0
totdeaths = 1

pox = 0
poxchanc = 0 # pox chance

print ("Dukedom")
while year != 5:
	totalmaint = castlemaint + granarycosts
	rats = round(random.uniform(5.0, 9.0))
	ratseat = (rats / 100) * food
	print ("Year: ", year, " Peasants: ", pop, " Land: ", totland, " Livestock: ", livestock, " Food: ", food, sep="")
	print ("Castle Overhead: ", totalmaint, " Births: ", births, " Deaths: ", totdeaths, sep="")
	print ("Rats have eaten ", round(ratseat), " units of grain.", sep="")
	if wardeaths > 0:
		print (wardeaths, "peasants have died from war.", sep="")
		wardeaths = 0
	if pox == 1:
		diseasedeaths = pop * 0.1
		print ("A pox has been ravaging your Duchy.")
	if pox == 0:
		diseasedeaths = 0
	year = year + 1
	try:
		supply = int(input("Food for peasantry: "))
	except supply > 20:
		supply = int(input("Food cannot be greater than 20, please choose a new number: "))
	except ValueError:
		print ("My liege, that isn't a valid number.")
	if supply < 14:
		print ("Your peasants are starving!")
		starving = 14 - supply
		starvationd = round((starving / 14) * pop)
		popularity = popularity - (9 * starving)
		print (starvationd, "peasants have died from hunger.", sep="")
		print (starving, popularity)
	if supply > 15:
		oversupply = supply - 15
		popularity = popularity + round(oversupply * 0.9)
	if supply >= 14:
		starving = 0
		starvationd = 0
	try:
		plant = int(input("Land to be planted:")
	except plant > totland:
		print("You are planting more land than available, choose new number")
	except ValueError:
		print ("My liege, that isn't a valid number.")
	food = food - ratseat - ((supply) * pop) + (livestock * 2) + (plant * 15)
	print ("")
	totdeaths = natdeaths = starvationd + wardeaths + diseasedeaths
	pop = pop + births - totdeaths
	births = round(pop * 0.06)
	natdeaths = round(pop * 0.03)
	while popularity < 25:
		print ("The peasants revolt! They tire from wars and famine.")
		print ("The King quells the rebellion, but he gets someone else for the job.")
if year == 5:
	print ("Year: ", year, sep="")
	print ("You have died of old age.")
if popularity > 50:
	print ("You are remembered as a kind duke.")


BC AdBot (Login to Remove)

 


#2 groovicus

groovicus

  • Security Colleague
  • 9,963 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Centerville, SD
  • Local time:08:31 PM

Posted 26 March 2010 - 06:50 PM

I am not a Python programmer, so I am not as familiar with the syntax, but I think you are having some misconceptions about exception handling. Exceptions are for for handling program errors. So for instance, if the program expects a number, and it gets a letter instead, you would have an error. you have an example of that in your code.
try:
   plant = int(input("Land to be planted:")
  .....  
except ValueError:
   print ("My liege, that isn't a valid number.")

You can not do this:
try:
		supply = int(input("Food for peasantry: "))
	except supply > 20:
		supply = int(input("Food cannot be greater than 20, please choose a new number: "))

This is how exceptions really work. You have a 'try' section, and a 'except' section. If the statements inside the 'try' section fail because of a programming error, then the code inside the 'except' block is executed. You can not say except supply>20 and expect it to do anything. Exceptions do not take conditionals as parameters. If you want to throw an error when a particular condition is violated, then you need to raise an exception. I don't see any need for it though. If the parameter is not valid, then just print the error message. You don't need an exception. Your code would be fine like this:
try:
		supply = int(input("Food for peasantry: "))
		if supply >20
		   supply = int(input("Food cannot be greater than 20, please choose a new number: "))
	except ValueError:
		print ("My liege, that isn't a valid number.")

So what happens is if the input is not a valid number, then the code throws the exception and will ignore the rest of the code. If it is a valid number, and it is greater than 20, then it will display the next input message. If not, it skips that code.

#3 razzo

razzo
  • Topic Starter

  • Members
  • 13 posts
  • OFFLINE
  •  
  • Local time:07:31 PM

Posted 27 March 2010 - 02:12 AM

Thank you. Still another bug. Syntax error:

plant = int(input("Land to be planted:")
		if plant > totland:
		print("You are planting more land than available, choose new number")


#4 groovicus

groovicus

  • Security Colleague
  • 9,963 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Centerville, SD
  • Local time:08:31 PM

Posted 27 March 2010 - 06:05 AM

What is the error exactly?

#5 PropagandaPanda

PropagandaPanda


  • Malware Response Team
  • 10,433 posts
  • OFFLINE
  •  
  • Gender:Male
  • Local time:10:31 PM

Posted 27 March 2010 - 05:27 PM

Hello razzo.

I'll just jump in if you don't mind.

plant = int(input("Land to be planted:")

You didn't close the int() function bracket.

Are you using a Python IDE, or just a plain text editor? A program like WING IDE should have pointed out the error immediately.

A quick word on using input(). It's not just getting data from the user. What the user types is actually evaluated as if it appeared in your source code place of the input() command. You may not have noticed since you are just using it for obtaining ints.

For instance, if you had the following:
Name = input("Please enter name")
And the person entered
  • 9873 - You would get an int type
  • {"asdf":4587} - You would get a dictionary type
  • Panda - You get a syntax error because Panda is probably not defined in your program.
  • "Panda" - You get a str, what you actually wanted
This forces you to catch errors, which is tiresome and expensive in terms of processing.

Instead, you should use raw_input(), which always returns a str and does not attempt to evaluate the string.

A good way to do what you were trying would be.
try:
	plant = int(raw_input("Land to be planted:"))
except ValueError:
	print "Invalid input"
	#Or whatever else you want to do

In my opinion, error handling should not be used to check user input. Instead, a conventional if statement can be used as such.
plant = (raw_input("Land to be planted:"))

if plant.isdigit():
	plant = int(plant)
else:
	print "Invalid input"

With Regards,
The Panda

edit: make my code raw_input()

Edited by PropagandaPanda, 27 March 2010 - 06:46 PM.


#6 groovicus

groovicus

  • Security Colleague
  • 9,963 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Centerville, SD
  • Local time:08:31 PM

Posted 27 March 2010 - 05:53 PM

In my opinion, error handling should not be used to check user input.


And I whole-heartedly agree. Exceptions should be for program-related errors.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users