How to jump to a random function in python3 - python

i am making a python script that talks back to just for fun and i want it to pick a random subject to talk about each time here is a snippet of my code
def randsub():
rand = random.randrange(1,3)
rand.toString()
randsub = "sub" + rand
randsub()
but it keeps giveing me this error
TypeError: Can't convert 'int' object to str implicitly

Put the functions in a list, then use the random.choice() function to pick one at random for you. Functions are just objects, just like any other value in Python:
import random
def sub_hello():
print('Well, hello there!')
def sub_nice_weather():
print("Nice weather, isn't it?")
def sub_sports():
print('What about them Broncos, eh?')
chat_functions = [sub_hello, sub_nice_weather, sub_sports]
randsub = random.choice(chat_functions)
randsub()
You got your specific error because you tried to concatenate an integer with a string ("sub" is a string, rand an integer); you'd normally convert the integer to a string first, or use a string template that supports converting other objects to strings for you (like str.format() or str % (values,)). But the string doesn't turn into a function, even if the string value was the same as a function name you happen to have defined.

Related

array handling in python

i am just trying...but the self.value show error ie...i want to loop self.a,self.b,self.c...help require for learning help required......output wanted is x= [AA,EE,II] using classes and loops.i tried looping the self.a,self.b,self.c using for loop.........i am learning python and object oriented programming newly....help me out
import string
A = ["AA","BB","CC","DD"]
B = ["EE","FF","GG","HH"]
C = ["II","JJ","KK","LL"]
class User:
def __init__(self,A,B,C):
self.a= A
self.b= B
self.c= C
def User1(self):
x=[]
for i in range(ord('a'), ord('c')+1):
value= chr(i)
x.append= self.(value)[0] ///for getting first elemen from A,B,C
i+=1
return x
honey= User(A,B,C)
print(honey.User1())
WHat you want is to use getattr - but there are a few other things broken there. (to start with the fact that the comment character is # in Python, and not the // sequence.
So, your User1 method could be something like:
def User1(self):
x=[]
for value in "abc":
x.append(getattr(self, value)[0])
return x
Note as well that the for statement will always iterate over a sequence, and you don't need to go long ways to convert your sequence to numbers, just for converting those numbers back to the desired elements. As a string is also a sequence of characters - just looping over "abc" will yield your desired letters.
As stated above, the getattr built-in will then retrieve the desired attribute from self gven the attribute name as a string, contained in the value variable.

How to use dictonary to create an object?

I'm new in stackoverflow and I'd like to make my first question for a problem in this code I've tried to write to learn objects in python.
I'm trying to call the creation of an object through a dictionary.
My purpose is to create an object thanks to a number, for example I have the dictionary newch = {1 : Character.new_dragon(), 2 : Character.new_goblin()} and when I call Player1 = newch[1] it should create a new dragon (#classmethod new_dragon) and assign it to Player1
The problem is that when i run the program, Character.new_dragon() and Character.new_goblin() are called automatically (i put a control print), but when I write "DRAGO" after the request "which player?" the functions aren't called because there isn't the control print
import random
class Character:
def __init__(self,idd,height,weight,att,defe):
self.idd=idd
self.height=height
self.weight=weight
self.att=att
self.defe=defe
#classmethod
def new_goblin(cls):
print('newgoblin')
return cls(1,getr(1,1.5,0.1),getr(40,60,0.5),getr(5,15,1),getr(6,10,1))
#classmethod
def new_dragon(cls):
print('newdrago')
return cls(2,getr(20,30,1),getr(500,2000,5),getr(50,150,3),getr(20,100,3))
def getr(start,stop,step): #returns float
x=random.randint(1, 1000)
random.seed(x)
return random.randint(0, int((stop - start) / step)) * step + start
play={1:'p1', 2:'p2', 3:'p3', 4:'p4'} #dict for players
newch={1:Character.new_dragon(),2:Character.new_goblin()} ############This doesn't work
i=1
while True:
char=input("which player? Drago or Goblin?").upper()
if(char=="DRAGO"):
play[i]=newch[1] #here i try to call Character.new_dragon()
i+=1
break
elif(char=="GOBLIN"):
play[i]=newch[2]
i+=1
break
print("write \'Drago\' or \'Goblin\'")
print(play[1].height, play[1].weight, play[1].att, play[1].defe)
Here's my code, if you could help me, I would be very glad, thanks
The new object is created immediately when you call Character.new_dragon(), and the object is then stored in the dict.
Instead you could not store the object in the dict, but the function that creates it. That function would be Character.new_dragon (without the ()). Then you can call that function when the player selects a character:
play[i]=newch[1]()
Complete code:
import random
class Character:
def __init__(self,idd,height,weight,att,defe):
self.idd=idd
self.height=height
self.weight=weight
self.att=att
self.defe=defe
#classmethod
def new_goblin(cls):
print('newgoblin')
return cls(1,getr(1,1.5,0.1),getr(40,60,0.5),getr(5,15,1),getr(6,10,1))
#classmethod
def new_dragon(cls):
print('newdrago')
return cls(2,getr(20,30,1),getr(500,2000,5),getr(50,150,3),getr(20,100,3))
def getr(start,stop,step): #returns float
x=random.randint(1, 1000)
random.seed(x)
return random.randint(0, int((stop - start) / step)) * step + start
play={1:'p1', 2:'p2', 3:'p3', 4:'p4'} #dict for players
newch={1:Character.new_dragon,2:Character.new_goblin} ############This doesn't work
i=1
while True:
char=input("which player? Drago or Goblin?").upper()
if(char=="DRAGO"):
play[i]=newch[1]() #here i try to call Character.new_dragon()
i+=1
break
elif(char=="GOBLIN"):
play[i]=newch[2]()
i+=1
break
print("write \'Drago\' or \'Goblin\'")
print(play[1].height, play[1].weight, play[1].att, play[1].defe)
This works, however I would not say it is the best coding style. Its hard to judge from only this piece of code, but it might be a better idea to make Drago and Goblin subclasses of the Character class and store the type of those classes in that dictionary.
newch={1:Character.new_dragon(),2:Character.new_goblin()}
As this is written, the new_dragon and new_goblin functions are called when the dictionary is created. This is why you are seeing them both run "automatically" every time you run your program.
If you instead declared the dict like:
newch={1:Character.new_dragon ,2:Character.new_goblin}
And later have something like:
if(char=="DRAGO"):
play[i]=newch[1]()
(note the parenthesis after the newch[1]) you should get what you want.
Incidentally, those break statements aren't necessary. The If/elif/else chain doesn't fall through like a switch statement in other languages.
When you are initialising the dictionary this way:
newch={1:Character.new_dragon(),2:Character.new_goblin()}
You are binding keys (1 and 2) to the return values of the new_dragon and new_goblin functions. You need to bind the functions(without calling them) like so:
newch={1:Character.new_dragon,2:Character.new_goblin}
Notice there are no brackets!
And then, when you create players, you execute those functions like so:
play[i]=newch[1]() Notice here we have brackets!
Additionally, if I may suggest an improvement of the code here:
if(char=="DRAGO"):
play[i]=newch[1]()
i+=1
To avoid the if statement, you can create you mapping with a string:
newch={"DRAGO":Character.new_dragon,"GOBLIN":Character.new_goblin}
And create instances just by calling
play[i]=newch[char]()
To handle errors, you can add just a single if statement checking whether the char string is in the list with dict keys.

How to complete this function then print it out, using Python?

I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?
string = "Hello"
reverse = string[::-1]
print(reverse)
I tried putting it in a function but I cannot make it print Hello.
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
also tried this
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
Nothing seems to work. I'm having same problem with this as well.
total = 0
def length(words):
for i in words:
total += 1
return total
Functions without a return value
Functions that just take action or do something without returning a value (for example, print).
Functions that don't return a value can be defined like that:
def sayHello():
print "Hello!"
And can be used (called) like that:
sayHello()
And the output will be:
Hello!
Function parameters
A function can also receive parameters (type of variables) from the caller. It's better to demonstrate it with an example.
A function that receives a name and greets this name:
def sayHelloTo(name):
print "Hello", name
It can be called like that:
sayHelloTo("Yotam")
And the output will be:
Hello Yotam
The parameters are the function's input.
Functions with a return value
Other functions, unlike sayHello() or sayHelloTo(name) (that just do something) can return a value. For example, let's make a function that rolls a dice (returns a random number between 1 and 6).
from random import randint
def rollDice():
result = randint(1, 6)
return result
The return keyword just sets the output value of the function and exits the function. An example use of the rollDice function will be:
dice = rollDice()
print "The dice says", dice
When the function hits a return keyword, it finishes and the return value (in our case, the variable result) will be placed instead of the function call. Let's assume randint(1, 6) has produced the number 3.
Result becomes 3.
Result is returned.
Now, instead of the line:
dice = rollDice()
We can treat the line as:
dice = 3
(rollDice() was replaced with 3)
Functions with parameters and a return value
Some functions (for example, math functions) can take inputs AND produce outputs. For example, let's make a function that receives 2 numbers and outputs the greater one.
def max(a,b):
if a > b:
return a
else:
return b
What it does is pretty clear, isn't it? If a is greater, it returns the value of it. Otherwise, returns the value of b.
It can be used like that:
print max(4, 6)
And the output will be:
6
Now, your case
What you want to do is a function that reverses a string. It should take 1 parameter (input) - the string you want to reverse, and output 1 value - the reversed string. This can be accomplished like that:
def reverse_a_string(my_text):
return my_text[::-1]
now you can do something like that:
s = raw_input("Please enter a string to be reversed\n") #input in Python3
r = reverse_a_string(s)
print r
r will contain the reversed value of s, and will be printed.
About your second function - well, I assume that based on this answer you can make it yourself, but comment me if you need assistance with the second one.
Local variables
About your 3rd example:
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
This is something that is really worth delaying and understanding.
the variable reverse is first used inside the function. This makes it a local variable.
This means that the variable is stored in the memory when the function is called, and when it finishes, it is removed. You can say it's lifetime is from when the function is called to when the function is done.
This means that even if you called reverse_a_string(string), you wouln't be able to use the reverse variable outside of the function, because it would be local.
If you do want to pass a value like that, you have to "declare" your variable outside of the function and to use the global keyword, like that:
reverse = "" #This makes reverse a global variable
def reverse_a_string(string):
global reverse #Stating that we are going to use the global variable reverse
reverse = string[::-1]
# Then you can call it like that:
reverse_a_string("Hello")
print reverse
The output will be
olleH
Although it's strongly not recommended to do it in Python, or in any other language.
Once you create a function you must call it. You have created the function reverse_a_string but then you never actually call it. Think about a function as a button that does something everytime it is pushed (or in our case called). If you never push the button then although it has the potential to do something, it never will. In order for the set of instructions to happen we need to push the button (or in our case call the function). So in order for your code to work you first need to define the function then actually call it:
def reverse_a_string():
string="Hello"
reverse = string[::-1]
print reverse
reverse_a_string()
Result: 'olleH'
If you want to pass your own string in to the function so it doesn't just return 'olleH' all the time your code needs to look like such:
def reverse_a_string(stringThatWillBeReversed):
reverse = stringThatWillBeReversed[::-1]
print reverse
reverse_a_string('whateverStringYouWant')
Result: The reverse of the string you entered.
Hope that helps!
I don't know whether you are asking how to define functions in python or something else
If you want to learn python functions, go to http://www.tutorialspoint.com/python/python_functions.htm or just write python tutorial in google, you will get billions of good sites
def reverse_a_string(string):
#function definition
reverse = string[::-1]
print(reverse)
#function call
reverse_a_string("your string")
But you to define function for this, you could simply do
print( string[::-1] )
# defines the 'Reverse a String' function and its arguments
def reverse_a_string():
print(string)
reverse = string[::-1]
print(reverse)
print("Type a string") # asks the user for a string input
string = input() # assigns whatever the user input to the string variable
reverse_a_string() # simply calls the function
for functions, you have to define the function, then simply call it with the function name i.e. funtion()
In my example, I ask for a string, assign that to the variable, and use it within the function. If you just want to print hello (I'm a little unclear from your question) then simply including the print("hello") or w/ variable print(string) will work inside the function as well.

Python - Parameters

I have a code like this:
>>> def enterText(value):
command = input ("enter text: ")
value = command
>>> def start():
text = ""
enterText(text)
print ("you entered: "+str(text))
I have tied a lot of things but I can't seem to figure it out. I'm new to Python, can help me pass a string through functions? Thanks!
Strings in Python are immutable. You need to return the string from enterText() so you can use it within start().
>>> def enterText():
return input("enter text: ")
>>> def start():
text = enterText()
print ("you entered: " + str(text))
A given string object cannot be changed. When you call enterText(text), value will refer to the empty string object created within start().
Assigning to value then rebinds the variable, i.e. it connects the name "value" with the object referenced by the right-hand side of the assignment. An assignment to a plain variable does not modify an object.
The text variable, however, will continue to refer to the empty string until you assign to text again. But since you don't do that, it can't work.

"Function object is unsubscriptable" in basic integer to string mapping function

I'm trying to write a function to return the word string of any number less than 1000.
Everytime I run my code at the interactive prompt it appears to work without issue but when I try to import wordify and run it with a test number higher than 20 it fails as "TypeError: 'function' object is unsubscriptable".
Based on the error message, it seems the issue is when it tries to index numString (for example trying to extract the number 4 out of the test case of n = 24) and the compiler thinks numString is a function instead of a string. since the first line of the function is me defining numString as a string of the variable n, I'm not really sure why that is.
Any help in getting around this error, or even just help in explaining why I'm seeing it, would be awesome.
def wordify(n):
# Convert n to a string to parse out ones, tens and hundreds later.
numString = str(n)
# N less than 20 is hard-coded.
if n < 21:
return numToWordMap(n)
# N between 21 and 99 parses ones and tens then concatenates.
elif n < 100:
onesNum = numString[-1]
ones = numToWordMap(int(onesNum))
tensNum = numString[-2]
tens = numToWordMap(int(tensNum)*10)
return tens+ones
else:
# TODO
pass
def numToWordMap(num):
mapping = {
0:"",
1:"one",
2:"two",
3:"three",
4:"four",
5:"five",
6:"six",
7:"seven",
8:"eight",
9:"nine",
10:"ten",
11:"eleven",
12:"twelve",
13:"thirteen",
14:"fourteen",
15:"fifteen",
16:"sixteen",
17:"seventeen",
18:"eighteen",
19:"nineteen",
20:"twenty",
30:"thirty",
40:"fourty",
50:"fifty",
60:"sixty",
70:"seventy",
80:"eighty",
90:"ninety",
100:"onehundred",
200:"twohundred",
300:"threehundred",
400:"fourhundred",
500:"fivehundred",
600:"sixhundred",
700:"sevenhundred",
800:"eighthundred",
900:"ninehundred",
}
return mapping[num]
if __name__ == '__main__':
pass
The error means that a function was used where there should have been a list, like this:
def foo(): pass
foo[3]
You must have changed some code.
By the way, wordify(40) returned "fourty". I spell it "forty"
And you have no entry for zero
In case someone looks here and has the same problem I had, you can also get a pointer to a function object if the wrong variable name is returned. For example, if you have function like this:
def foo():
my_return_val = 0
return return_val
my_val = foo()
then my_val will be a pointer to a function object which is another cause to "TypeError: 'function' object is unsubscriptable" if my_val is treated like a list or array when it really is a function object.
The solution? Simple! Fix the variable name in foo that is returned to my_return_val.

Categories