I just started learning python 2 days ago and Im trying to make some kind of text based adventure to practice , the only problem Im having is with functions:
def menu_op():
print('1- Action 1')
print('2- Action 2')
choice= input('Choose action: ')
return choice
def action_op(x):
if x == 1:
print('You chose action 1')
if x == 2:
print('You chose action 2')
menu_op()
action_op(menu_op())
The idea behind this is to call the menu function , which gives a value equal to user's input , which gets fed into the action function when the latter is called and does something depending on the user choice.
Cant tell what im doing wrong though , as the code doesnt seem to work.
Thanks in advance
It looks like you are using Python 3.x. In that version, input returns a string object like raw_input did in Python 2.x. This means that the return value of the function menu_op will always be a string.
Because of this, you need to compare x with strings rather than integers:
if x == '1':
print('You chose action 1')
elif x == '2':
print('You chose action 2')
I also changed the second if to elif since x could never equal both '1' and '2'.
You're calling menu_op() function twice. The first time it gets called choice is not passed to action_op()
menu_op() #return is not catched
action_op(menu_op())
And the value returned from menu_op is a string so you should compare strings in action_op instead of comparing x with integers
def action_op(x):
if x == 1:
^^^ #should compare strings here -> x == "1"
choice= int(input('Choose action: ')) # make choice an int to compare
In [1]: 1 == "1"
Out[1]: False
In [2]: 1 == int("1")
Out[2]: True
input is a string and you are comparing if x == 1 where x is "1"
Related
I'm learning python since few weeks ago and I need some help with a code. I'm triying to run a code that display certain value according to the input given by the user, so if user enters 1, x value is shown. I've tried a lot of different ways to do it but surely I'm skipping or ignoring something. How could I make this work? Thanks. (This code only prints second_statement no matter what the user inputs).
def first_statement(x):
print("xxxx")
def second_statement(x):
print("yyyy")
x = input("If you want x thing press 1, otherwise, press 2: ")
if x == 1:
print(first_statement(x))
else:
print(second_statement(x))
You can change 1 to '1' in if statement or just convert input to int using int() in input line.
First way
def first_statement(x):
print("xxxx")
def second_statement(x):
print("yyyy")
x = input("If you want x thing press 1, otherwise, press 2: ")
if x == '1':
print(first_statement(x))
else:
print(second_statement(x))
second way
def first_statement(x):
print("xxxx")
def second_statement(x):
print("yyyy")
x = int(input("If you want x thing press 1, otherwise, press 2: "))
if x == 1:
print(first_statement(x))
else:
print(second_statement(x))
Error:
Because input gives a string even if you enter a number so you have to convert it to a number using int or float.
or use string to compare with the input.
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
I'm trying to figure out if there is a way to "force" a Python script to not "throw me back" into the bash environment if I commit a simple error in my Python script.
Here's an MWE (MWE.py) to illustrate the point:
How can you tell Python NOT to kick me out of the program if I press 3 in the MWE below?
x = raw_input("Please input a number 1 or 2: ")
if (x == '1'):
print '1'
elif (x == '2'):
print '2'
#else:
#print 'Neither 1 nor 2.'
Notice that my last two lines are commented out. If I uncomment them, obviously I will get the respective print statement and the program will finish successfully. However, let's assume that I didn't have those last two lines, and wanted MWE.py to "stay in Python mode" (so to speak) and not harshly return me to the bash shell, thereby forcing me to rerun from scratch with python MWE.py.
Is there a way to accomplish this somehow?
Obviously, this is a trivial MWE but I'm trying to understand the principle: is it possible to just return the last prompt that I was presented with right before I committed an input error (such as committed in this MWE when I pressed 3). Is there basically a "generalized way" to get back to x = raw_input("Please input a number 1 or 2: ") (or whatever else was the most recent prompt that I was given before I made an input error)?
This seems particularly important in programs that require multiple user inputs at different stages. I would hate to start all over.
It's called a loop (the parentheses around the conditions are not required):
x = None
while x != '1' and x != '2':
x = raw_input("Please input a number 1 or 2: ")
if x == '1':
print '1'
elif x == '2':
print '2'
else:
print 'Neither 1 nor 2.'
print "all OK"
There are many ways of writing this. You should pay attention to how you initialise x before the loop, None is typical in python.
Also note the the value of x is a string, not an int.
This would quickly become unwieldy if you had a large number of possible values to test. So an alternative approach is to use an infinite loop and break out on a correct reply:
x = None
while True:
x = raw_input("Please input a number 1 or 2: ")
if x == '1':
print '1'
break
elif x == '2':
print '2'
break
else:
print 'Invalid input, try again'
print "all OK"
I am struggling with local and global variables.
I was doing this:
def SomeFunc(Input):
if Input == 1:
Input = "True"
elif Input == 0:
Input = "False"
RawInput=int(raw_input("Input 1 or 0: "))
SomeFunc(RawInput)
print str(RawInput)
and it showed this:
>>> def SomeFunc(Input):
if Input ==1:
Input = "True"
elif Input ==0:
Input = "False"
>>> RawInput = int(raw_input("Input 1 or 0: "))
Input 1 or 0: 1
>>> SomeFunc(RawInput)
>>> print str(RawInput)
1
What should I do so that the input will convert to str in the function?
Input is an int which is an immutable object. In other words, you can't change it anywhere. However, you can assign it to something else. One of the tricky things about python is learning that everything is just a reference. When you assign to something, you just change the reference. Think about your variables as strings which go into boxes. When you assign to a variable, you put that string in a particular box. When you assign that variable to something else, you change the box that string goes to. Of course, when you actually do an addition, you add the contents of the box, not the strings (which is a little confusing). If you're accustomed to programming in C, it's kind of like everything is a pointer which gets automatically dereferenced (except when you do an assignment).
So, what to do? The easiest thing is to return the value from your function.
def some_func(inpt):
if inpt == 1:
return "True"
elif inpt == 0:
return "False"
else:
raise ValueError("WHAT IS THIS GARBAGE? I SAID 0 OR 1!!!!") # ;^)
Now you can call your function as:
processed_input = some_func(rw_inpt)
as a side note, your function can be condensed to:
def some_func(inpt):
return str(bool(inpt))
or
def some_func(inpt):
return "True" if inpt else "False"
Both of these pass (and return "True" if the user puts in any integer that isn't 0). If you really want to force the user to not put in something like "2", you can do:
def some_func(inpt):
return {1:"True",0:"False"}[inpt]
But I wouldn't recommend that one...
Basically you want the argument to be pass-by-reference, but that is not how Python works for basic datatypes. The pythonic way of doing this is as following:
def some_func(input):
if input == 1:
return "True"
elif input == 0:
return "False"
And then
raw_input = some_func(raw_input)
Note: You can just do this: print bool(int(raw_input("Input 1 or 0: ")))
The more pythonic way of doing it would be as follows:
def some_func(x):
if x == 1:
return "True"
elif x == 0:
return "False"
x = int(raw_input("Input 1 or 0: "))
x = some_func(x)
print x
However if you did want to use globals you could do it like this but this is really hacky and it isn't one of the good coding practices that python promotes.
def some_func():
global x
if x == 1:
x = "True"
elif x == 0:
x = "False"
x = int(raw_input("Input 1 or 0: "))
some_func()
print x
Some other notes:
Try not to use names like the bultins eg. Input and RawInput since it makes things unclear and mixes everything up.
What should I do so that the input will convert to str in the
function?
def SomeFunc(Input):
as_string = str(Input)
if Input == '1':
Input = "True"
elif Input == '0':
Input = "False"
Note that python has a native boolean type, including the values True and False already. You can use the integer value of Input as a condition all on its own.
I have updated my code with the changes made. I am still getting incorrect results...
# Import statements
import random
# Define main function that will ask for input, generate computer choice,
# determine winner and show output when finished.
def main():
# Initialize Accumulators
tie = 0
win = 0
lose = 0
score = 0
# initialize variables
user = 0
computer = 0
# Initialize loop control variable
again = 'y'
while again == 'y':
userInput()
computerInput()
if score == win:
print('You won this round, good job!')
win += 1
elif score == tie:
print('You tied this round, please try again!')
tie += 1
else:
print('You lost this round, please try again!')
lose += 1
again = input('Would you like to play another round (y/n)? ')
#determine winning average
average = (win / (win + lose + tie))
print('You won ', win, 'games against the computer!')
print('You lost ', lose, 'games against the computer.')
print('You tied with the computer for', tie)
print('Your winning average is', average)
print('Thanks for playing!!')
# get user input for calculation
def userInput():
print('Welcome to Rock, Paper, Scissor!')
print('Please make your selection and and Good Luck!')
print('1) Rock')
print('2) Paper')
print('3) Scissor')
user = int(input('Please enter your selection here: '))
print('You selected', user)
# get compter input for calculation
def computerInput():
computer = random.randint(1, 3)
print('The computer chose', computer)
def getScore():
if user == 1 and computer == 3:
score = win
return score
elif user == 2 and computer == 1:
score = win
return score
elif user == 3 and computer == 2:
score = win
return score
elif user == computer:
score = tie
return score
else:
score = lose
return score
# Call Main
main()
In Python:
>>> print("3" == 3)
False
Strings and integers are values of different data types, and will not compare equal. Try changing your input to:
userInput = int(input('Please enter your selection here: '))
This will convert the string typed by the user to a number for later comparison. (Note that I have assumed you are using Python 3.x, because input() behaves slightly differently in Python 2.x.)
Note that this will throw an error if you type anything other than a number.
Update: As pointed out by #FelipeFG in the comments below, you are also overwriting the function userInput with the value typed by the user. You'll need to change the name of one or the other, for example:
def getUserInput():
...
Also don't forget to change the place where you call the function. Do the same for computerInput (change to getComputerInput).
Later on, you can change those to actual functions that return values.
userInput() calls the function "userInput", but you discard the result. The same remark applies to computerInput().
userInput == 1 asks whether the function userInput itself is equal to 1. It isn't. The same remark applies to computerInput == 3 and the others.
In the function "userInput", userInput = ... binds the name "userInput" to the result of the expression. This makes "userInput" a local variable of the function. The function doesn't explcitly return anything, therefore it returns None.
If you're using Python 3, input returns a string, and you should convert its result to an int. If you're using Python 2, input evaluates whatever is entered, which isn't safe; you should use raw_input instead and convert its result to an int.
You need to compare against the return value of your function, not the function itself.
Also:
again = input('Would you like to play another round (y/n)? ')
This will throw an exception if you enter y or n, because there is no defined identifier of that name! What you want to use instead is raw_input()
Edit: As pointed out by Greg, this only applies to Python 2.x. You seem to be using Python3 though.