This is the code that I made when I tried making an if-then statement but, it always defaults to else. Also i just started trying to code from online tutorials today.
print('yes or no?')
if sys.stdin.readline() == 'yes' :
print('Yay')
else :
print('Aww')
This is what happens:
Console:yes or no?
Me:yes
Console:Aww
I've been looking stuff up for half an hour and can't figure out how to fix this please help
sys.stdin.readline() reads a line which ends with '\n' (when you hit "enter").
So you need to remove this '\n' from the captured input using strip().
print('yes or no?')
if sys.stdin.readline().strip() == 'yes' :
print('Yay')
else :
print('Aww')
I tried to explain and solve your specific problem but you could of course use raw_input() or input() (PY3) as mentioned in the other answer.
In python, getting the input of a user's string can be done via input() (or in python 2.7, use raw_input()).
If you include the code:
user_input = raw_input("yes or no?")
This will first print the string "yes or no?", then wait for user input (through stdin), then save it as a string named user_input.
So, you change your code to be:
user_input = raw_input("yes or no?")
if user_input == "yes":
print("Yay")
else:
print("Aww")
this should have the desired effect.
Ok I used user_input and input instead of sys.stdin.readline() on strings and i used it in a basic calculator here it is :
import random
import sys
import os
user_input = input("Would you like to add or subtract?")
if user_input == 'add' :
print('What would you like to add?')
plus1 = float(sys.stdin.readline())
print('Ok so %.1f plus what?' % (float(plus1)))
plus2 = float(sys.stdin.readline())
print('%.1f plus %.1f equals %.1f' % (float(plus1),float(plus2), float(plus1+plus2)))
elif user_input == 'subtract' :
print('What would you like to subtract?')
minus1 = float(sys.stdin.readline())
print('Ok so %.1f minus what?' % (float(minus1)))
minus2 = float(sys.stdin.readline())
print('%.1f minus %.1f equals %.1f' % (float(minus1), float(minus2), float(minus1 - minus2)))
else :
print('That is not one of the above options')
Thanks alot guys!
Related
I am attempting to make a game that I made via Rpg Maker MV in python but I've hit a road block in the if statement or rather the gender input. The code is meant to have the user input either "Boy" or "Girl" and depending on that the variable "gender" will be set for pronouns. How ever the console is saying This
This is the code
import time
print ("Elvoria")
print ("Start")
input = input()
if input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if input == ("Boy"):
gender = 1
elif input == ("Girl"):
gender = 2
else:
print ("Error")
You need to check the input using the variable name genderin that you defined, instead of input == ("Boy").
EDIT: Also, you are mirroring the built-in method input() with the variable name input and you should not do that. Rename your variable to e.g. start_input.
import time
print ("Elvoria")
print ("Start")
start_input = input()
if start_input == "Start":
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print ("Error")
You're defining the variable "input" on line 4 to be a string, given from the "input" function. This overrides the keyword. Then, on line 9, you're calling "input" again. Since you've replaced the built-in function with a string, an error is thrown (the error "not callable" means that you're trying to treat a non-function like a function).
Here's your code sample, without overriding built-in methods:
import time
print ("Elvoria")
print ("Start")
user_input = input()
if user_input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == ("Boy"):
gender = 1
elif genderin == ("Girl"):
gender = 2
else:
print ("Error")
You should avoid using input as a varible name, since a built-in function with that name already exists, input(). So just change it's name to something else. Secondly, you're storing the gender input (boy/girl) in genderin, but then checking input, when you should be checking genderin. So the code after fixing these would look something like this:
import time
print ("Elvoria")
print ("Start")
choice = input()
if choice == "Start":
print("Always Great To See New People")
time.sleep(1)
print("Now Are You A Boy Or Girl?")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print("Error")
I have used choice for demonstration purposes, you can use a different name if you want, just remember to make sure that a python built-in with that name doesn't exist. Also, no need to put ("Start") in the if statement, use "Start" instead (same goes for other if/elif statements)
You have also used print ("example") (space between print and brackets), i've rarely ever seen someone using this, most people use print("example") instead.
Finally a tip -> You can make the string lowercase, genderin = genderin.lower() to manage case sensitivity, i.e, both boy and Boy will be valid inputs, etc.
I'm a complete newbie to the coding trying my hands on python. While coding a simple program to calculate the age I ran into an error I cannot seem to fix no matter how hard I try. The code is pasted below. The program runs as far as I enter an year in the future, however when an year which has passed is used, the code loops again asking if the year is correct. Any help is appreciated.
from datetime import date
current_year = (date.today().year)
print('What is your age?')
myAge = input()
print('future_year?')
your_age_in_a_future_year= input()
future_age= int(myAge)+ (int(your_age_in_a_future_year)) - int(current_year)
def process ():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = input()
if answer =='yes':
print (future_age)
if answer == 'no':
print ('cya')
while answer != 'yes' or 'no':
print ('enter correct response')
process ()
process()
In this case, your function just needs to contain a while loop with an appropriate condition, and then there is no need to break out from it, or do a recursive call or anything.
def process():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')
try
...
if future_age > 0:
print(future_age)
return
else:
print('do you really want to go back in time?, enter "yes" or "no"')
...
I'm currently in year 10 and I'm creating a program which tells the user if their ransom note can be created from an article they have inputted. Some of the inputs I've been typing in come up with the error: TypeError: Can't convert 'NoneType' object to str implicitly
It seems to work at first but then I typed in "hello" as my ransom note and "hell" as my article and it came up with the error above. I thought it might've been because the article is shorter than the note but I tried it with other inputs and that doesn't seem to be the problem. I've included the function in case that might have something to do with it. Sorry if my code is a bit messy or inefficient.
elif choice == "2" :
user_note = input("\nPlease enter your ransom note: ")
user_article = input("Please enter your article: ")
print("\n" + can_I_ransom(user_article, user_note))
can_I_ransom function:
def can_I_ransom(newspaper_text, ransom_text):
article_list = list(newspaper_text)
article_copy = list(newspaper_text)
for i in range(len(ransom_text)):
for j in range(len(article_list)):
if ransom_text[i] == article_list[j]:
del article_list[j]
if len(article_copy)-len(ransom_text) == len(article_list):
return "Ransom can be made"
break
else:
if j == len(article_list)-1:
return "Ransom note cannot be made"
I'm expecting the output to be either "Ransom can be made" or "Ransom note cannot be made" and nothing else. Please help if you can :)
The problem is that when the ransom cannot be made, you aren't returning anything, and so it doesn't know what to do with a None which is what comes out when you just break without actually getting a "You can ransom" output. For example, what happens if the first if statement is true but the second isn't? Or if the first if statement is false and the second is false? This is why it only happens for some inputs - it only happens on the ones that slip through the cracks on the if statements. Also, I'm not quite sure your indentation is right for the outer else statement you have. Try running this:
def can_I_ransom(newspaper_text, ransom_text):
article_list = list(newspaper_text)
article_copy = list(newspaper_text)
for i in range(len(ransom_text)):
for j in range(len(article_list)):
if ransom_text[i] == article_list[j]:
del article_list[j]
if len(article_copy)-len(ransom_text) == len(article_list):
return "Ransom can be made"
else:
return "something"
else:
if j == len(article_list)-1:
return "Ransom note cannot be made"
else:
return "something"
choice = "2"
if choice == "2" :
user_note = input("\nPlease enter your ransom note: ")
user_article = input("Please enter your article: ")
print("\n" + can_I_ransom(user_article, user_note))
Just change the "something"s to the appropriate response.
First off. My code:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
I am not that good at coding, so this is probably something that I have done really wrong
This post seems a bit duchy, since I almost just have code,
but I have absolutely no idea on how to make this work.
What the code looks like without shortening:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
EDIT: I see that it might be hard to see what I'm asking.
I'm wondering how I can shorten my original code
If all your elif blocks have the same pattern, you can take advantage of this.
You can create a dictionary for the text you want to print and then do away with the conditionals.When it comes to choosing which one to print, you simply fetch the relevant text using its corresponding key. You use the get(key, default) method. If there is no key in the dictionary, the default value will be returned. For example,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
I found a solution, just stop using elif entirely.
Example:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")
I have a feeling I've made a silly mistake somewhere but at nearly 2am I just can't see it...
Here's the code in question. It is part of a function:
running = True
while (running):
playerName = input("Please enter your first name \n").title()
print ("You have entered '%s' as your name. Is this correct?"%playerName)
playerNameChoice = input("Enter 'Y' for Yes or 'N' for No.\n").upper()
if(playerNameChoice == "Y"):
break
#The following randomly selects Card 1 for the computer
randomComputerCard = random.choice(availableCards)
if randomComputerCard in (Queen,King,Jack,Ace):
randomComputerCard = 10
else:
randomComputerCard = randomComputerCard
randomComputerCard2 = random.choice(availableCards)
if randomComputerCard2 in (Queen,King,Jack,Ace):
randomComputerCard2 = 10
else:
randomComputerCard2 = randomComputerCard2
print ("%i"%randomComputerCard)
print ("%i"%randomComputerCard2)
print ("TEST OVER")
elif(playerNameChoice == "N"):
continue
During testing when I enter Y when prompted to enter either Y or N nothing happens, it just continues the loop when it should actually break. However when I enter N it does exactly what it's meant to and continues the loop. Sorry if this is a waste of a question, but I actually have no idea what I've done incorrectly.
Thanks in advance as always! :)
EDIT: The variable availableCards has already been defined.
You need to remove the 'break' at line 7. That's causing your code to exit prematurely.