Hello, so my task is shown above in the image. I'm not asking for answers, I would just like to know how to get started on this.
My initial ideas are to:
1. Have user input str("example word")
2. Have user input int("Example number")
3. Use a for loop to read the number and then print the word out.
So far, my code is as shown below:
def repeat():
word=str(input("Please input a single word: "))
number=int(input("Please input a number: "))
for i in range(number):
number+=1
print(word,end=" ",sep='')
repeat()
However I'm running into two issues:
1. When printing the word out, the output is i.e "hello hello hello" instead of "hellohellohello"
2. I feel like I'm not exactly hitting the right points for the question.
Would appreciate any help!
This portion of your code:
print(word, end=' ', sep='')
is adding those spaces. You don't need those. Also, I'm not sure why you're incrementing the 'number' datatype. No need to do that since you're only using that for the amount of times the for loop will go based on the user input. Also, this should all be passed to a function that has two paramters: One to accept and integer and the other to accept a string. For example:
repeat(intA, strB)
Also, my suggestion would be to concatenate. Add your strings together instead of just displaying it multiple times. This will also allow you to create a new variable that will later be returned to the function that called it.
You can create function as below to repeat the string:
def repeat(text, occurrence):
new_text = ''
for i in range(occurrence):
new_text += text
return new_text
print(repeat('Hi', 4)) # sample usage
Finally you can implement your code like:
In [6]: repeat(input("Please input a single word: "), int(input("Please input a number: ")))
Please input a single word: hello
Please input a number: 5
Out[6]: 'hellohellohellohellohello'
More pythonic is to use a generator expression:
def f(s,n):
return ''.join(s for _ in range(n))
or Python's standard library:
import itertools as it
def f(s, n):
return ''.join(it.repeat(s, n))
print(f('Hi', 3))
Both produce
'HiHiHi'
Related
I am currently a beginner in Python. This is my problem: First, the program asks that you input a number.
For example, if I put 1, I get 1 out. If i put 2, i get 12 out. If I put 3, I get 123. If I put 4, I get 1234. That is the gist of this set of problem. However, I developed a mathematical equation that works if I put it through a loop:
if __name__ == '__main__': # ignore this part
n = int(input())
s = 1
while s > n:
z = s*10**(n-s)
s += 1
answer = z
if s == n:
print(z)
When I tried to run this code, I got nothing, even though I added print at the end. What is it that I am doing wrong here? For anyone answering the problem, introduce any concepts that you know that may help me; I want to learn it.
Please enlighten me. Don't exactly give me the answer....but try to lead me in the right direction. If I made a mistake in the code (which I am 100% sure I did), please explain to me what's wrong.
It's because your while loop condition is backwards. It never enters the loop because s is not bigger than n. It should be while s < n
Use a for loop using range() as in
for i in range(1, n+1):
where n is the input so that the numbers from 1 till n can be obtained.
Now use a print() to print the value of i during each iteration.
print() by default will add a newline at the end. To avoid this, use end argument like
print(var, end='')
Once you are familiar with this, you can also use list comprehension and join() to get the output with a single statement like
print( ''.join([str(i) for i in range(1, n+1)]) )
Take the input as you've done using input() and int() although you might want to include exception handling in case the input is not an integer.
See Error handling using integers as input.
Here is the solution:
Using string
a = int(input())
# taking the input from the user
res=''
# using empty string easy to append
for i in range(1,a+1):
# taking the range from 1 (as user haven't said he want 0, go up to
# a+1 number (because range function work inclusively and will iterate over
# a-1 number, but we also need a in final output ))
res+=str(i)
# ^ appending the value of I to the string variable so for watch iteration
# number come append to it.
# Example : 1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
# so after each iteration number added to it ,in example i have taken a=9
sol = int(res) #converting the res value(string) to int value (as we desire)
print(sol)
In one line, the solution is
a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))
Try this,
n = int(input('Please enter an integer'))
s = 1
do:
print(s)
s+=1
while s == n
this works.
(Simple and Short)
So I'm trying to create a program in Python that:
A) Prompts a user to enter a number a certain amount of times
B) Then stores those numbers in a list and prints them in reverse order.
This is my code:
for numbers in range (1,4):
print("Please enter a number.")
numbers = input()
numbersList = list(reversed(str(numbers)))
print(numbersList)
When I run it, it just prints <list_reverseiterator object at 0x105447da0>. And even when I tried it without adding 'reversed' in the code, instead of printing a list of ALL the numbers entered in reverse order like I want it to, it spits out the most recent number entered in list format. So if I enter '4' for a number, it just prints: ['4']. No idea why it's doing that. Any help would be appreciated. Thanks.
If I understood correctly, this is what you're looking for:
numbers = []
for i in range (1,4):
print("Please enter a number.")
numbers.append(input())
numbersList = str(numbers)
numbersList.reverse()
print (numbersList)
As commented, i is an iterator generated by range command. One way to collect 3 numbers from the user is to append them into a list, numbers in this case.
After that you can process your list outside the loop. It also seems more viable to reverse the list once it is fully created which again points to outside the loop. I use Python 2.7 so the solution is a bit different than your initial one, but the result is as intended - first it converts all the numbers to strings using map and then it reverses the list in place using reverse.
Try something like this:
numbersList = []
for numbers in range (1,4):
print("Please enter a number.")
numbersList.append(input())
numbersList.reverse()
print(numbersList)
First, you have to define numbersList. Then, you append values to in while in the loop and finally print it out.
Your issue was that you were defining the list each time you ran the for loop (3 times in the above example) and so it only had the last value. (Also, you were tying to print it out each iteration as well).
Also, a 'point of interest' - you can use input("User prompt here: ") to avoid using print() the line before.
l=[]
for _ in range(1,5):
l.append(int(input("enter the number: ")))
print(l[::-1])
First of all: Yes I know, this is not what you call elegant programming, but my only target is to do it short, not readable.
Now the real problem:
I want to store an amount of x Strings in a list.
The user inputs how many Strings he wants to input and then one by one afterwards. Here's what I got so far:
print(
[
exec(
('input("text: "),' * int(input('number: ')))[:-1]
)
]
)
And this is a sample output:
number: 4
text: one
text: two
text: three
text: four
[None]
Why arent the inputs taken into account during list creation?
And how can i do this (short[er])?
Shorter and more readable.
print([input("text: ") for i in range(int(input("number: ")))])
The shortest and dumbest I could produce...
print map(input,['text: ']*input("number: "))
input("number: ") produce an str given the user input
['text: ']*input produce an array of length equal to the input, containing 'text: ' for every values
map iterate over the array and give the value to input
results are return as a list and printed
Edit Python3:
print(list(map(input,['text: ']*int(input("number: ")))))
Edit2: Saved one char for python2 thx to #Delgan
Readable > short almost every time.
In this instance, assuming you want a list of strings from the user, something like:
count = int(input("number of strings: "))
strings = []
for i in range(count):
strings.append(input("text: "))
print(strings)
should work.
In general, try to avoid exec.
I am trying out this problem in a coding competition. I believe I have solved the problem, but have some problem in taking the input. Help me out here:
Input
The first line of the input contains a single integer T denoting the number of test cases. The description for T test cases follows. Each test case consists of a single line containing two space-separated strings R and S denoting the two recipes.
Now, I have coded the problem and it seems to work, but whenever I directly copy paste the input values, it fails to work by giving this error message
T= int(raw_input())
ValueError: invalid literal for int() with base 10:
'3\nalex axle\nparadise diapers\nalice bob'
Whenever I try to submit the problem, I get an error message. May be they are also copy pasting the input values and checking for the output. My code skeleton goes something like this
def whetherGranama(str1,str2):
return "NO"
#can't give the implementation out yet
T= int(raw_input())
ans=[]
for x in range(0,T):
s=raw_input()
s1,s2=s.split()
ans.append(whetherGranama(s1,s2))
for elem in ans:
print elem
How can I fix the \n error ? I think the entire input is treated as one string.
Split the input, extract the integer the process using the split list
s = raw_input()
s = s.split()
T = int(s[0])
ans=[]
for st in s[1:]:
//Do the rest
If the entire input is being read in as one string, you could try using stdin.readline() instead of raw_input to capture the input stream:
from sys import stdin
T = int(stdin.readline())
Since this is a coding competition however, I'm assuming that speed is of the essence. Since IO operations are computationally expensive, you should actually welcome the opportunity to read all of your input at one time. In other words, it's generally faster to read it in all at once and then parse the input within your code. I guess in your case, it would look something like this (assuming that it comes in all at once by design):
data = raw_input().splitlines()
#(or data = sys.stdin.read().splitlines() or data = list(sys.stdin.readlines()))
T = int(data[0])
S = (s.split() for s in data[1:])
Split your input first and then convert the int:
T, body = raw_input().split("\n", 1)
for x in xrange(int(T)):
...
That will split once and give you the first number item and then the rest of your input string.
Yes the entire string is treated as one input. You can simply store the input as a list and work with the list instead of calling raw_input in your loop, that would look something like this:
def whetherGranama(str1,str2):
return "NO"
#can't give the implementation out yet
input_lines = raw_input().split("\n")
T = int(input_lines[0])
ans=[]
for x in range(1,T):
s = input_lines[x]
s1,s2=s.split()
ans.append(whetherGranama(s1,s2))
for elem in ans:
print elem
I know how to take a single input from user in python 2.5:
raw_input("enter 1st number")
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box.
How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number:................
enter second number:.............
This might prove useful:
a,b=map(int,raw_input().split())
You can then use 'a' and 'b' separately.
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ")
input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
Or if you are collecting many numbers, use a loop
num = []
for i in xrange(1, 10):
num.append(raw_input('Enter the %s number: '))
print num
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
print(i)
a, b, c = input().split() # for space-separated inputs
a, b, c = input().split(",") # for comma-separated inputs
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
The best way to practice by using a single liner,
Syntax:
list(map(inputType, input("Enter").split(",")))
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
List_of_input=list(map(int,input (). split ()))
print(List_of_input)
It's for Python3.
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second)
print('The product of the two is ' + str(product))
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way.
I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]
print items
You can try this.
import sys
for line in sys.stdin:
j= int(line[0])
e= float(line[1])
t= str(line[2])
For details, please review,
https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects
Split function will split the input data according to whitespace.
data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = []
# endless loop, exit condition within
while True:
inputstr = input('Enter another string, or nothing to quit: ')
if inputstr:
strings.append(inputstr)
else:
break
This is Python 3 code; for Python 2, you would use raw_input instead of input.
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can't for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines:
strings = [line.rstrip('\n') for line in lines]
n = int(input())
for i in range(n):
i = int(input())
If you dont want to use lists, check out this code
There are 2 methods which can be used:
This method is using list comprehension as shown below:
x, y = [int(x) for x in input("Enter two numbers: ").split()] # This program takes inputs, converts them into integer and splits them and you need to provide 2 inputs using space as space is default separator for split.
x, y = [int(x) for x in input("Enter two numbers: ").split(",")] # This one is used when you want to input number using comma.
Another method is used if you want to get inputs as a list as shown below:
x, y = list(map(int, input("Enter the numbers: ").split())) # The inputs are converted/mapped into integers using map function and type-casted into a list
Try this:
print ("Enter the Five Numbers with Comma")
k=[x for x in input("Enter Number:").split(',')]
for l in k:
print (l)
How about making the input a list. Then you may use standard list operations.
a=list(input("Enter the numbers"))
# the more input you want to add variable accordingly
x,y,z=input("enter the numbers: ").split( )
#for printing
print("value of x: ",x)
print("value of y: ",y)
print("value of z: ",z)
#for multiple inputs
#using list, map
#split seperates values by ( )single space in this case
x=list(map(int,input("enter the numbers: ").split( )))
#we will get list of our desired elements
print("print list: ",x)
hope you got your answer :)