Hi this is my first post. I am working on homework for my Python course. I have my code nearly complete, however I am having an issue with a line break. I have three pictures showing my results when I submit for the grade. My theory is this is an issue with my loop and that I will need to add a break or change the structure somehow. If you could please also point me in the right direction and not give me the answer for free it would be appreciated. Thank you very much.
https://imgur.com/D34gqwD https://imgur.com/1tYuoPO https://imgur.com/Xw5NjOH
I also have my code below:
string = input('Enter input string: ')
while string != 'q':
if ',' not in string:
print('\nError: No comma in string.')
else:
string = string.replace(' ','')
string_parts = string.split(',')
print('\nFirst word: %s' % string_parts[0])
print('Second word: %s' % string_parts[1])
user_input= input('Enter input string: ')
string = user_input
Comparing, your output and the expected one, I find the only difference to be the absence of the newline (\n) in yours. I don't think there is any problem with the structure of the loop.
Observe where the instructor requires you to put the newlines and just add them in the relevant parts of your loop.
Related
I'm very new to python and Stack overflow so sorry if my question is lacking information, but I hope you can solve it.
To give some background, I am making a game that generates a random alphabet with some words in there (kind of like a word search) and I am unable to remove a specific letter (to make it easier for the user to guess) until after the response has been given. Valid words are the words that are in the alphabet, and random_az_word is a string of a random alphabet.
Here is the code:
while not user_win:
user_input = input(input_question)
if user_input in valid_words:
user_win = True
while not user_input.isalpha():
user_valid = False
input_question = 'Please put in a valid word '
user_input = input(input_question)
if user_input not in valid_words:
while not remove:
remove_num = random.randint(1,int(len(random_az_word)-1))
if random_az_word[remove_num] not in ''.join(valid_words):
remove = True
random_az_word = random_az_word.replace(random_az_word[remove_num],'')
input_question = f'Incorrect, please try again, after removing the letter {random_az_word[remove_num]} alphabet is {random_az_word} '
After wards, the input question ends up with the old alphabet (without the removed letter), until after you put in a response.
PS. I'm very tired right now so I could just be missing a very noticeable mistake, I apologize if that's the case.
Please write a program which asks the user to type in a string. The program then prints out all the substrings which begin with the first character, from the shortest to the longest. Have a look at the example below.
Please type in a string: test
t
te
tes
test
Obviously my code is not the way it supposed to be:
stg = input("Please type in a string: ")
print(stg[0])
print(stg[0:5])
print(stg[0:10])
print(stg[10:50])
print(stg[:])
ok, this is a homework and I don't give you the exact solution... but as some points:
you have a string and want to print first 1 letter, first 2 letters and so on... so your range end must increase one by one...
you don't know about input length so you can't use hard code and use a loop
for loop you need to know about string length and use a builtin method for getting the length...
any question? ask it...
userString = input("Gimme String: ")
# Looping based on the given String
# Last Value is not included so you need to increment the value by one
for i in range(len(userString)):
# Last Value is not included so you need to increment the value by one
print(userString[:i+1])
#Alternative
for i in range(1,len(userString)+1):
print(userString[:i])
stg = input("Please type in a string: ")
print("\n".join([stg[0:i+1] for i in range (len(stg))]))
Output:
t
te
tes
test
Just use simple for loop
stg = 'test'
temp_str = ''
for i in range(len(stg)):
temp_str = temp_str + stg[i]
print(temp_str)
My friend and I recently started learning python and we have a task that the both of us are struggling with. The task involves getting a number from the user and printing that many underscores. Example: user entered 8, the the code will print 8 underscores in one line. My code is
num = input('Enter a number: ')
after that, to make it print the underscores I thought it would be something like
print('_'*num)
I tried many variations of that and suggestions from the internet but I still can't get it to work without a syntax error. My friend and I are both very stuck on this, any help appreciated. Feel free to ask questions, I found this hard to explain since I'm new to this.
Most likely the issue is you need to use int(input("Enter a number: ")) instead of just input, to convert the input from a string to an integer.
Many of the responses here are way too complex for a very simple problem. The only issue with your code is that num is a string, not an integer. You cannot multiply two strings, thus this will throw TypeError: can't multiple sequence by non-int of type 'str'. The fix is simple, change the type:
num = input('Enter a number: ')
print("_" * int(num))
You need to cast the input to an integer
num = int(input("Number"))
"_______________________________"[:num] # substring
"".join(["_" for i in range(num)]) # build array then construct string
"_"*num # string repetition
num = int(input("enter: "))
this is inputting the number of times you want the unerscore to be printed.
for i in range(num):
this for loop repeats the code inside n times
print("_", end =" ")
The end =" " makes sure that the next print statement happens on the same line, so the final code would be:
num = int(input("enter: "))
for i in range(num):
print("_", end =" ")
Hope this helps! (It's my first time answering lol)
This is what you are looking for:
i = input("Enter the number: ") # get input from user
character = "_"
for x in range(int(i)):
print(character, end="") # repeat print the specified character. end="" ensurer that all is in one line
for i in (0, userinput): print('hello world', end = ')
end = is for no newline
I'm having trouble trying to execute this code, I want the user to input a value, the program checks if that value is a string then it returns the length.
If the value contains whitespaces the programs remove the whitespace and print the length.
But if it contains any integer values the program returns "No Integers is Allowed"
This is the code:
def length(Name):
long = len(Name)
return long
new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if value1.isspace() == True:
print("This is Before Removing Spaces: " + value1)
value2 = value1.replace(" ", "")
print("This is After Removing Spaces: " + value2)
elif value1.isalpha() == True:
print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
print("Integers are not allowed! ")
else:
print("There's someting wrong with "+ value1)
So if you can help me with that I appreciate it.
Thanks
I don't think the str.isspace, str.isalpha and str.isdigit methods do what you expect them to do. To start with, they all test if all the characters in the string you enter are of the type that is described in their name. Your code seems to be expecting them to be return True if any of the characters match. That is, if there are any spaces, you want to remove them and show the two lengths, before and after.
There's no single string method that will do that test for you in Python. You could use regular expressions (which are more powerful, but much more complicated), or you could write some slightly more elaborate code to do the test. I'd suggest using the any function, and passing it a generator expression that calls the method you want on each character in the string.
if any(c.isspace() for c in user_str):
...
This may not be exactly what you want for all of your tests. The desired logic of your code is not entirely obvious, as there are a number of corner cases that your output doesn't specifically address. Is a string that contains both letters and numbers valid? How about one that has spaces in between numbers, but no letters at all? You may need to reorder the conditions of your if/elif/else statements so that they match what you intend.
I'd also note that the variable name you used for user input, new_length, is very misleading. It's not a length, its the string you want to measure the length of! It's a lot easier to make logic errors about variables that have misleading or unclear variable names, so taking time to go back and reconsider names you chose earlier is sometimes a good idea, as it can improve the clarity of your code a lot! Descriptive variable names are good, but it's a tradeoff between clarity and brevity, as long names are tedious to type (and prone to typos). They also can lead to line length issues, which can make it less convenient to see all your code on your editor screen at once.
You can use this function to check if the input string contains a number:
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
It returns true if there is a number and false if there is not.
As for the whitespaces you can ommit isspace(). Using replace() alone will do the job, even if there are no whitespaces.
stri='jshsb sjhsvs jwjjs'
stri=stri.replace(' ','')
I suggest reading the documentation in these cases. For isspace, note here that
Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.
That is, if there's anything that's not a space there, it will be False. Which is annoying, but why check in the first place? Just do the replacement! If there's no whitespace, it won't do nothing. If you need to print those statements, you can do
if ' ' in value1:
...
(of course, this doesn't consider all the possible kinds of whitespaces, check the other answers for doing the for loop if you need that)
Next, I believe you need to remove the elifs and just use if statements, since note that if you input a name with a space, it will print the name with the spaces removed... and nothing after that. Not even if it has integers in it. This is because elif statements don't execute once another above them did.
There are many other things you need to consider, but these two I think you should consider first. Hope it's useful!
You can use the re module in Python to check for white spaces in your string. It returns True if there are white spaces and False otherwise.
import re
def length(Name):
long = len(Name)
return long
new_length = input("Please Enter Your name You can use Spaces: ")
value1 = new_length
if re.search('\s', value1):
print("This is Before Removing Spaces: " + value1)
value2 = value1.replace(" ", "")
print("This is After Removing Spaces: " + value2)
print("Here is The Length: ", length(value2))
elif value1.isalpha() == True:
print("Here is The Length: ", length(value1))
elif value1.isdigit() == True:
print("Integers are not allowed! ")
else:
print("There's someting wrong with "+ value1)
I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.