raw_input check to allow for reinitiation of same function - python

I was banging my head against my desk on this one, because I'm an idiot, and I've finally gotten it to work. This is a simplified, dumb version of my actual code (which is why the function's purpose seems so inane) but I'm curious whether there is (or rather, am sure there must be) a more efficient way of doing the following:
def get_char():
character = raw_input("Enter the character you would like to use.\n >")
if character.isalpha:
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed?(Y/N)\n>")
while True:
if proceed in "N,n":
raw_input("Press enter to try again with another value.")
character = get_char()
break
else:
break
return character
#print character
character = get_char()
print character
What I want to end up with is a way of checking that the user's input is what they intended. Until I set character = get_char() in the while loop, I was getting problematic output (i.e. incorrect final values for character); having fixed that, I've noticed that if I include the print statement at the end of the get_char() definition, it prints out the number of times a "no" choice has been made +1. While the end result is still fine, I'm curious whether the fact that it seems to be holding iterations in a queue, as indicated by the multiple prints upon inclusion of the print statement, means that there's a better way of doing this. Thanks in advance for any help!
UPDATE:
Just in case anyone else needs help with this same issue, based on the suggestion by millerdev, I've adjusted the code to the following, which works just the same except without the self-call which was generating unnecessary character queuing:
def get_char():
while True:
character = raw_input("Enter the character you would like to use\n >")
if character.isalpha:
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/N)\n>")
if proceed in ("N", "n"):
raw_input("Press enter to try again with another value.")
else:
break
#print character
return character
character = get_char()

Because of character = get_char(), your loop only runs once, because it will recurse deeper if it fails instead of iterating again. This probably isn't what you want, because it's slower and runs the risk of overflowing the stack. The cleanest way to do this would probably be (you could replace my messages with yours easily):
def get_char(is_valid = lambda c: True):
while True:
c = raw_input('enter a character > ')
if is_valid(c):
keep = raw_input('do you want to use {0}? (Y/N)> '.format(c)).lower()
if 'n' in keep:
continue # go back to While True line
return c
print('{0} is not a valid character'.format(c))
Session:
>>> get_char()
enter a character > a
do you want to use a? (Y/N)> n
enter a character > c
do you want to use c? (Y/N)> no
enter a character > x
do you want to use x? (Y/N)> y
'x'
At least, this is the cleanest in my opinion. Your implementation has a few other problems, like proceed in "N,n", which would also count comma as an n, and if the character isn't isalpha, you still return it.

Is this what you're aiming for?
def get_char():
while True:
character = raw_input("Enter the character you would like to use.\n >")
if character.isalpha: # this is always true; add parens if that's what you want, otherwise remove it
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/n)\n>")
if proceed.lower() == "n":
raw_input("Press enter to try again with another value.")
character = get_char()
return character
character = get_char()
print character

Related

How to make a string that only includes spaces be an invalid input in python

I'm a newbie in coding using python and I'm trying to write a piece of small code that prints whatever you input in the terminal, but I don't want anything that only includes spaces and no other characters or doesn't even have an input to be printed. Here's the code:
while True:
my_name= input("> ")
if "" in my_name:
print("I don't know what that means. Please choose a valid answer.")
else:
print(f"Ah, I see, so your name is {my_name}?")
would love to have multiple solutions to this, and thank you if you helped :)
https://docs.python.org/2/library/stdtypes.html#str.isspace
I think this should do the trick
if my_name.isspace():
print("Your name is full of spaces")
Python isspace() method is used to check space in the string. It returns true if there are only white space characters in the string. Otherwise it returns false.
ex:
# Python isspace() method example
# Variable declaration
str = " " # empty string
# Calling function
str2 = str.isspace()
# Displaying result
print(str2)
There's one way of doing that by using exceptional handling for no input using try - except block and a flag variable that checks if input doesn't contain only spaces.
try:
flag = False
my_name = input()
for i in my_name:
if i != ' ':
flag = True
if flag:
print(my_name)
else:
print('Invalid input')
except:
print('No input')
The other ways can be using the built in function strip() which removes the trailing and leading spaces in input.
If the input has only spaces then strip() will remove all of them resulting in an empty string.
try:
my_name = input()
if my_name.strip() == '':
print('Invalid input')
else:
print(my_name)
except:
print('No input')
Like this, you can use bools:
while True:
my_name= input("> ")
if my_name.strip():
print(f"Ah, I see, so your name is {my_name}?")
else:
print("I don't know what that means. Please choose a valid answer.")

