This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I am pretty new to Python and I am having trouble with this 'quiz' I am creating.
answer_1_choices = {
'A' : 'A: A list is a datatype that stores a sequence of items with individual indexes that are mutable.',
'B' : 'B: A list is a datatype that stores a sequence of items with individual indexes that are immutable.',
'C' : 'C: A list is a datatype that stores a sequence of items assigned to individual keys that are immutable.'
}
Number_One = '1. What is a list?'
def answer():
x = input()
if x == 'A' or x == 'a':
print('Correct!')
else:
print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
print('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
def question_one():
print(Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
print('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
question_one()
answer()
I want the else statement to run infinitely every time that the input is something other than 'A' or 'a'. I know I have to use some kind of loop or something, but I just can't seem to figure it out. Can someone help me?
What you're thinking of there is a while loop. Instead of checking for x = 'A' or x = 'a', you might try testing for whether x isn't 'A' or 'a'.
Try this:
while (x != 'A' and x != 'a'):
print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
x = input('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
print('Correct!')
This way, it will only print "Correct!" once the breaking condition has been satisfied.
Add as the last line of the else case a recursive call:
answer()
Full code:
def answer():
x = input()
if x == 'A' or x == 'a':
print('Correct!')
else:
print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n')
print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C'])
print('\n' + 'Is the answer A, B, or C? Type the letter of your choice.')
answer()
Related
Suppose I have a string : ' Swarnendu Pal is a good boy '
Here I want to remove all the spaces in between the strings, that means the leading and the last spaces should be remain same but all other spaces should be removed. My final expected output will be : ' SwarnenduPalisagoodboy '
Try this... doesn't matter #spaces you have in the start/end... the code will retain them... & remove in between strings...
s = " Swarnendu Pal is a good boy "
start_space, end_space = 0,0
for i in s:
if i == " ":
start_space += 1
else:
break
for i in s[::-1]:
if i == " ":
end_space += 1
else:
break
result = " " * start_space + s.replace(" ","") + " " * end_space
print(result)
# " SwarnenduPalisagoodboy " #### output
Hope this helps...
An attempt at regular expression, which will remove consecutive white space characters with non white space characters outside both ends (I'm not very good at using it yet, and there may be a better solution):
>>> import re
>>> re.sub(r'(?<=[^ ]) +(?=[^ ])', '', ' Swarnendu Pal is a good boy ')
' SwarnenduPalisagoodboy '
I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.
I'm having trouble in the 3rd part of my Scripting homework.
1.23 LAB: Warm up: Variables, input, and type conversion
(1) Prompt the user to input an integer between 32 and 126, a float, a character, and a string, storing each into separate variables. Then, output those four values on a single line separated by a space.(2) Extend to also output in reverse. (3) Extend to convert the integer to a character by using the 'chr()' function, and output that character.
It seems to come up fine when I run the program but when I submit for grading I get 0 points. Here's my code:
user_int = int(input('Enter integer (32 - 126):\n'))
user_float = float(input('Enter float:\n'))
user_char = input('Enter character:\n')
user_str = input('Enter string:\n')
print(str(user_int) + " " + str(user_float) + " " + str(user_char) + " " + user_str)
print(str(user_str) + " " + str(user_char) + " " + str(user_float) + " " + str(user_int))
print(str(chr(user_int)) + " " + str(user_float) + " " + str(user_char) + " " + user_str)
A few remarks on your code.
one:
print(str(user_int) + " " + str(user_float) + " " + str(user_char) + " " + user_str)
It is not necessary to cast user_char to str. It is already a string.
print(str(user_int) + " " + str(user_float) + " " + user_char + " " + user_str)
two:
print(str(user_str) + " " + str(user_char) + " " + str(user_float) + " " + str(user_int))
Again you have cast usr_char (and user_str), to str and it isn't necessary as they are already strings and don't require casting to str.
print(user_str + " " + user_char + " " + str(user_float) + " " + str(user_int))
three:
And as I remarked in my comment above, (and I may be wrong), I think the specification only requires you to print out the character decoded from the user_int.
print(chr(user_int))
The changes I suggested could be rendered like the following.
user_int = int(input('Enter integer (32 - 126):\n'))
user_float = float(input('Enter float:\n'))
user_char = input('Enter character:\n')
user_str = input('Enter string:\n')
print(user_int, user_float, user_char, user_str)
print(user_str, user_char, user_float, user_int)
print(chr(user_int))
(Note that I didn't add spaces between the items as printing a comma separated list of items adds a space between each item. Also, you can print the user_int and user_float without casting them to str and python will accept them. It is necessary to cast them to str if you are concatenating them to (spaces in your approach). (However, it seems your instructor wants you to cast them, so you should probably use your approach adding spaces between each item in your print statements and don't use my approach that uses a comma separated list).
Running this program, I got this sample result below.
Enter integer (32 - 126):
122
Enter float:
3.1415
Enter character:
B
Enter string:
Tom likes watermelon
122 3.1415 B Tom likes watermelon
Tom likes watermelon B 3.1415 122
z
This worked and satisfied all 3 portions of the question.
user_int = int(input('Enter integer (32 - 126):\n'))
user_float = float(input('Enter float:\n'))
user_char = input('Enter character:\n')
user_string = input('Enter string:\n')
print(user_int, user_float, user_char, user_string)
print(user_string, user_char, user_float, user_int)
print(user_int, 'converted to a character is', chr(user_int))
Hopefully this helps!
I'm a student and have a question. I'm not getting the correct output in our textbook.
first = 'I'
second = 'love'
third = 'Python'
sentence = first + '' + second + '' + third + '.'
Output:
I love Python.
When I run it, nothing happens. Can someone explain why? Thanks in advance!
print sentence. Will print the outut
But from what you have this will output "IlovePython." not I love Python.
This is because ther is no space between your '' tags. To fix this convert all those '' to ' '. Save the last one, which is . as it should be.
Your sentence variable should be:
sentence = first + ' ' + second + ' ' + third + '.'
and after assigning the value to sentence you have to print it:
print (sentence)
Also you can print directly the concatenation without saving it into a variable:
print (first + ' ' + second + ' ' + third + '.')
I know that it is very weird code, but try not to pay attention. I just want to solve this task with such a strange method. But in the process, I am faced with this problem. Can you help me to fix it?
in <module>
in reverse_alternate
IndexError: string index out of range
I suppose that it's associated with modulo. Right?
def reverse_alternate(string):
a = string.split(' ')
new = ''
for i, c in enumerate(a):
if i % 2 != 0:
new += ' ' + c[::-1] + ' '
else:
new += c
if new[-1] == ' ':
a = new[:-1]
return a
else:
return new
Replace
if new[-1] == ' ':
with
if len(new) and new[-1] == ' ':
If you have no tokens, new will end up being empty, and as such, it won't have the -1'st element. Thus, referencing it would result in "index out of range" error.