How would I loop this on Python? - python

How would I loop this code to make it so that the user inputs the number of friends they have, their names, and in the end, the program will be able to output the information? This is what I have so far, but I believe it's incorrect.
Friends = int(input("Please enter number of friends")
for i in range(Friends):
Name = input("Please enter friend number 1:")

Append each name to a list, then print the list. And use string formatting to put an appropriate number in the prompt.
friendList = []
Friends = int(input("Please enter number of friends")
for i in range(Friends):
Name = input("Please enter friend number %d: " % (i+1))
friendList.append(Name)
print(friendList)

Loop using the number of friends, and store the name for each of them:
friend_count = int(input("Please enter number of friends: "))
friend_list = []
for friend_index in range(friend_count):
name = input("Please enter friend number {}: ".format(friend_index + 1))
friend_list.append(name)
print(friend_list)

Here a try using list comprehension:
Friends = int(input("Please enter number of friends :"))
Names = [input("Please enter friend number {}:".format(i)) for i in range(1,Friends+1)]
print(Names)

You can use raw_input, from the documentation
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
Code
name_array = list()
num_friends = raw_input("Please enter number of friends:")
print 'Enter Name(s): '
for i in range(int(num_friends)):
n = raw_input("Name :")
name_array.append((n))
print 'Names: ',name_array

Related

How do I stop my python code from printing none after it prints the string? [duplicate]

This question already has answers here:
Why is this printing 'None' in the output? [duplicate]
(2 answers)
Closed 1 year ago.
str = input("Please enter y to start the program: ")
while str == 'y':
def printNTimes(s, n):
for i in range(n):
print(s)
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Output:
Please enter y to start the program: y
Enter a string: Hi
Enter a positive number: 3
Hi
Hi
Hi
None
Please enter y if you want to continue:
You don't need print(allTogether), or the variable itself, because when you print it, you get an extra None (because the function returns None i.e, it does not return anything).
Also, put the function outside the while loop so that it is easier to read.
def printNTimes(s, n):
for i in range(n):
print(s)
str = input("Please enter y to start the program: ")
while str == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
printNTimes(phrase, number)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Just call the function. You could use return and then print the function, but this might be easier.
The problem is the function printNtime is actually being used as a subroutine, meaning it doesn't RETURN any values.
I am not sure what you want as a final output so here's two solution.
IF USED AS SUBROUTINE: just remove the print(allTogether)
IF USED AS A FUNCTION: you need to create a string variable in the function and return it.
def printNTimes(s, n):
mystring = ""
for i in range(n):
mystring = mystring + s + "\n"
return mystring
The issue you're seeing is because your routine, printNTimes(), returns a None value. You say:
allTogether = printNTimes(phrase, number)
print(allTogether)
allTogether is set to None because printNTimes does not return a value. When you call print(allTogether), that's what is printing the None.
It sounds like you intended your printNTimes() routine to assemble one big string of all the output and return it, which you would then print out via the print(allTogether) call. But your printNTimes() routine is calling the print() method and outputing the text then. So, you need to rewrite your printNTimes() method. Also, note that defining that function inside the loop is not necessary. Once is sufficient. So something like this should suffice:
def printNTimes(s, n):
s_out = ""
for i in range(n):
s_out += s + '\n'
return s_out
str_ = input("Please enter y to start the program: ")
while str_ == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str_ = input("Please enter y if you want to continue: ")
print("DONE")
Also note that I renamed your str variable to str_. str is a Python type, a reserved word that should not be reused.

How do I check the user has entered two or more words in a single string?

My function takes a string, and as long as the string has two names in it, such as "John Smith", the program runs OK.
My issue occurs when the user enters 1 or less names in their input.
user_input = input("Enter your name: ")
name = user_input.split()
print(name[0])
print(name[1])
Ideally, it would check that the user has entered a string of just two names, but it doesn't really matter.
I don't know the required checks in Python; if it was Java, it would be a different story.
You could use len() or try/except as in:
user_input = input("Enter your name: ")
if len(user_input.split()) > 1:
print("At least two words.")
else:
print("Only one word")
Or
user_input = input("Enter your name: ")
try:
user_input.split()[1]
print("At least two words.")
except IndexError:
print("Only one word")
user_input = input("Enter your name: ")
name = user_input.split()
for x in names:
print(x)

How do I eliminate spaces between variables and strings within an input in python?

int(input("Please enter number ",num,":")
I want it to output as: "Please enter number (num): " #no spaces between '(num)' and ':'
When I try to use sep='', i get an error that I can't use that within and input().
You can us old style % formatting, .format() or use f-strings (python 3.6+) to format your text:
num = 42
tmp = int(input( "Please enter number %s:" % num))
tmp = int(input( "Please enter number {}:".format(num)))
tmp = int(input( f"Please enter number {num}:"))
Output (trice):
Please enter number 42:
See
old style % vs .format()
f-strings
You should use string formatting to construct the string yourself.
Either using .format
num = 5
int(input("Please enter number {}:".format(num)))
Or using f-strings for python 3.6+
num = 5
int(input(f"Please enter number {num}:"))
#Output:
Please enter number 5:

How to insert as many numbers as were mentioned before using raw_input?

I want the user of my program to provide a number and then the user must input that number of numbers.
My input collection code
inp1 = int(raw_input("Insert number: "))
inp2 = raw_input("Insert your numbers: ")
Example:
If the user enters 3 at Insert number: then they have to input three numbers (with spaces between them) at Insert your numbers:.
How do I limit the number of values in the second response to the amount specified in the first response?
I assume, we should use a list to work with.
my_list = inp2.split()
I'm using Python 2.7
Use the len function to get the length of the list, then test if it is correct:
inp1 = int(raw_input("Insert number: "))
inp2 = raw_input("Insert your numbers: ").split()
while len(inp2) != inp1:
print "Invalid input"
inp2 = raw_input("Insert your numbers: ").split()
Another approach would be to get each input on a new line seperately, with a loop:
inp1 = int(raw_input("Insert number: "))
inp2 = []
for i in range(inp1):
inp2.append(raw_input("Enter input " + str(i) + ": "))
This way, there are no invalid inputs; the user has to enter the right amount of numbers. However, it isn't exactly what your question asked.

creating a code that use .isdigit

I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.
You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")
Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")

Categories

Resources