How to gather information from user input and apply it elsewhere - python

Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.
This is my code so far
words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')
suppose I choose three letters then the output of my code then pressed enter on the fourth,
the code will be:
Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.
I want to add to this code so that when I type in a character that is not
from the alphabet the code will do something like this.
Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.
This is how I want my program to work

Use str.isalpha()
It is gives only true if all characters in the string are letters.
Example:
>>> 'test'.isalpha()
True
>>> 'test44'.isalpha()
False
>>> 'test test'.isalpha()
False
In your code:
words = []
word = input('Character: ')
while word:
if word.isalpha() and word not in words:
words.append(word)
word = input('Character: ')
print(words,'is a a valid alphabetical string.')

You can use a while loop to collect input, then break out of the loop if either the input is empty (the user hit enter without inputting a character) or if the input is not in the alphabet.
letters = []
while True:
letter = input('Character:')
if letter == '':
if letters:
print('{} is a valid alphabetical string.'.format(''.join(letters)))
else:
print('The input was blank.')
break
elif letter.isalpha():
letters.append(letter)
else:
print('{} is not in the alphabet.'.format(letter))
break

You can try this out :-
words = []
while 1:
word = input('Character: ')
if word != '':
try:
if word.isalpha():
pass
if word not in words:
words.append(word)
except Exception:
print word, " is not in the alphabet"
break
else:
res = (''.join(words) +' is a valid alphabetical string.') if (words != []) else "The input was blank."
print res
break

Related

Can I print the input of a string for len not just the number of characters?

I'm trying to find find the longest string entered then print it as the output value. The program stops running when an 'a' has been entered then returns the longest string entered not just the numbers of characters in the string. Can the length function do this?
def longest_str(words):
words = len(words)
return words
true = 1
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
if words.startswith('a'): #comparing if starts with a or A
print(f"The longest string was: {longest_str(words)}") # printing output
break #stop once reached a
else:
continue # continue to loop through, no a was found.
I understand what you are trying to do but you have several mistakes
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
This will read only one word at the time.
So, your if will be executed only if you enter a word starting with 'a'.
This will solve your problem
def longest():
maxLength = 0
longestWord = ''
while(True):
word = str(input("Enter a string: "))
word = word.lower()
if word == 'a':
print(f"The longest string was: {longestWord}")
break
if len(word) > maxLength:
maxLength = len(word)
longestWord = word
Take a look at the differences
We check if the word entered is 'a', then print the longest string and stop.
If not, we check if the new word is longer than what we previously had (initialy nothing).If the new word is longer, we retain it to be able to print it.
Just call this in the main function.
If you want the string itself you could just do it like this:
longest_string = ''
while True:
word = input("Enter a string: ").lower()
if word == 'a': break
if len(word) > len(longest_string):
longest_string = word
print("The longest string was: " + longest_string)
Keep in mind, this will make ALL words lowercase, if you dont want that you have to remove the .lower()

Python program to check if the word has an alphabet lowercase letter or not

I was trying to make a program to check if word has an alphabet letter in it or no, but when it runs it displays all the letters because of for loop so is there any other code I can use to make the program?
Here's my code:
import string
def checker(word):
lower = list(string.ascii_lowercase)
for char in lower:
if char in word:
print("Word has alphabet lowercase letter.")
else:
print("Error")
return word
wordy = input("Enter: ")
word_ = checker(wordy)
//Try the code below and let me know if it meets your needs
words= input("enter any word ?")
for word in words:
if word.isalpha():
print("True")
break
Using regex:
import re
def checker(word):
match = re.search('[a-zA-Z]', word)
if match is not None:
return True
return False
checker('10')
# False
checker('aaa')
# True

Filter words in a sentence that begin with a certain range of letters

