Hi so my school is doing an RPG project on python, and i have encountered a problem where i define my own functions, and needs to call one of them inside another, and it doesn't work. The following code for example:
from characters1 import *
def printmana(typeofenemy):
print typeofenemy.mana
def printmany(typeofenemy):
print typeofenemy.damage
print typeofenemy.health
option = raw_input("Type something ")
if option == 1:
printmana(typeofenemy)
printmany(Goblin)
when i call printmany(Goblin), everything goes fine until i type in 1, where i expect it to call printmana(Goblin) and print Goblin.mana, but it doesn't. Yet when i call printmana(Goblin) separately, it works absolutely fine. I also tried this:
from characters1 import *
def printmana(typeofenemy):
return (typeofenemy.mana)
def printmany(typeofenemy):
print typeofenemy.damage
print typeofenemy.health
option = raw_input("Type something ")
if option == 1:
print (printmana(typeofenemy))
printmana(Goblin)
Where i thought i change the print in printmana as return, and call the print printmana(Goblin) in the second function, yet it still doesn't work when i type in 1. There must be some thing i don't yet understand about the nature of python functions, so can someone please explain why is my example code not working? Thank you!
Your trouble is that you're comparing the output of raw_input (a string) with an integer. Try one of the following:
if option == "1":
...
or
if int(option) == 1:
...
Option is a string in this code:
>>> option = raw_input("Type something ")
Type something 1
>>> print option
1
>>> print type(option)
<type 'str'>
>>> print option == 1
False
>>> print option == "1"
True
So you need change the if to:
if option == "1":
raw_input doesn't cast the value to an integer. You could compare option to a string, i.e:
if option == '1':
Or you could convert option to an int, i.e.:
option = int(option)
Be aware that the second choice has some interesting gotchas if the value can't be converted to an int.
You set the variable "option" to become whatever the user types in. If the user types '1' and hits return, "option" will hold the string value, '1'. So, the issue is in your "if" statement, where you compare a string and a integer.
Related
I'm doing a bunch of work in the Python console, and most of it is referring to addresses, which I'd prefer to see in hex.
So if a = 0xBADF00D, when I simply enter Python> a into the console to view its value, I'd prefer python to reply with 0xBADF00D instead of 195948557.
I know I can enter '0x%X' % a to see it in hex, but I'm looking for some sort of python console option to have it do this automatically. Does something liket this exist? Thanks!
The regular Python interpreter will call sys.displayhook to do the actual displaying of expressions you enter. You can replace it with something that displays exactly what you want, but you have to keep in mind that it is called for all expressions the interactive interpreter wants to display:
>>> import sys
>>> 1
1
>>> "1"
'1'
>>> def display_as_hex(item):
... if isinstance(item, (int, long)):
... print hex(item)
... else:
... print repr(item)
...
>>> sys.displayhook = display_as_hex
>>> 1
0x1
>>> "1"
'1'
I suspect you'll quickly get tired of seeing all integers as hex, though, and switch to explicitly converting the ones you want to see as hex accordingly.
Building on previous answers, here's a version that works for Python 2/3, doesn't display bools as hex, and also properly sets the _ variable:
import sys
def _displayhook(o):
if type(o).__name__ in ('int', 'long'):
print(hex(o))
__builtins__._ = o
else:
sys.__displayhook__(o)
def hexon():
sys.displayhook = _displayhook
def hexoff():
sys.displayhook=sys.__displayhook__
Something like this, perhaps?
class HexInt(int):
"Same as int, but __repr__() uses hex"
def __repr__(self):
return hex(self)
So you'd use that when creating all your integers that you want to be shown as hex values.
Example:
>>> a = HexInt(12345)
>>> b = HexInt(54321)
>>> a
0x3039
>>> b
0xd431
>>> c = HexInt(a + b)
>>> c
0x1046a
Note that if you wanted to skip the explicit creation of a new HexInt when doing arithmetic operations, you'd have to override the existing int versions of methods such as __add__(), __sub__(), etc., such that they'd return HexInts.
Modifying the top python2 answer for python3...
def display_as_hex(item):
if isinstance(item, int):
print(hex(item))
else:
print(repr(item))
import sys
sys.displayhook = display_as_hex
You could so something like this:
while True:
print hex(input('> '))
To get a basic prompt that prints the hex value of all of the results. You could even make it conditional -- check to see if the return type of input is a string or number, and if it is, print the hex value, else print the value normally.
There is some control logic that I am trying to set up, and it would be useful if I could have input() return a boolean value based on input from the user. Does input() already compare a value to another in how it inherently works?
I can imagine myself having to write a function based on what input() already does if it does not have a boolean return feature.
So far, my code consists of a while loop. It had an exit condition that I need to use more specifically. I have left it out from below
str = "original"
while True:
print(str)
time.sleep(1)
str = "changed"
if str == "changed":
changed = True
Actual Results:
original
changed
changed
changed
changed
At some point, this loop should just print out what a user gives to input() with a time delay between each print statement, but what I have done here does not use input and only exits with a keyboard interrupt.
I don't know which needs to be addressed first to complete this code: making the exit from the while loop independent of the keyboard interrupt or the processing of the user input.
No, input() always returns a string.
But you would just compare that string with another
s = "original"
changed = False
while not changed:
print(s)
time.sleep(1)
s = input("> ")
if s == "changed":
changed = True
print('s = {}'.format(s))
Note: str is a built-in python class. Don't name a variable as the same
import time
s = "original"
changed = False
while not changed:
time.sleep(1)
sprev = s
s = input("> ")
if s != sprev:
changed = True
I have a task to make a program that asks the user about an issue they have with their mobile phone. My program is then to look at the input and go through a series of keywords it may recognise. Certain keywords allow it to read a certain line from a file I have created.
Here is my code, it's fairly simple however isn't working properly
I run the program, and when keywords are recognised from the if statement the program is supposed to print out the lines that match the keywords in the if statement. However if i put more than one keyword from different if statements it only prints out the line(solution) for the first keyword. I have tried using if instead of elif but this makes a bigger problem because the while loop doesn't break even when keywords are recognised.
It's because once an if or (elif) statement is matched the whole of statement is done. Use all if statements and get rid of your last else statement. If you never satisfy any of the if statements your false condition will remain false anyway. You can have your last if statement be if keyword_comparison == false print ('enter new key word') or something
Something like:
def myfun():
boolean = False
while boolean == False:
word = input("enter input")
if "hi" in word:
print "test"
boolean = True
if "bye" in word:
print "test1"
boolean = True
if boolean == False:
print "please try again"
Question
First of all, as you have been asked in the comments, you should provide a MCV example, this means the smallest code that can run on its own and reproduces your error, which usually means including all in one single file but if you decide to keep the .txt at least provide it.
Also, paste your code, not an image of it, as we would need to retype all the code.
Answer
If you want multiple prints you can't have them in the same if ... elif ... else ... block. You need to check each condition in its own if ... block. This modification means you don't have access to a common else ..., but this has a simple solution, check if the flag is still False.
while not keyword_recognition:
if condition1:
print("1")
keyword_recognition = True
if condition2:
print("2")
keyword_recognition = True
if condition3:
print("3")
keyword_recognition = True
...
if not keyword_recognition:
print("Unrecognised keywords, ...")
Further corrections
You have another bug:
<<< ('hello' and 'world') in 'hi world'
>>> True
First the inner of the parenthesis is evaluated, which yields "world" and then just this partial result is checked. If you want to force both to be in the sentence you should use the following:
<<< string = 'hi world'
<<< ('hello' in string and 'world' in string) or 'goodbye' in string
>>> False
The parethesis wrap both operations together, so string must either contain both 'hello' and 'world' or just contain 'goodbye'. Fullfilling both conditions would also yield True unless you use an exclusive or.
Relatively new to programming and doing some coursework on python. I've been told to label all my variables with the correct data type. For example an integer would be called iVariable and a string would be sString. Although I recall someone telling me that sometimes you need to label a variable containing a number a string? I don't really understand what they meant by this. Below is the start of my code, it's not perfect but if someone could tell me if I've done the data types right or wrong and told me what their supposed to be that would be great. Thanks in advance
iResultlist = 0
sEndScript = 0
while iResultlist == 0:
if sEndScript == "y":
iResultlist = 1
sStudent = input("What is the students name?")
bInputValid = False
while (bInputValid == False):
sUserResponse = input("What score did they get")
if sUserResponse.isdigit():
iScore = int(sUserResponse)
bInputValid = True
else:
print ("Enter a valid number please")
iClass = input("What class is the student in? \"1\, "\"2\" or \"3\"")
if iClass == "1":
Class1 = open("Class1.csv", "a+")
Class1.write(Student+","+Score+"\n")
Class1.close()
Also is there a data type I should use for my file names? And if so what is it?
sometimes you need to label a variable containing a number a string
I'm guessing that what they meant is a situation like in:
iClass = input("What class is the student in? \"1\, "\"2\" or \"3\"")
The content of iClass is going to be a number, sure. But the type is still a string. To get a numerical value out of it, you still have to convert it via int(iClass). So if you're really going for the hungarian notation, then it should be something like:
sClass = input(...) # this is a string, even if the string is "123"
iClass = int(sClass) # now it's a proper int
Although in the current code, you just don't need the converted iClass at all.
If you're not sure what type something is at some point, you can always print it out during execution, like:
print("iClass is:", type(iClass))
But like #Blorgbeard commented - hungarian notation isn't really popular outside of winapi these days.
You can always test the type of a variable by doing
if isinstance(iClass, int):
... # continue with you example
Instead of 'int' you can use other types like str, float etc
BTW, the Hungarian notation is useful in languages that enforce a variable to only have one type. It was common in the first language I learnt, FORTRAN, but punched cards were the thing too.
I just have this little program here that I want to use to take an input from a user (as if entering a password). I have a list with the password in it, I then take the users input and place it in an empty class. Then compare that class to the one with the password in it, if it matches it will return "good". However I've only been able to do this using one digit. How would allow for the user to use multiple integers? And is this an efficient way of doing this sort of thing? Is there are quicker more efficient method? Thanks.
class KeyCode(object):
def access(self):
room_code = [1]
print "Before you enter you must provide the room code: "
attempt = []
code = int(raw_input('>>'))
attempt.append(code)
if attempt == room_code:
print "Good"
else:
return 'death'
class Boxing_room(KeyCode):
def enter(self):
print "This is the boxing studio"
return 'Gymnast_room'
Lists aren't necessarily needed. You can just compare strings, or if your code is only numbers, integers.
Also, a class isn't really helpful here (unless it's here just to learn a bit about them). A function will suffice:
def access():
room_code = 12534
code = int(raw_input('Enter the code: '))
if code == room_code:
return 'good'
return 'death'
You can use a dictionary to store the keycodes:
code_dict = {'Boxing':'12345', 'Locker':'00000'}
and test
if code_input == code_dict['Boxing']:
...
I agree with Haidro's answer, but it seems to me you may want to allow more than one password?
If that is the case you would just need to do an 'IN' check.
For example.
def access():
room_code = [12345,54321]
code = int(raw_input('Enter the code: '))
if code in room_code:
return 'good'
return 'death'