def headName():
print (Name[0].upper())
def tailName():
print (Name[1:].lower())
Name = input("Please enter a name ")
headName()
tailName()
That's my code; I want to know how to concatinate headName() and tailName(), so that they're on the same line. Thanks
You can't do that without rewriting the functions. The newline is added by print. Since you call print inside the functions, nothing you do outside the function can undo the newline that was already added inside.
A better idea is to have your functions return the values, and then do the printing outside:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print(headName(), tailName(), sep="")
Incidentally, what you are doing can also be accomplished directly with Name.title().
To print on the same line call them in one print statement, something like:
print(headName(), ' ', tailName())
You can also use string formatting, which in case that you wanted to customize further the output would give you more control over the outcome:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print('{}{}'.format(headName(), tailName()))
You can also try:
def headName():
print ((Name[0].upper()), end="")
This will cause your print function to end with nothing, instead of ending with a newline (default).
For more information: https://docs.python.org/3/whatsnew/3.0.html
Related
I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to figure it out lol.
what I'm trying to do is:
Wow (PlayerName) that's cool
so far what I have is:
name = input("Name? ")
print("Wow") (print(name)) (print("that's cool"))
python came back with an error saying object 'NoneType' is not callable, so instead i tried to write it as a function and call that instead:
name = input("Name? ")
def name_call():
print(name)
print("Wow") (name_call()) (print("that's cool"))
same issue, I tried various similar things, but at this point I'm just throwing darts
I'm not 100% sure why neither of these worked, but I do know that it probably has something to do with me writing it incorrectly. I could just print the name on a new line, but I want to try and put them all on the same line if possible.
you can try this code:
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'Wow that\'s cool!'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = (input('Please input name = '))
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 3
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
The result will be like this:
The original string is : Wow that's cool!
Please input name = Alice
Formulated String : Wow Alice that's cool!
you can input any name to the program.
As others have said, I think you're looking for string interpolation. As of Python 3.6 we have f-strings.
name = input("Name? ")
print(f"Wow {name} that's cool")
https://www.programiz.com/python-programming/string-interpolation
Your print's need to be on new lines.
name = input("Name? ")
print("Wow")
print(name)
print("that's cool")
Python thinks you are trying to call the result of the print function (which returns None) as a function of its own.
|
V you are accidentally calling the return value here
print("Wow")(print(name))
val = 'name'
print(f"Wow {val} that's cool.")
Btw, if you want name_call() to play a role, the following code also works
def name_call():
return ('name')
print(f"Wow {name_call()} that's cool.")
You may use the format method to insert name into the string's placeholder {}:
print("Wow {} that's cool".format(str(name)))
x = str(input('Name: '))
print('user entered {} as their name'.format(x))
def name(reading):
return reading
print(name([[10,9,9,10],2]))
When I get the program it prints [[10,9,9,10],2] but I need it to print without the extra brackets ending up with [10,9,9,10],2. I tried using things like (*reading, sep = ", ") but that only works when I use print directly. I ultimately want to know how to make reading = [10,9,9,10],2 and not [[10,9,9,10],2]. Thank you.
You can return it as a string using join()
def name(reading):
return ",".join(str(x) for x in reading)
reading=[[10,9,9,10],2]
def name(reading):
solution=""
reading = [[10,9,9,10],2]
for i in range(len(reading)):
solution+=str(reading[i])
if i<len(reading)-1:
solution+=","
return solution
print(name(reading))
How About this?
+and you should define reading in global scope.
You can use this:
def name(reading03=[[10,9,9,10],2]):
reading02 = str(reading03)
reading01 = reading02.replace("[", "")
reading = reading01.replace("]", "")
return reading
print(name)
I am using python 3.6.5
I want to input a variable which can take in name of the person with space. This is my code for it right now:
def addition():
with open('Directory.csv','a',newline='') as file:
w=csv.writer(file,delimiter=',')
def names():
name=input('Enter Name :')
n=0
for i in name:
if i.isalpha() or i.isspace():
n+=0
else:
n+=1
if n==0:
return name
else:
print('Error')
return names()
name=names()
But when I press enter without any value inputted, it still accepts it:
Enter Value of k : 2
Enter Name :
Enter Year of Birth :
What should be my code to correct this?
The basic problem here is that the loop for i in name: won't run if name is empty, leaving n at zero. The least invasive way to fix this is to check in the subsequent if:
if name and n == 0:
There are other improvements I'd recommend, starting with removing the recursive call in favor of a loop. A user could trigger a stack overflow by typing in bad characters enough times.
Rather than counting bad characters, you can break out of the loop early. This removes your dependence on n entirely:
def names():
while True:
name = input('Enter Name: ')
if name:
for i in name:
if not i.isalpha() or not i.isspace():
break
else:
return name
print('Error')
The else clause here is correctly matched to the for loop. It's a neat python trick for running code only if the loop didn't break.
There are less manual ways to check that a string contains only letters and spaces. The most popular likely being regular expressions, which are supported by the standard library. This would be a simple regex:
import re
...
name_pattern = re.compile('[a-zA-Z ]+')
...
def names():
while True:
name = input('Enter Name: ').strip()
if name_pattern.fullmatch(name):
return name
print('Error')
I am trying to write a function that will allow the user to enter a name or phone number, check if it is present in a file, and if it is prints out the entire line in which that element has been found. I have so far:
def searchPlayer():
with open("players.txt") as f:
data = f.readlines()
print "Enter 0 to go back"
nameSearch = str(raw_input("Enter player surname, forname, email, or phone number: "))
if any(nameSearch in s for s in data):
#Finding the element in the list works
#Can't think of a way to print the entire line with the player's information
else:
print nameSearch + " was not found in the database"
The file is formatted like so:
Joe;Bloggs;j.bloggs#anemailaddress.com;0719451625
Sarah;Brown;s.brown#anemailaddress.com;0749154184
So if nameSearch == Joe, the output should be Joe;Bloggs;j.bloggs#anemailaddress.com;0719451625
Any help would be appreciated, thank you
Why not use a loop?
for s in data:
if nameSearch in s:
print s
break
any is looping anyway, from the docs:
def any(iterable):
for element in iterable:
if element:
return True
return False
Seems too complicated, just do
with open("players.txt") as f:
for line in f:
if nameSearch in line:
print line
You can't use any as others have mentioned, but you can use next if you want to keep the more compact code. Instead of:
if any(nameSearch in s for s in data):
you'd use next with a default value:
entry = next((s for s in data if nameSearch in s), None)
if entry is not None:
print entry,
else:
print nameSearch, "was not found in the database"
Note: You might want to use csv.reader or the like to parse here, as otherwise you end up mistaking formatting for data; if a user enters ; you'll blindly return the first record, even though the ; was formatting, not field data. Similarly, a search for Jon would find the first person named Jon or Jonathan or any other name that might exist that begins with Jon.
As #alexis mentioned in a comment, you shouldn't use any() if you want to know which line matched. In this case, you should use a loop instead:
found = False
for s in data:
if nameSearch in s:
print s
found = True
#break # Optional. Put this in if you want to print only the first match.
if not found:
print "{} was not found in the database".format(nameSearch)
If you want to print only the first match, take out the hash sign before break and change if not found: to else:.
I fixed the issue with the spacing and have corrected other errors a long the way. Now it is doing what i want but what i select choice 2 it will print out the record of the employee 4 times. And if i enter another employee it will just print the second one and not the 1rst one as well.
class EmployeeClass:
def Employee(name, lastName, age, salary):
name = name
lastName = lastName
age = age
salary = salary
def displayEmployee(x):
print("Name: " + name + ", " + lastName)
print("Age: " + age)
print("Salary: " + salary)
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input()
if choice == "1":
name = input ("Enter First Name: ")
EmployeeArray.append(name)
if name == "":
Continue = False
print ("Goodbye!")
break
lastName = input ("Enter Last Name: ")
EmployeeArray.append(lastName)
age = input ("Enter Age: ")
EmployeeArray.append(age)
salary = input ("Enter Salary: ")
EmployeeArray.append(salary)
elif choice == "2":
for Employee in EmployeeArray:
EmployeeClass.displayEmployee(Employee)
Continue = False
elif choice == "3":
print ("Bye!")
break
else:
print ("Please choose a valid option")
print ("\n")
Your error message will give you an indication about the line number where this problem is happening. Basically, you are mixing tabs and blank spaces, so you need to use only one of them consistently for indentation.
PEP8 - The Style Guide for Python recommends the use of spaces and also notes:
When invoking the Python command line interpreter with the -t option,
it issues warnings about code that illegally mixes tabs and spaces.
When using -tt these warnings become errors. These options are highly
recommended!
From briefly examining your source it seems that there are tabs in front of the print statements - replace those with blanks (that is also the reason they are not rendered correctly in the post above)
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
There might be other spots, you'll have to check carefully. In fact I suspect where your code doesn't show as correctly indented in your post might be worth a look.
In the order to avoid problems like this it's best to use an editor or IDE that will consistently indent for you with the same characters.
It looks like you need to indent everything after the first line.
I.E.
class Employee:
empCount = 0
def _init_(self, name, lastName, age, salary):
...
The problem is that you are using a tab character ('\t') to indent some lines, and four spaces (' ') to indent others.
This can be a problem, because a tab doesn't necessarily mean a given number of spaces - different editors may interpret it as the equivalent of 2 or 4 or 8 spaces (or really, any number of spaces it likes, but those are the most common choices). If you indent using only spaces, or only tabs, that is unambiguous and Python is happy. If you use a mixture, the meaning of your code will be different depending on how many spaces a tab character is equal to - so instead of guessing, possibly leading to strange errors, Python stops with the warning message you see.
The immediate solution is to use search-and-replace to replace every tab character with 4 spaces. The longer-term solution is to use a text editor which will automatically insert 4 spaces whenever you hit the tab key. (On Windows, I like Notepad++, but there are lots of other good ones too).
Never use tabs in Python, you can but it's not conventional. The PEP8 convention is to use four spaces.