My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.
This is my code so far, however it still prints words which begin with "g" and does not print the last word.
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.
Sample input:
Wheresoever you go, go with all your heart
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Algorithm I've come up with:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
You can define a neat little generator to split your sentence into words and compare the first letter of each.
def filter_words(sentence, lo, hi):
lo, hi = map(str.upper, (lo, hi))
words = sentence.upper().split()
for word in words:
if lo <= word[0] <= hi:
yield word
sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')
WHERESOEVER
YOU
WITH
YOUR
HEART
This is how I approached this problem. It gave me a hard time since I am a beginer. But it seems to work fine.
quote = "quote goes here"
word = ""
for letter in quote:
if letter.isalpha():
word += letter
else:
if word > "":
print(word.upper())
word = ""
else:
word = ""
print(word.upper())
I added the space to the user_input and also used the word > 'h'. Below is how it looks:
user_input = input('Enter a phrase: ').lower()
user_input += ' '
word = ''
for char in user_input:
if char.isalpha():
word += char
else:
if word > 'h':
print(word.upper())
word = ''
else:
word = ''
This code worked for me...
The task is: Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
I was making the mistake of using word > "g" before, which needs to be replaced by word > "h".
Also, you need to add the last print command in order to print the last word in case the phrase does not end with a punctuation (as in the given example)
phrase = input ("Please enter a phrase: ").lower()
word = ""
for letter in phrase:
if letter.isalpha():
word += letter
else:
if(word > "h" ):
print(word)
word = ""
else:
word = ""
if word.lower() > 'h':
print(word)
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.
The two issues you've highlighted is that you are comparing the whole word instead of just the first character.
Simply change:
if word > "g":
To:
if word and word[0] > "g":
And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:
if word:
print(word)
You may note the output is all uppercase, so .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:
famous_quote = input("Enter a one sentence quote: ")
...
if word and word[0].lower() > "g":
Note: You can simplify your else: condition:
else:
if word and word[0] > "g":
print(word)
word = ""
You stated that you are not allowed to use the split() method. I am not sure what you can use, so here's a solution (not the optimal one).
famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
if current_word is None:
current_word = c # start a new word
else:
current_word += c # append a new letter to current word
else:
if current_word is not None:
f = current_word[0] # first letter
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print(current_word)
current_word = None
Here is a sample run of the program. It preserves lowercase and uppercase. It also splits words on any non-ASCII character.
Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.
Assuming that the famous quote contains only spaces as word separator, this should do the job:
words = input("Enter a one sentence quote: ").lower().split()
for word in words:
if word[0] > 'g':
print("{w} ".format(w = word))
split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.
print() can be used in a lot of ways, due to python's history with this function.
You can .join() the list (getting a string as result) and print it:
print(" ".join(words))
you can also print with concatenations (considered ugly):
print(word+" ")
or you can use formatted printing, which I do use a lot for readibility:
print("{w} ".format(w = word))
interprets "{w}" and replaces it with word wherever "{w}" appears.
Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).
1. Split the words by building a placeholder variable: word
Loop each character in the input string
and check if character is a letter. Then add letter to the variable "word". Loop until a non-alpha char is encountered.
2. If character is alpha or (alphabet)
Add character to word.
Non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to the "else" part.
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
3. Else
Check if word is greater than "g" alphabetically. Print word and set "word = empty" string.
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
4. Or else
Set word = empty string and build the next word.
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
The last "if" is explicitly coded to print the last word if it doesn't end with a non-alpha character like a space or punctuation.
I did this exact same problem. The issue most people are having (and no one seemed to point out) is when you encounter double punctuations or a punctuation followed by a space.
This is the code I used.
phrase = input("Please enter a famous quote: ")
word = ""
for letter in phrase:
if letter.isalpha() is True:
word += letter
elif len(word) < 1: <--- [This is what accounts for double punctuations]
word = ""
elif word[0].lower() >= "g":
print(word)
word = ""
else:
word = ""
print(word) <--- [accounts for last word if not punctuated]
Variable "word" already contains your last word of the phrase but since it does not fulfil the condition to enter the loop it does not gets printed. So you can check the below solution.
phrase = input("Enter a phrase after this: ")
word = ""
for char in phrase:
if char.isalpha():
word += char
else:
if word != "":
if word[0].lower() >= "h":
print(word.upper())
word = ""
else:
word = ""
if word[0].lower() >= "h":
print(word.upper())
This code works for me:
phrase=input("Enter a one sentence quote,non-alpha separate words: ")
word=""
for character in phrase:
if character.isalpha():
word+=character
else:
if word.lower()>="h".lower():
print(word.upper())
word="" -----this code defines the end of a word
else:
word=""
print(word.upper()) ------this will print the last word
I would use regular expressions and list compreshension as shown in the function below.
def words_fromH2Z():
text = input('Enter a quote you love : ')
return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')]
When I test the function by putting in the input "I always Visit stack Overflow for Help", I get:
words_fromH2Z()
Enter a quote you love : I always Visit stack Overflow for Help
['I', 'Visit', 'stack', 'Overflow', 'Help']
This worked well for me. I had to add the last two lines of code because without them, it wasn't printing the last word, even if it began with a letter between h and z.
word = ""
quote = input("Enter your quote")
for char in quote:
if char.isalpha():
word += char
elif word[0:1].lower() > "g":
print(word.upper())
word = ""
else:
word = ""
if word[0:1].lower() > "g":
print(word.upper())
famous_quote = input("Enter a one sentence quote:")
current_word = None
for c in famous_quote:
if c.isalpha():
if (c >= 'a') or (c >= 'A'):
if current_word is None:
current_word = c
else:
current_word += c
else:
if current_word is not None:
f = current_word[0]
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print (current_word.upper())
current_word = None
if famous_quote[-1].isalpha():
print (current_word.upper())

how do i get this code to tell me what position a word in the sentence is

