Write a program that requires users to enter integers, each in a separate line. The user indicates the end of the entry in a blank line. The program prints negated values. The program prints values in the same line separated by a space.
n = input()
while n != "":
n = int(n)
print(-n, end=" ")
n = input()
print(-n, end=" ")
This code works, but it needs help with the formatting.
The input should look like this:
5
0
-11
The output should look like this:
-5 0 11 -2
Since you want to input all values first and then print you need save them all to a list. Then, print them out after you're doing inputting. You can do this by using join(), but note that you must convert from str to int and back to str with this.
all_nums = []
n = input()
while n != "":
all_nums.append(str(-int(i)))
n = input()
print(" ".join(all_nums))
Instead, if you would like to print the numbers out with a normal loop you can do this
all_nums = []
n = input()
while n != "":
all_nums.append(-int(i))
n = input()
for i in all_nums:
print(i, end=" ")
Related
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.
This is the code.
n = int(input("Enter number of strings: "))
for i in range(n):
ai= input("Enter string ")
i=0
print(ai)
Why does it give last string and not the first string?
If I try to print a0 ,it gives error.
I know that I can use lists , but I didn't know about list when I wrote the program and now I have to change everything to use list.
Because you are overwriting the variable in each iteration of the loop, if you want to print all the strings added in the format you can use something like this
n = int(input('enter number of strings'));
ai = ''
for i in range(n):
ai += input('enter a string: ')+'\n'
i = 0
print(ai)
This will print your string.
You should use a list and append every input to the list instead:
n = int(input("Enter number of strings: "))
a = []
for _ in range(n):
a.append(input("Enter string: "))
print(a[0])
I'm trying to create a program that gets each digit of an inputted number into a list using a while loop. However, it only appends the last digit of the number to the list.
Code -
num = int(input("Enter a number: "))
numstr = str(num)
numlen = len(numstr)
x = 0
while x < numlen:
digits = []
a = numstr[x]
digits.append(a)
x = x + 1
print(digits)
So if I were to put in 372 as the number, the list would just simply be ['2'] with a length of 1.
Try this code:
digits = [i for i in str(num)]
You cannot do better than digits = list(str(num)). In fact, since input returns a string, even the conversion to a number is not necessary:
num = input("Enter a number: ")
digits = list(num)
(You still may want to ensure that what's typed is indeed a number, not a random string.)
Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list
this is my code on python 3.2.3 IDLE:
numbers = []
numbers = input("(Enter a empty string to quit) Enter a number: ")
while numbers != "":
numbers = input("(Enter a empty string to quit) Enter a number; ")
numbers.append(n)
print ("The list is", numbers)
problem now is, i can't append the list.
if i make numbers = int(input( then it works for appending the list but won't let me quit out of entering the numbers.
if i make numbers = input
like i have right now, it won't let me append the list
how can i get these numbers to append to a list?
There are two problems:
you're assigning the input to numbers instead of n;
the append() is in the wrong place.
Try the following:
numbers = []
n = input("(Enter a empty string to quit) Enter a number: ")
while n != "":
numbers.append(n)
n = input("(Enter a empty string to quit) Enter a number; ")
print ("The list is", numbers)
If you want to store integers instead of string, change the append() line to:
numbers.append(int(n))
Stylistically, if the first prompt is the same as the prompt for all subsequent inputs, I'd restructure the code as follows:
numbers = []
while True:
n = input("(Enter a empty string to quit) Enter a number: ")
if n == "": break
numbers.append(n) # or int(n)
print ("The list is", numbers)
Despite the problems you've got an answer to, this can be heavily simplified for simple data input:
numbers = list(map(int, iter(input, '')))
Working inside-out (a bit of explanation):
iter(input, '') repeatedly calls until '' (an empty input) is met and yields that value
the map(int,...) takes those values and tries to convert to an integer - an exception will be thrown if it can't
the list(...) then takes that and creates an actual list object
numbers = ... is err, as it says :)
Then, possibly wrap in a function (using functools.partial here, but lambda is fine):
def ask(prompt):
from functools import partial
prompt_func = partial(input, prompt)
return list(map(int, iter(prompt_func, '')))
numbers = ask('Keep entering valid numbers (or a blank line to quit)')