May someone help me figure out how to update my dashes on my python hangman code

I am supposed to be able to update these dashes so that when someone types in "a" the dashes will look like a---a-. And if the user guesses the letter "l", the dashes will look like a---al.
magic_word = "animal"
dashes = "--------"
def get_guess()
while True:
print dashes
guess = str(input("Guess a letter: "))
if len(guess)>1:
print "Too long"
continue
elif not guess.islower():
print "Your guess must be one lowercase letter"
continue
if guess in magic_word :
print "That is in the word"
continue
else:
print "That is not in the word"
continue
return guess
break
get_guess()
You'd want to use a different method to see if the guess is in the magic word.
One such method would be to iterate through the string and whenever the guess is found in the magic word, update the corresponding space in the dashes string:
for x in range(len(magic_word)):
if guess == magic_word[x]:
dashes[x] = guess
Which would update the dashes for you
You should use the "index()" method for finding the index of the character and then by using the "replace()" method for replacing the dashes with that word.
indexOfGuessChar = magic_word.index(guess)
dashes = dashes.replace(dashes[indexOfGuessChar], guess)
something like this will do the trick just put these functions to work and play with it.

How to get both guesses replaced instead of the underscores in my hangman code?

dashes = ""
for i in word_chosen:
dashes = dashes+"_ "
def get_guess():
guess = ""
guess = input("Please can you enter a guess for hangman: ")
return guess
def check_guess(dashes):
if len(guess)>1:
print("word")
else:
if guess in word_chosen:
print("The word contains an ",guess)
# Yes option
dashes_tem = " "
count = 0
# new variable made
for i in word_chosen:
# loop through the word chosen
if i == guess:# check word against guess
dashes_tem = dashes_tem + i + " "
else:
dashes_tem = dashes_tem + dashes[(count*2)] + " "
count = count + 1
return dashes_tem
else:
print("The word doesn't contain an",guess)
# No option - will come back
guess = get_guess()
dashes = check_guess(dashes)
print(dashes)
guess = get_guess()
dashes = check_guess(dashes)
print(dashes)
So I have made my hangman code and am in the middle of coding it when there is two correct guesses however when there is two correct guesses it will just say the word contains 'x' but won't replace the underscore, like it did for the first correct guess.
I'd suggest starting from scratch and using data structures that map to the problem better.
For instance:
Use a set (which is an unordered data structure with constant-time lookup) or a dictionary (of which a set is a degenerate case) to track letters which have already been guessed. To regenerate the word to be displayed, translate all characters not in the set to underscores. Doing this, the exact same logic will be used with any number of unhidden characters, preventing the situation you have here (where something works correctly only with exactly one unhidden character in place).
Break your program logic away from your user input, breaking down logic into components as reusable as possible. For instance, if you have a function:
hide_unguessed(real_word, guessed_letters)
...then you can do something like this:
if hide_unguessed(real_word, guessed_letters) == real_word:
print "You win!"
...outside of that function, rather than putting it inside.
Prefer to store and manipulate state that directly maps to your problem space (the target word, the letters guessed so far) rather than state which can trivially be derived from that content (the currently unhidden set of letters).
Functions you could use as building blocks might look like the following:
def check_guess(real_word, guessed_letter):
return guessed_letter in real_word
def hide_unguessed(real_word, guessed_letters):
return ''.join([letter if letter in guessed_letters else '_' for letter in real_word])
Notice that these are pure functions -- if you know what their inputs are, you'll always know what their return value is (they don't depend on something unpredictable like user input), and they don't have any side effects other than their return value. Prefer to use pure functions whenever you can -- these are far easier to reason about and test than other code.

Coding a language translator

