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.)
Related
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'm teaching myself Python and can't see a huge difference between these two examples except the extra formatting options (eg. %r) that string formatting provides.
name = "Bob"
print "Hi, my name is %s." % name
print "Hi, my name is", name
Is there any reason in general why you'd prefer one over the other?
I realise that .format() is the preferred way to do this now, but this just for me to better understand how Python operates.
The primary difference between the two (which no one else seems to be describing) is this:
print "Hi, my name is %s." % name
Here, a new string is being constructed from the two strings (the string literal and the value of name). Interpolation (the % operator) is an operation you could use anywhere—for example, in a variable assignment or a function call—not just in a print statement. This newly-minted string is then printed (then discarded, because it is not given a name).
print "Hi, my name is", name
Here, the two strings are simply printed one after the other with a space in between. The print statement is doing all the work. No string operations are performed and no new string is created.
It is programming choice:
1) Using % clarifies the type to the reader of the code, but for each additional variable used, the programmer will need to spend time in modifying in 2 places
2) Using , implicitly does % so the reader will have to look back to know about he type. But it is quick and if code is intuitively written removes a lot of burdon of maintenance
So yes, it is choice of maintaining balance between, maintenance, readability and convenience.
The difference is that the comma is part of the print statement, not of the string. Attempting to use it elsewhere, e.g. binding a string to a name, will not do what you want.
Write a function called getUsername which takes two input parameters, firstname (string) and surname (string), and both returns and prints a username made up of the first character of the firstname and the first four characters of the surname. Assume that the given parameters always have at least four characters.
First, you will want to make a function. (Please note any syntax I use will be for V2.7)
def makeUsername(firstName,lastName):
Next, I would suggest a string to store the username that you will make. You only want the first character and then the first 4. Note the first and last names will be whatever you name the parameters.
x = firstName[0] + lastName[:4]
Finally, printing the string and returning the string.
print x
return x
Then, when you call the function it will look something like this:
makeUsername('John', 'Smith')
If you have any more questions, just ask!
This is how you build the string: firstname[0] + surname[:4]
I'm studing Python for one month and I'm trying to make a keygen application by using the dictionary. The idea was to compare each letter in name = input('Name: ') to dict.keys() and print as result dict.values() for each letter of name equal to dict.keys(). That's what I wrote:
name = input('Name: ')
kalg = dict()
kalg['a'] = '50075'
kalg['b'] = '18099'
kalg['c'] = '89885'
etc...
I tryed writing this...
for x in kalg.keys():
print(x)[/code]
...but i need to keep print(x) result but i don't know how to do it! If i do this:
for x in kalg.keys():
a = x
'a' keeps only the last key of the dictionary :(. I thought it was because print(x) prints each key of dict.keys() on a new line but i don't know how to solve it (I tryed by converting type etc... but it didn't work).
Please can you help me solve this? I also don't know how to compare each letter of a string with another string and print dict.values() as result and in the right position.
Sorry for this stupid question but i'm too excited in writing python apps :)
# Karl
I'm studing Python over two differt books: 'Learning Python' by Mark Luts which covers Python
2 and a pocket which covers Python 3. I examined the list comprehension ón the pocket one and Imanaged to write three other variants of this keygen. Now i want to ask you how can I implementthe source code of this keygen in a real application with a GUI which verify if name_textbox andkey_textbox captions match (i come from basic so that was what i used to write, just to give youan idea) as the keygen output result. I know i can try to do this by my own (I did but with nosuccess) but I would like to first complete the book (the pocket one) and understand all the mainaspects of Python. Thank you for the patience.
Calling print can't "keep" anything (since there is no variable to store it in), and repeatedly assigning to a variable replaces the previous assignments. (I don't understand your reasoning about the problem; how print(x) behaves has nothing to do with how a = x behaves, as they're completely different things to be doing.)
Your question boils down to "how do I keep a bunch of results from several similar operations?" and on a conceptual level, the answer is "put them into a container". But explicitly putting things into the container is more tedious than is really necessary. You have an English description of the data you want: "dict.values() for each letter of name equal to dict.keys()". And in fact the equivalent Python is shockingly similar.
Of course, we don't actually want a separate copy of dict.values() for each matching letter; and we don't actually want to compare the letter to the entire set of dict.keys(). As programmers, we must be more precise: we are checking whether the letter is a key of the dict, i.e. if it is in the set of dict.keys(). Fortunately, that test is trivial to write: for a given letter, we check letter in dict. When the letter is found, we want the corresponding value; we get that by looking it up normally, thus dict[letter].
Then we wrap that all up with our special syntax that gives us what we want: the list comprehension. We put the brackets for a list, and then inside we write (some expression that calculates a result from the input element) for (a variable name for the input elements, so we can use it in that first expression) in (the source of input elements); and we can additionally filter the input elements at the same time, by adding if (some condition upon the input element).
So that's simple enough: [kalg[letter] for letter in name if letter in kalg]. Notice that I have name as the "source of elements", because that's what it should be. You explained that perfectly clearly in your description of the problem - why are you iterating over dict.keys() in your existing for-loops? :)
Now, this expression will give us a list of the results, so e.g. ['foo', 'bar', 'baz']. If we want one continuous string (I assume all the values in your dict are strings), then we'll need to join them up. Fortunately, that's easy as well. In fact, since we're going to pass the results to a function taking one argument, there is a special syntax rule that will let us drop the square brackets, making things look quite a bit neater.
It's also easier than you're making it to initialize the dict in the first place; idiomatic Python code rarely actually needs the word dict.
Putting it all together:
kalg = {'a': '50075', 'b': '18099', 'c': '89885'} # etc.
name = input('Name: ')
print(''.join(kalg[letter] for letter in name if name in kalg))
I can only guess, but this could be what you want:
name = input('Name: ')
kalg = {'a':'50075', 'b': '18099', 'c': '89885'}
keylist = [kalg[letter] for letter in name]
print(" ".join(keylist))