Python 3 input loop - python

I use the for loop to input the n words
n = int(input(""))
for i in range(n):
a = input("")
print(a)
when I input:
3
1
1
1
2
It allow me to input the n+1 words
And the n+1 word can not be output
I just want to output n words then equal with the syntax in C:
int a = 0;
for(int i=0; i<n; i++)
scanf("%d",&a);
[Update]
Actually it is a problem with Pycharm. And I don't know why.
In terminal,the code can work.
So,plz not downvote....

I don't understand why this isn't working for you. Try this modified version that makes it clearer what is happening:
n = int(input("Enter number of values: "))
for i in range(n):
a = input("Enter value {} ".format(i+1))
print("Value {0} was {1}".format(i+1, a))
The ouput from this was:
Enter number of values: 3
Enter value 1 1
Value 1 was 1
Enter value 2 1
Value 2 was 1
Enter value 3 2
Value 3 was 2

It ran exactly 3 times when I tried it.
If you want to make it more explicit what you're doing you could set it to for i in range(0,n): but that won't really change anything.
The loop for i in range(n): will run from 0 to n-1.
So if you put in 3 it, it will generate 3 runs, with the values of i being 0, 1, 2.
n = int( input( "Enter the number of runs: " ) )
for item in range( 0, n ):
a = input( "\tPlease Input value for index %d: "%item )
print( a )
It generated the output:
Enter the number of runs: 3
Please Input value for index 0: 1
1
Please Input value for index 1: 1
1
Please Input value for index 2: 1
1

I think you are confusing with the output printed by the loop.
If you enter 3 in the first n = int(input(""))" the loop will go from 0 to 2 (inclusive).
In every loop you ask for a new value of a and print it. So, after the first loop, you input 1 and it outputs 1 (because it prints it). In the second loop you input another 1 and it prints it. Finally you input a 2 and it also prints it.
First loop:
input: 1
output: 1
Second loop:
input: 1
output: 1
Third loop:
input: 2
output: 2
That's why if I run the following
>>> n = int(input(""))
3
>>> for i in range(n):
... a = input("")
... print a
...
1
1
2
2
3
3
I get 6 numbers (inputs and outputs). You can see this more clearly with the following example:
>>> n = int(input("Input: "))
Input: 3
>>> for i in range(n):
... a = input("Input: ")
... print "Output: " + str(a)
...
Input: 1
Output: 1
Input: 2
Output: 2
Input: 3
Output: 3

Related

How to print output for different test cases in different lines?

t = int(input())
for _ in range(t):
a, b = 0, 1
n = int(input())
count = 0
if n == 1:
print(b)
while count < n:
print(b, end = " ")
a, b = b, a+b
count += 1
When I run this code,the answer of of all the inputs gets printed in the same line.
Input:
2
7
5
my output is:
1 1 2 3 5 8 13 1 1 2 3 5
The expected output is:
1 1 2 3 5 8 13
1 1 2 3 5
I want the output in the exact format as I am failing multiple test cases.
This program prints first n numbers of fibonacci series.
Just add an print() after the while loop as suggested by #Tomerikoo.

Function that takes the limit as an argument of the Fibonacci series and prints till that limit in Python3

