raw_input('What are you doing? ')
a = 'nothing'
if type(a):
print 'That seems boring'
else:
print 'Nice'
The meaning of this code, is that if a person answers the raw_input with 'nothing'. It should print that seems boring. And if a person writes something else it should print ok.
I am new to programming so please help me :)
If I understood your question correctly, what you are looking for is:
a = raw_input("What are you doing?")
Notice that the answer to the prompt is saved in the variable 'a'.
if a == 'nothing':
print 'That seems boring'
else:
print 'Nice'
Pay attention to the indentation. Also, we use '==' for comparison and '=' for assigning values to a variable.
I suggest you learn basics of python from https://www.codecademy.com/
I always like to make variables that show what they contain.
My version would look like this:
print "What are you doing?"
reply = raw_input()
if reply == "nothing":
print "That seems boring"
else:
print "Nice"
You can also do it like this, it will take input during run time in more oriented way
#!/usr/bin/env python
def user_input():
print "What are you doing?"
# takes user input
a = raw_input()
# if user enter "Nothing" or "nothing"
if (a == "Nothing") or (a == "nothing"):
print "boring"
# if he enters anything else
else:
print "nice"
if __name__ == '__main__':
user_input()
Related
I wonder if the first if statement is True, whether are the following elif executed or not (even if they are also True) ?
I have tried:
if True:
print "Hi"
elif True:
print "hello"
And it prints only "Hi". But in a more complex part of my code, I see some print outputs displayed that are within some elif statements and I just basically switch the very first if to True so that none of the elif should be executed for testing purposes. So why are the print statement that are within the elif printed?
(code is too long to print here, I just wonder if it could be an answer without...)
An elif will only be entered if the condition matches and the previous condition does not:
>>> if x == True:
... print 'hi'
... elif x == False:
... print 'bye'
...
hi
>>> if x == True:
... print 'hi'
... elif x == True:
... print 'bye' #not entered because previous condition was valid
...
hi
>>>
I'm not sure if I understand this correctly, but have you tried else?
if True:
print "Hi"
else:
print "Hello"
EDIT: Sorry, understood what you mean now..
I might be wrong, but "elif" means "else if"
So what you're basicly writing is like this:
If i have 5 apples, i put up a hand
else if i have 5 apples, i put up a leg.
using elif should however not be used at the end of a statement/code. If you aren't going to compare more than 2 statements, use 'if' and 'else'
But why should you have 2 'True'?
In an [if, elif, else] blocks only the first block with the condition that checks out will be executed.
but considering your situation I guess it needs more context to understand it fully, post part of the code you're testing or something with the same logic.
Greetings stackoverflow,
I am pretty new to both this website and python.
I wrote a simple program to create a list of devisors based on a user inputted number, the program works (as far as I know)
But I am pretty sure my syntax is extremely amateurish, so I ask the fluent among you, what can I do to make this:
divisors = []
def devisors(x):
while True:
try:
for i in range(1,x+1):
if x%i==0:
divisors.append(i)
if x==i:
break
except ValueError, TypeError:
return "Invalid input."
continue
print "The list of divisors of",x,"Are: ", divisors
choice1= raw_input("Would you like to use devisors program?(Y/N): ")
while True:
try:
if choice1 in yes:
x = int(raw_input("Please enter a number: "))
devisors(x)
elif choice1 in no:
print "Alright, bye bye."
break
else:
print "invalid input"
choice1= raw_input("Would you like to use devisors program(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
try:
choice2= raw_input("Would you like to try again?(Y/N): ")
if choice2 in yes:
divisors = []
continue
devisors(x)
elif choice2 in no:
print "Alright, bye bye. "
break
else:
print "invalid input"
choice2= raw_input("Would you like to try again?(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
Better written?
I want you to go berserk on this code, tell me (If you feel like it) what could be done to improve it, to write less lines, and mistakes I made.
Also I am not sure if this is something allowed on stackoverflow, if not, please let me know and I'll delete this.
Thank you.
Looking forward to the feedback.
First of all, we do have a dedicated Stack Exchange Code Review site, but you're not the only one asking for a code review here.
The first thing I noticed is that you are trying to hard to put everything in a single method.
Whenever you are faced with a problem or task you should try to divide it into the smallest possible problems. Afterwards we can implement the solution to these small problems as functions.
In your example your tasks are the following:
Get user input of a number
Get the divisors of that number
Print the divisors
Ask if the user wants to give it another try
Let's start with the 2nd point of our list:
def divisors_of(x):
if x < 0:
raise ValueError("Value cannot be smaller than 0")
divisors = []
for i in range(1, x + 1):
if x % i == 0:
divisors.append(i)
return divisors
That doesn't look too bad, does it?
After implementing the user input for a number and printing the result, we already get something like this:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
Looking at our task list we still don't ask the user for another try. Again, IMHO it's more readable if we put the logic for that in a function. This has two additional benefits, we can convert the yes/no choice to a boolean and the written code is reuseable:
def yes_no_choice(text):
while True:
choice = raw_input(text)
if choice in "yes":
return True
# Returning like this is called early return
# As we jump out of the function, the code after
# the if is automatically the else statement
# The code is shorter and more readable
if choice in "no":
return False
print "Invalid answer"
Our final result looks like this:
while True:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
if not yes_no_choice("Would you like to try again?(Y/N): "):
print "Bye!"
break
# else we will loop
Oh, and try not to use global variables if you don't have to. I'm looking at your divisors = []
I just started to learn python about a week ago. I tried to create a simple hangman game today. All of my code in this works so far, but there is one thing that I cannot think of how to implement. I want the code to print 'you win' when it the player correctly types 'python', letter by letter. But I cant seem to end it after they get it right. It will end if they type 'python' in one attempt, opposed to letter form. My attempt to do it is on the line with the .join. I can't seem to figure it out though. Any help or advice for a new programmer would be greatly appreciated.
guesses = []
count = 1
ans = 'python'
word = ''
while count < 10:
guess = raw_input('guess a letter: ')
guesses.append(guess)
if ''.join(word) == ans:
print 'you win'
break
elif len(guess) > 1 and ans == guess:
print ans
print 'you win'
break
else:
for char in ans:
if char in guesses:
word.append(char)
print char,
else:
print '_',
count += 1
else:
print '\nyou lose'
First, I want to start off by saying, unless you are dealing with legacy code or some library which you need that only works in 2.7, do not use python 2.7, instead use python 3.x (currently on 3.6). This is because soon 2.7 will be deprecated, and 3.6 + has a lot more features and a lot of QOL improvements to the syntax and language you will appreciate (and has support for functionality that 2.7 just doesn't have now).
With that said, I'll make the translation to 3.6 for you. it barely makes a difference.
guesses = []
count = 1
ans = 'python'
word = ''
while count < 10:
guess = input('guess a letter: ')
guesses.append(guess)
if ''.join(word) == ans:
print('you win')
break
elif len(guess) > 1 and ans == guess:
print(ans)
print('you win')
break
else:
for char in ans:
if char in guesses:
word.append(char)
print(char)
else:
print('_')
count += 1
else:
print('\nyou lose')
The only two changes here are that print now requires parenthesis, so every print 'stuff' is now print('stuff'), and raw_input is now input('input prompt'). Other than that, I'm suprised you were able to get away with word.append(char). You cannot use append() on a python str in either 2.7 or 3.x. I think you were trying to use it as an array, as that is the only reason you would use ''.join(word). To fix this I would do word = [] instead of word = ''. now your ''.join(word) should work properly.
I would advise you to take the next step and try to implement the following things to your program: If the user doesn't enter a single character, make it so that the characters are not added to the guesses list. Try making this a main.py file if you haven't already. Make parts of the program into functions. Add a new game command. Add an actual hangman in chars print out every time. Add file io to read guess words (ie instead of just python, you could add a lot of words inside of a file to chose).
How can I get my code to respond to string inputs? I want it to do something if the answer is yes or no. I tried something like this.
yes = 'yes'
yesOrNo = input('yes or no?')
if yesOrNo == yes:
print'you said yes'
No matter what I typed for the input, it always would say,'you said yes'.
In Python 2 input doesn't return a string, but an object. To do something like this you would want
choice = raw_input('yes or no?\n')
if choice == 'yes':
print 'you said yes'
else:
print 'you said no'
raw_input does return a string.
I'm sure this is super basic to everyone but for some reason I cannot figure out the code below only prints out "Glad to see you back at it again."
I'm new to programming and this is my first attempt to create something small to interact with. Any ideas why the other options in elif and else dont print?
def was_read():
print "Have you read this before?"
read = raw_input('Yes or No? ')
if read == 'Yes' or 'yes':
print 'Glad to see you back at it again.'
elif read == 'No' or 'no':
print 'Hope its a good one then!'
else:
print "I'm sorry I didn't understand that"
was_read()
While Python may look like English, it isn't English. What you wrote will it be interpreted like:
if (read == 'Yes') or ('yes')
'yes' is truthy, so your if statement really acts like:
if (read == 'Yes') or True
False or True and True or True are both True, so your first if statement will always be true.
Be explicit:
if read == 'Yes' or read == 'yes'
Or just do it the simpler way:
if read.lower() == 'yes'