im trying to code a kind of language translator from any language to a kind of gibberish language, wheres every consonant will be replaced with the same consonant plus an o and then the consonant again.
b = bob
d = dod
f = fof
so the text "Hi my name is x"
will become "Hohi momy nonamome isos xox"
The problem i have is the converting part.
any tips on how i can proceed?
Oh and btw I am using python 3
What i got this far.
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z":
i = i + "0" + i
gibberish.append(i)
elif i == "a,o,u,e,i,y":
gibberish.append(i)
#print out the gibberish
print (gibberish)
Yeah! i think i got it to work quite well..
# -*- coding: cp1252 -*-
#Repeat
while True :
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("Give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i in "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ":
i = i + "o" + i
gibberish = gibberish + i
elif i in "aoueiyåäö AOUEIYÅÄÖ":
gibberish = gibberish + i
#print out the gibberish
print (gibberish)
print ("\n")
Im open for suggestions to make it "better"
The problem is you're comparing a character i to a string "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z". The two will never be equal.
What you want to do instead is use the in operator.
if i in 'bcdfghjklmnpqrstvwxz':
Also, strings don't have an .append() method, only lists do.
You can create a string from a list of strings by doing ''.join(my_list)
If and in statements don't work like that. This is actually a very common mistake, so no worries. When you get to the if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z": python reads that as "if i is all of this string (the string that contains all the consonants). Now unless you enter that string exactly somewhere in your sentence, python is going to think "nope no string like that" and skip it. You have the same problem with your vowel statements.
For the fastest fix:
if i in "bcdfghjklmnpqrstvwxz": #note the removal of commas, don't want them getting "o'd"
#rest of your code for consonants
else: #having an else is often very good practice, or else you may not get a result.
#what to do if its not a consonant
The function checks if it is a lower case vowel (might want to add stuff for upper case letters), then if it isn't, it checks if it is a letter period. string is very useful when working with strings. You should look at the docs.
And finally, you need to change append to just use + with strings.

I can't get this right in Python?

I was studying Python on this website www.codacademy.com and I'm stuck on exercise PygLatin in part 4 of 12.
"Write an if statement that checks to see if the string is not empty.
If the string is not empty, print the user's word.
Otherwise (else), print "empty" if the string is empty.
Make sure you thoroughly test your code. You'll want to make sure you run it multiple times and test both an empty string and a string with characters. When you are confident that your code works, continue on to the next exercise."
I have to print the user's input word if he does so, if not, print "empty".
original = raw_input("Welcome to the English to Pig Latin translator! Type in the word you wish to use.")
if len(original) > 0:
return raw_input
else:
return "empty"
print original
But it's not working, I need help.
What am I doing wrong? The error claims it's on line 2 (if len(original) > 0:) but I haven't figured out what's wrong.
Wrong indentation is the main problem. Also, you have return statements but don't have a function. Plus, you can simplify the check if original is empty:
original = raw_input("Welcome to the English to Pig Latin translator! Type in the word you wish to use.")
if original:
print original
else:
print "empty"
or, in one line:
print original if original else "empty"
or:
print original or "empty"
You have two main problems: indentation and return without a function.
If you want to use a function, you could define a function that receive a string parameter, checks if it's empty, and then returns the corresponding string.
For example:
def checkstring(string):
if len(string) > 0:
return string
else:
return "empty"
original = "Welcome to the English to Pig Latin translator! Type in the word you wish to use."
print checkstring(original)
You can't indent arbitrarily in Python. The four lines beginning with the if statement are indented one level further than the first statement: that's not allowed. You can only indent after a statement that introduces a new block, as you have done after if and else. Bring those four lines back a level so that they start at the left-hand side.
I got the code from "Quine"but I edited more so you can actually put the input. Works better if you ask me for the purpose of this exercise:
print "Welcome to the English to Pig Latin translator!"
def checkstring(original):
if len(original) > 0:
return original
else:
return "empty"
original = raw_input("What is your name?")
print checkstring(original)
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
raw_input ("What is your name")
variable_name = raw_input ()
original = raw_input()
if len (original) > 0:
print "the user's word"
else:
print "empty"

Categories

Resources