I've to write a function that takes the limit as an argument of the Fibonacci series and prints till that limit. Here, if the limit is fibonacci(10) then the output should be 0 1 1 2 3 5 8
I tried:
def fibonacci(number):
a = 0
b = 1
print(a,end = ' ')
print(b, end = ' ')
for num in range( 2 , number):
c = a + b
a = b
b = c
print(c, end = " ")
fibonacci(10)
The output came:
0 1 1 2 3 5 8 13 21 34
What should I do?
You can simply just add a check to see if the number resulting from a+b is going to be larger than the limit.
for num in range( 2 , number):
if a+b > number: return
c = a + b
a = b
b = c
print(c, end = " ")
Output:
0 1 1 2 3 5 8
The break statement exits the for loop so that no numbers over the limit will be printed. You can also use return instead of break. However, if you end up adding logic after the for loop, it will not be reached because return will exit the entire function.
SUGGESTION (courtesy of #OneCricketeer)
You may also use a while loop here instead of a range. This achieves the same output with cleaner, easier to understand code.
while (a+b < number):
c = a + b
a = b
b = c
print(c, end = " ")
def fibonacci(limit):
a=0
b=1
print(a,end=" ")
print(b,end=" ")
for i in range(limit):
c=a+b
if c<=limit:
print(c,end=" ")
a=b
b=c
x=int(input())
fibonacci(x)
Input:
10
Output:
0 1 1 2 3 5 8

python Program is saying 2 numbers are different when they are the same

Thanks for the help in advance.
I compare 2 variables which hold numbers with the operation !=
the program takes input like this
4
1 2 3 4
Then the program should return the highest product exluding a square product. In this case the result should be 12(4x3) not 16(4x4) but it is incorrectly returning 16.
The code is here
def max_pairwise_product():
n = int(input())
a = input().split()
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != integer1:
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
This is because your comparing an int to a str. I have edited your code minimally to fix this issue, but you have better to edit your list input before hand.
def max_pairwise_product():
n = int(input())
a = input().split() #If I were you I would do: a = [int(x) for x in input().split()]
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != int(integer1): #This is were I have changed
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
You compare string vs. integer which is always False:
for integer1 in a: # integer1 is a string
product = int(integer1) * n
if n != integer1: # n is a number
Fix:
def max_pairwise_product():
_ = input() # not used
a = "1 2 3 4".split() # input() removed and fixed input given
a = sorted(set(map(int,a))) # convert all to intergers and sort unique numbers
maxno = 0
for idx,number in enumerate(a):
for number2 in a[idx+1:]:
maxno = max( maxno, number*number2 )
return maxno
print(max_pairwise_product())
Output:
12
The loops are optimized leveraging the fact that they numbers are sorted and unique - thats why the second loop can be shorter - no need to recompute already computed results.
Its good if you get inputs like '1 1 1 1 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6' because it will only compute for '1 2 3 4 5 6' and never compute any paring twice.

Trouble with while loop and end = ' '

I'm writing a program in which a range of numbers prints on one line. However my code:
while True:
user = int(input('Enter'))
if user > 0 :
for x in range (0,user +1):
print(x,end=' ')
Has the following output:
Enter9
0 1 2 3 4 5 6 7 8 9 Enter
Why does enter print on the same line? How do I change this?
Use this:
while True:
user = int(input('Enter'))
if user > 0 :
for x in range (0,user +1):
print(x,end=' ')
print()
You have to add just one print() statement after for loop. This makes sure that a line break is added after the elements in the range sequence is printed out.
Your print command does not end with a new line. Add:
print()
after the for loop.
Your code prints "Enter" on the same line because you set the "end" parameter of print to ' '. Therefore, when you print "Enter" you begin in the same line and not in a new one. The default value of "end" is \n meaning that after the print statement it will print a new line.
I'd suggest you to add \n before you print "Enter". This will fix your problem and will be easier to read. Try to change your code to this:
while True:
user = int(input('\nEnter: '))
if user > 0 :
for x in range (0,user +1):
print(x,end=' ')
And you'll see results similar to this:
Enter: 7
0 1 2 3 4 5 6 7
Enter: 8
0 1 2 3 4 5 6 7 8
Enter: 4
0 1 2 3 4
Enter: 1
0 1

Subset in Python output error - HackerRank

This is a question from HackerRank
You are given two sets A and B.
Your job is to find whether set A is a subset of set B.
If set A is subset of set B print True.
If set A is not a subset of set B print False.
Input Format:
The first line will contain the number of test cases T.
The first line of each test case contains the number of elements in set A.
The second line of each test case contains the space separated elements of set A.
The third line of each test case contains the number of elements in set B.
The fourth line of each test case contains the space separated elements of set B.
Output Format:
Output True or False for each test case on separate lines.
Sample Input:
3
5
1 2 3 5 6
9
9 8 5 6 3 2 1 4 7
1
2
5
3 6 5 4 1
7
1 2 3 5 6 8 9
3
9 8 2
Sample Output:
True
False
False
I coded this and it worked fine. The output and expected output matches but the output is claimed to be wrong. I even checked if it was because of any trailing whitespace characters. Where am I going wrong ?
for i in range(int(raw_input())):
a = int(raw_input()); A = set(raw_input().split())
b = int(raw_input()); B = set(raw_input().split())
if(b<a):
print "False"
else:
print A.issubset(B)
The problem specification says this:
Note: More than 4 lines will result in a score of zero. Blank lines won't be counted.
Your solution uses 7 lines, so it counts as a failure.
In Python-3
##Hackerrank##
##Check Subset##
for i in range(int(input())):
a = int(input())
A = set(input().split())
b = int(input())
B = set(input().split())
print(A <= B)
t = int(input())
ans = []
for i in range(t):
A = int(input())
a = list(map(int,input().split()))
B = int(input())
b = list(map(int,input().split()))
check = 0
for c in range(A):
if(A>B):
check = 0
break
else:
for j in range(B):
if(a[c]==b[j]):
check = 1
break
else:
check = 0
if(check == 0):
break
if(check == 1):
ans.append('True')
else:
ans.append('False')
del a
del b
print('\n'.join(map(str,ans)))
for i in range(int(input())):
a = int(input())
A = set(input().split())
b = int(input())
B = set(input().split())
print(A.issubset(B))

Categories