varSentence = ("The fat cat sat on the mat")
print (varSentence)
varWord = input("Enter word ")
varSplit = varSentence.split()
if varWord in varSplit:
print ("Found word")
else:
print ("Word not found")
for (num, x) in enumerate(sentence):
if word == x:
print ("Your word is in position",num,"!")
No need for a loop, use list.index, protected by a try/except block in case string is not found. list.index returns the first occurence of the word.
sent = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.'
words = sent.split()
word = "WHAT"
try:
print(words.index(word)+1)
except ValueError:
print("{} is not in the sentence".format(word))
returns 3 because index found the word at the 3rd position (and arrays start at 0)
Try with enumerate:
for i in enumerate(varSplit):
if i[1] == varWord:
print(i[0])
You can use the above like this:
varSentence = ("The fat cat sat on the mat")
varWord = input("Enter word ")
varSplit = varSentence.split()
if varWord in varSplit:
for i in enumerate(varSplit):
if i[1] == varWord:
print("Your word is in position", i[0], "!")
break # To stop when the first position is found!
else:
print ("Word not found")
You just need to loop over position:
def word_position(word):
for i in position:
if word == i[1]:
return i[0]
return "Your word is not in the sentence"
You can call the above function like this:
word = input('Which word would you like to search for?').upper()
pos = word_position(word)
Example of output:
>>> sent = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.'
>>> sen1 = sent.split()
>>>
>>> position = enumerate(sen1)
>>>
>>> word = input('Which word would you like to search for?').upper()
Which word would you like to search for?'what'
>>> word
'WHAT'
>>>
>>> pos = word_position(word)
>>> print(pos)
2
sent= 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.' # This defines the variable 'sent'
sen1= sent.split() # This splits the sentence into individual words
print (sen1) # This tells the program to display the sentence as the individual words
Word= str(input('Which word would you like to search for?')) # Tells the user to input one of the words from the sentence that they would like to find
Word1= Word.upper() # Changes the user's input to block capitals
print ("Searching for ", Word1) # Prints the user's input in capitals
position = list(enumerate(sen1)) # Numbers the words in the sentence starting at (ASK, 0)
if Word1 in sen1: # Asks the program to check if the user's input is within the defined sentence
for word in position:
if word[1]==Word1:
print ('Your word is in the sentence at ' , word[0]+1) # Tells the program to print a certain sentence if the users' inputted word is within the sentence
else: # Begins to tell the program what to do if the if condition is not met
print ('Your word is not in the sentence') # Tells the program what to do print if the users' inputted word is not within the sentence

Need to get it to display the position of the inputted word, not every word [duplicate]

varSentence = ("The fat cat sat on the mat")
print (varSentence)
varWord = input("Enter word ")
varSplit = varSentence.split()
if varWord in varSplit:
print ("Found word")
else:
print ("Word not found")
for (num, x) in enumerate(sentence):
if word == x:
print ("Your word is in position",num,"!")
No need for a loop, use list.index, protected by a try/except block in case string is not found. list.index returns the first occurence of the word.
sent = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.'
words = sent.split()
word = "WHAT"
try:
print(words.index(word)+1)
except ValueError:
print("{} is not in the sentence".format(word))
returns 3 because index found the word at the 3rd position (and arrays start at 0)
Try with enumerate:
for i in enumerate(varSplit):
if i[1] == varWord:
print(i[0])
You can use the above like this:
varSentence = ("The fat cat sat on the mat")
varWord = input("Enter word ")
varSplit = varSentence.split()
if varWord in varSplit:
for i in enumerate(varSplit):
if i[1] == varWord:
print("Your word is in position", i[0], "!")
break # To stop when the first position is found!
else:
print ("Word not found")
You just need to loop over position:
def word_position(word):
for i in position:
if word == i[1]:
return i[0]
return "Your word is not in the sentence"
You can call the above function like this:
word = input('Which word would you like to search for?').upper()
pos = word_position(word)
Example of output:
>>> sent = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.'
>>> sen1 = sent.split()
>>>
>>> position = enumerate(sen1)
>>>
>>> word = input('Which word would you like to search for?').upper()
Which word would you like to search for?'what'
>>> word
'WHAT'
>>>
>>> pos = word_position(word)
>>> print(pos)
2
sent= 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY.' # This defines the variable 'sent'
sen1= sent.split() # This splits the sentence into individual words
print (sen1) # This tells the program to display the sentence as the individual words
Word= str(input('Which word would you like to search for?')) # Tells the user to input one of the words from the sentence that they would like to find
Word1= Word.upper() # Changes the user's input to block capitals
print ("Searching for ", Word1) # Prints the user's input in capitals
position = list(enumerate(sen1)) # Numbers the words in the sentence starting at (ASK, 0)
if Word1 in sen1: # Asks the program to check if the user's input is within the defined sentence
for word in position:
if word[1]==Word1:
print ('Your word is in the sentence at ' , word[0]+1) # Tells the program to print a certain sentence if the users' inputted word is within the sentence
else: # Begins to tell the program what to do if the if condition is not met
print ('Your word is not in the sentence') # Tells the program what to do print if the users' inputted word is not within the sentence

Categories

Resources