Function with more choices - python

I created a simple key stroke counter code that prints number of entered letters. However I am trying to figure out how to make a function so it recognizes 1 letter from 2 letters (singular and plural). I would like to add also 'stroke' in my code, and when the keyboard key is entered only once Id like it to print "You entered 1 stroke" instead of "You entered 1 strokes.".
I tried something but cant really move forward:
print('Start typing: ')
count = raw_input()
print('You entered:'), len(count), ('strokes')

Just use normal conditionals, e.g. using a conditional expression:
print "You entered:", len(count), 'stroke' if len(count) == 1 else 'strokes'
Also, just for fun, the overly clever for the sake of brevity solution that you should not actually use:
print "You entered:", len(count), 'strokes'[:6+(len(count) != 1)]
or:
print "You entered:", len(count), 'stroke' + 's' * (len(count) != 1)

You can use if and else:
if len(count) == 1:
print 'you entered: 1 stroke'
else:
print 'you entered: {} strokes'.format(len(strokes))

Instead of using multiple arguments to print, you can also use string formatting:
print "You entered {} stroke{}".format(len(count), "s"*(len(count)!=1))
Admittedly, the last part is a bit exotic, but you can of course also do
print "You entered {} stroke{}".format(len(count), "s" if len(count) != 1 else "")

Related

Python; How do I test if something is in a list?

I was writing a code that will ask you to play a guessing game. It will ask you whether you want to play or not and proceed.
It was supposed to ask a number again if the entered value is not in the list but It is not working. I couldn't get it. Thx by now!
import random
import math
import time
repeat=True
numbers = ["1","2","3","4","5"]
gamestart=False
gamecontinue=True
def guess():
chosennumber=random.choice(numbers)
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber==chosennumber and guessnumber in numbers:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
print
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
elif not guessnumber in numbers:
while not guessnumber in numbers:
guessnumber=raw_input(">Please enter a number between 0 and 6:")
if raw_input(">Do you want to play guessing game? Y or N:") == "Y":
gamestart=True
else:
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
while gamestart==True and gamecontinue==True:
guess()
if raw_input (">Do you want to play again? Y or N:") == "N":
gamecontinue=False
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
so you figured out what was the issue, good! but i have one more tip for you, a better approach to achieve this is check if the input is correct as soon is readed, if it is correct you keep going, if it not, you ask for it again right there:
while True:
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber in numbers:
print "good!"
break
else:
print "bad!"
and now you're sure that the input is correct so you only check:
if guessnumber==chosennumber:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
else:
print "That is not right."
print "I chose %d." % (int(chosennumber))
if number not in numbers
That will do the trick
It checks if it is true that the selected number is in the list
The problem is that if you put two elif statements the first one will proceed first.
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
This condition will be asked first. But if you look again at it whether the input (guessnumber) is in the list or not it will proceed. So if we want it to become a condition which we enter a number that is in a list but not matching with the chosen number, we will add another condition to elif statement.
code will be like this
elif guessnumber!=chosennumber and guessnumber in numbers:
Slight detail but good to keep in mind I think.

Prompt error message for python

def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter")
if answer == 'a' or 'A':
print "You chose 'a'!"
elif answer == 'b' or 'B':
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()
This is my code. It's very simple, but for some reason it keeps returning and error message of reference error: 'prompt' is undefined
This is probably not going to solve the problem you are having (although the code worked for me in an iPython shell), there is an issue with your if/else statements. The following statement:
if answer == 'a' or 'A':
print "You chose 'a'!"
will always print "You chose 'a'!" regardless of the letter you enter upon prompting. In python, the or expression you are using asks the following question: Is the answer given equal to 'a' OR is the boolean value of "A" True? What you mean to ask is: Is the answer given equal to 'a' OR is the answer given equal to "A"? This is most concisely represented through:
if answer.lower() == 'a':
print "You chose 'a'!"
That should solve at least one problem that this code is having.
As #Bhargav Rao commented, your code does not match your error, when you run it you will get an output of a regardless of what you enter.
This is because if answer == 'a' or 'A': is the same as saying:
if answer == 'a': OR if 'A': <-- this is always true
To fix this you can use the condition in:
def choosing_room():
print "Welcome! You now must choose!"
answer = raw_input("Type a or b and hit Enter: ")
if answer in ['a','A']:
print "You chose 'a'!"
elif answer in ['b','B']:
print "You chose 'b'!"
else:
print "That is incorrect, please try again"
choosing_room()
choosing_room()

Display Variable value in Python using print Statement?

