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!
Related
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("-+")
When I run this simple script and enter information an error appears which says: Name error: name'...' is not defined.
Name = str(input("Enter the name of your friend: "))
Age = int(input("Enter age of that friend: "))
print("The name of your friend is {} and their age is {}".format(Name, Age))
To expand on Tarun Guptas answer, the convention in python is that function names always start with lowercase letters. Uppercase first letters are reserved for classes. All the inbuilt functionality of python sticks to these conventions. The same is true for variable names, never start them with uppercase letters.
If you find yourself hunting a lot after syntax errors, get yourself an editor with a good python linter, that is, inbuilt functionality that checks the code on the fly. This will help you make quick progress in avoiding the most common mistakes.
As you advance in python, you should really check out the python style guide. Most of the conventions in python are not strictly mandated by the language, however if you ever plan to interact with other programmers, they will hate you with a passion you if you don't stick to pep8.
I have modified your code to the correct state:
name = str(input("Enter the name of your friend"))
age = int(input("Enter age of that friend"))
print("The name of your friend is {} and their age is {}".format(name, age))
There were three errors:
p of print needs to be lowercase and
a closing parenthesis was missing
f of format also needs to be in lowercase.
In Learn Python The Hard Way (Exercise 13) the 3rd Study Drill says to "Combine raw_input with argv to make a script that gets more input from a user."
I wrote this script below, intending to have the terminal prompt the user for answers to three questions, then it would print back phrases with those answers integrated into them. However, I get an error about not having enough values to unpack when I try to run it with the following command:
python ex13.py
I understand that I need more variables to unpack in order for the script to work, so when I type this then the script works but never outputs the variables "first", "second" or "third" (which I don't want it to anyway):
python ex13.py first second third
I know how to write a script without importing argument variables, but how else can I interpret the study drill? I know I am not understanding the prompt of the study drill correctly but I'm not sure how to write the script differently or even if I am going in the right direction.
Can anyone offer some tips or advice? You don't have to give me the answer outright (I like figuring things out) but I am at a loss for the moment.
MY SCRIPT:
from sys import argv
script, color, number, shape = argv
color = raw_input("What is your favorite color? ")
number = raw_input("What is your favorite number? ")
shape = raw_input("What is your favorite shape? ")
print """
This program is called %r and it will determine your
favorite color, number and shape.
""" % script
print "Based on your answers, your favorite color is:", color
print "Your favorite number is:", number
print "And your favorite shape is a:", shape
What exactly do you want your code to do? If you want to have
$ python ex13.py
$ What is your favorite color? <yourColor>
..........
$ Your favorite color is <yourColor>
Then you need to get rid of the part where you set all those values from argv. argv is a list of the arguments passed to python when you invoke it in the command line. The fix you have in your comments sets script = ['ex13.py'] instead of 'ex13.py' for precisely this reason, you're setting script to be a list as opposed to a string.
If you want your code to run so that you pass the script arguments when you run it, you could get rid of your sections calling for raw_input (or you could leave them in, but that would overwrite their values from what you passed in the command line) Try running the code you've posted with
$ python ex13.py <yourColor> <yourNumber> <yourShape>
It should work much more closely to what you want.
As you have already solved one problem by removing the variables before the =, now the only problem is you are getting square brackets around ex13.py.
You see you have to add another variable after script before = that is without input() and the problem is solved.
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.