I'm working on an assignment:
My input is supposed to be a name, it could be anything.
The output is supposed to be the length of the name.
e.g.
Currently, I have:
print(input("What is your name? ")
print(len(input)
But the second half isn't correct.
If you need to DO something with the value, then you have to store it in a variable:
name = input("What is your name? ")
print(name)
print(len(name))
I think I located the problems in your code. This is what it should look like:
n = input("What is your name? ")
print((len(n))
I tested and switched things up a bit by adding a variable called "n" and giving it the input value. Then I wrote a changed into string version of the len of n... If that makes sense.
I put three brackets in the second line because the first one is for the print statement, the second one len, and the last one for the int.
Don't worry too much as it was an honest mistake! :)
PS. This is the better version of the code:
n = input("What is your name? ")
print("Your name has "+len(n)+" letters")
According to your question, your one line code can done in this way:
print(len(input("what is your name ?")))
Related
I am trying to create an empty list and for some reason it is telling me it's invalid syntax? it also flags the next line with the same error, saying that while count<amount: is invalid. am i wrong for thinking this doesnt make sense? using vsc. thanks in advance.
my code looks like this.
list=[]
count=0
while count < amount :
s=int(input"enter a number:")
list.append(s)
count= count+1
i tried to use list={}, list=() even though i know those are wrong. it also flags lines like list4=[1,3] ??
amount is not defined. Define it with a number like 5 and try then.
You also need to make sure the variable list is called something else, it is a python-reserved word.
Lastly, make sure the input function has parenthesis () around it. e.x. input("enter number: ")
In python the indent is 4 spaces.
You need to change the variable name "list" because it is a built in name in python.
You need to put brackets after input.
amount = 5
numberList = []
count = 0
while count < amount:
s = int(input("enter a number:"))
numberList.append(s)
count += 1
I think the problem there is that you're using input() wrong, it should be:
int(input("Enter a number: "))
Also, I am assuming that you defined amount earlier in your code, otherwise you will need to in order for your code to work :D
I also saw a comment saying that list is a python reserved function: It is, however you can use it as a variable name and it will not return an error :)
Have a good day :D
I just started with python. My teacher gave me an assignment and I'm stuck on a project where I have to make the numbers of characters appear when someone enters their name for input command input("what is your name") I don't think I have been taught this and google is giving me a hard time when trying to look for the command. This might be Childs play to most but can anyone throw me a tip/hint?
using print(len(myVariable)) should output the number of characteres that the string has. You should familiarize yourself with python methods.
Here are some resources:
https://docs.python.org/3/library/functions.html
https://www.w3schools.com/python/ref_func_len.asp
Printing the length of a variable is very easy with Python due to the many built-in functions you can perform on strings! In this case, you would use use len(). Read about other helpful string methods in python too in order to get a head start on your class!
inputtedName = input("What is your name? ")
nameLength = len(inputtedName)
print("Your name is " + str(nameLength) + " letters.")
print(f"Your name is {nameLength} letters.")
The first print statement uses something called string concatenation to create a readable sentence using variables. The second uses f strings to make using variables in your strings even easier!
I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
I have to define a function named introduce(). It asks for the name of a person twice, and then introduce each of the two people to the other. The function introduce() takes one string parameter
for instance it would say:
What is your name?
John
And What is your name? Mike
it would then return:
John meet Mike,
Mike meet John
the code I have so far is
def introduce(intro):
1st = input('What is your name?: ')
2nd = input('And what is your name? ')
print(1st(input) 'meet' 2nd(input))
I would like to know what I am doing wrong, I am new to Python so I am not too familiar with some of the elements in it
Among other things, variable names in Python (and most other languages) can't start with digits, so use first and second.
You're also doing some weird syntactical stuff in your print call, which definitely doesn't work. Once you assign the two variables, just print them out--there's no need to refer to the input function again. Just pass first, second, and anything else as comma-separated arguments to the print function:
print(first, 'meet', second)
I highly recommend you work through some of the Python tutorials. This is all really basic syntactical stuff; doing the examples there will likely help you out a lot.
First, in Python, variable names cannot start with numerals, so try naming them first and second
Second, the (input) after the variables is unnecessary (and wrong). The variable name speaks for itself.
Third, separate your variables and 'meet' with a comma, so they're printed with a space between them and automatically joined together. There are other ways, but this is the simplest
def introduce(intro):
first = input('What is your name?: ')
second = input('And what is your name? ')
print(first, 'meet', second)
print(second, 'meet', first)
first of all, you need to not start variable names with numbers.
the input is saved in the variable 1st. You don't need to use 1st(input). Instead, you just `print(first)
Also, there is a problem with the way you join the strings. It can be done in two ways:
#Method 1:
print(1st, 'meet' , '2nd')
or
#Method 2:
print(1st + ' meet ' + 2nd)
the difference is: a comma will add the space, whereas a space is required when using + (at least, they are the only differences you need to be aware of.)
Okay, below is my issue:
this program reads from a file, makes a list without using rstrip('\n'), which I did on purpose. From there, it prints the list, sorts it, prints it again, saves the new, sorted list to a text file, and allows you to search the list for a value.
The problem I am having is this:
when I search for a name, no matter how I type it in, it tells me that its not in the list.
the code worked til I changed the way I was testing for the variable. Here is the search function:
def searchNames(nameList):
another = 'y'
while another.lower() == 'y':
search = input("What name are you looking for? (Use 'Lastname, Firstname', including comma: ")
if search in nameList:
print("The name was found at index", nameList.index(search), "in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
else:
print("The name was not found in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
For the full code, http://pastebin.com/PMskBtzJ
For the content of the text file: http://pastebin.com/dAhmnXfZ
Ideas? I feel like I should note that I have tried to add ( + '\n') to the search variable
You say you explicitly did not strip off the newlines.
So, your nameList is a list of strings like ['van Rossum, Guido\n', 'Python, Monty\n'].
But your search is the string returned by input, which will not have a newline. So it can't possibly match any of the strings in the list.
There are a few ways to fix this.
First, of course, you could strip the newlines in your list.
Alternatively, you could strip them on the fly during the search:
if search in (name.rstrip() for name in nameList):
Or you could even add them onto the search string:
if search+'\n' in nameList:
If you're doing lots of searches, I would do the stripping just once and keep a list of stripped names around.
As a side note, searching the list to find out if the name is in the list, and then searching it again to find the index, is a little silly. Just search it once:
try:
i = nameList.index(search)
except ValueError:
print("The name was not found in the list.")
else:
print("The name was found at index", i, "in the list.")
another = input("Check another name? Y for yes, anything else for no: ")
Reason for this error is that any input in your list ends with a "\n". SO for example "john, smith\n". Your search function than uses the input which does NOT include "\n".
You've not given us much to go on, but maybe using sys.stdin.readline() instead of input() would help? I don't believe 2.x input() is going to leave a newline on the end of your inputs, which would make the "in" operator never find a match. sys.stdin.readline() does leave the newline at the end.
Also 'string' in list_ is slow compared to 'string' in set_ - if you don't really need indices, you might use a set instead, particularly if your collection is large.