I have created a Python program that guesses the number programmer thinks in mind. Everything is working file but i don't know how to use guess in print statement in a way that print statement display number as well. I tried adding word "guess" but it is not working. I am C programmer and working with Python for the first time, so i am unable to figure it out.
hi = 100
lo = 0
guessed = False
print ("Please think of a number between 0 and 100!")
while not guessed:
guess = (hi + lo)/2
print ("Is your secret number " + //Here i need to Display the guessed Number + "?")
user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too"
"low. Enter 'c' to indicate I guessed correctly: ")
if user_inp == 'c':
guessed = True
elif user_inp == 'h':
hi = guess
elif user_inp == 'l':
lo = guess
else:
print ("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: " + //Here i need to display final number saved in guess.)
Just convert it to string.
print ("Game over. Your secret number was: " + str(guess))
You could also use string formatting.
print("Game over. Your secret number was {}".format(guess))
Or, since you come from a C background, old style string formatting.
print("Game over. Your secret number was %d." % guess)
Try this in your print statement and let me know if it works.
str(guess)
Python has very nice string formatting, which comes in handy when you need to insert multiple variables:
message = "Game over after {n} guesses. Your number was {g} (pooh... got it in {n} times)".format(g=guess, n=number)
print(message)

Python While Loop woes

I am a brand new programmer, and I have been trying to learn Python (2.7). I found a few exercise online to attempt, and one involves the creation of a simple guessing game.
Try as i might, I cannot figure out what is wrong with my code. The while loop within it executes correctly if the number is guessed correctly the first time. Also, if a lower number is guessed on first try, the correct code block executes - but then all subsequent "guesses" yield the code block for the "higher" number, regardless of the inputs. I have printed out the variables throughout the code to try and see what is going on - but it has not helped. Any insight would be greatly appreciated. Thanks! Here is my code:
from random import randint
answer = randint(1, 100)
print answer
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print "Top of Loop"
print guess
print answer
i = i + 1
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
else:
print "else statement"
print "Congratulations! You got it in %r guesses." % i
print "Time to play a guessing game!"
print "Enter a number between 1 and 100:"
guess = raw_input()
guess = int(guess)
logic(guess, answer, i)
I'm sure it is something obvious, and I apoloogize in advance if I am just being stupid.
You've noticed that raw_input() returns a string (as I have noticed at the bottom of your code). But you forgot to change the input to an integer inside the while loop.
Because it is a string, it will always be greater than a number ("hi" > n), thus that is why "Too high. Try again:" is always being called.
So, just change guess = raw_input() to guess = int(raw_input())
Try this:
guess = int(raw_input())
As raw_input.__doc__ describes, the return type is a string (and you want an int). This means you're comparing an int against a string, which results in the seemingly wrong result you're obtaining. See this answer for more info.
Ok, I found your problem. The problem is in this Code:
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
In the code above you are getting your input as string, but you try to compare it with integer. All you need to do is to convert the input to integer, like this:
guess = raw_input()
guess = int(guess)
This should solve your problem :)
I updated the program. You came out of the while loop because after you get guesss as input inside elif group, you forget to convert that to int, so it throwed back error. Now, corrected but you can also optimise it.
import sys
from random import randint
answer = randint(1, 100)
'''randint(1, 100)'''
print (answer)
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print ("Top of Loop")
print (guess)
print (answer)
i = i + 1
if guess < answer:
print ("Too low. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
elif guess > answer:
print ("Too high. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
else:
print ("else statement")
print ("Congratulations! You got it in %r guesses." % i)
print ("Time to play a guessing game!")
print ("Enter a number between 1 and 100:")
guess = input()
guess = int(guess)
logic(guess, answer, i)

`choice == 1` is False even when user enters "1"

I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin.
Here is my script:
import sys
print "********************************************************************"
print "** 1) This is menu choice #1 **"
print "** **"
print "** **"
print "** **"
print "** **"
print "** **"
print "********************************************************************"
print
print "Choice ?"
choice = sys.stdin.readline()
print "You entered: " + choice
if choice == 1:
choice1 = sys.stdin.readline()
print "You entered:" + choice1
else:
quit()
print "Exiting"
When I run the script, I get to the Choice? prompt. I enter 1 and I get the "You entered:" message and then the script exits without displaying the "Exiting" message.
Seems like it should be so easy. Thanks in advance for any help.
You're comparing a string to an integer. Try converting the string into an integer:
if int(choice.strip()) == 1:
Use raw_input() instead of sys.stdin.readline()
Change choice == 1 to choice == '1'
The problem is that readline returns a string, but your if statement expects an int. To convert the string to an int, you could use int(choice.strip()) (be prepared for it to raise an exception if what you enter isn't a valid number).
In [8]: choice
Out[8]: '1\n'
In [9]: int(choice.strip())
Out[9]: 1
Not sure, but I think the user is entering a string, not a number. The number 1 and the string 1 are two completely different things.
Try choice == "1"
The readline function retains the newline at the end of the input. Your first if should be:
if choice == "1\n":
assuming you want the newline.
It's exiting by calling quit() since it takes the else branch. That's because '1' (a string) does not equal 1, an integer.

Categories

Resources