i want to take input from user in and each value of the input is on consecutive line.this is to be implemented in python
while x=int(raw_input()): ##<=showing error at this line
print(x)
gollum(x)
#the function gollum() has to be called if the input is present
The reason why your code does not work is why wants a condition or an object. As you are assigning a value (x=raw_input()), while does not find anything to test (an assignment does NOT return any value).
You can either request an input, and then do a while loop depending on the value of this input (that will be modified inside the while loop) :
x = int(raw_input())
while x:
print(x)
gollum(x)
x = int(raw_input())
That gives you an error because x=int(raw_input()) doesn't return a boolean, and you need a boolean inside the while condition.
You can try this one:
while True:
x = raw_input()
if x=='':
break
x = int(x)
print(x)
gollum(x)
that way if you put an empty string (just an enter) the program just stops and doesn't give an annoying error :P
Related
Without making my foo function contain an actual print statement, and only have foo return a
value, what is the best way to format a function? The code in the example will make the main function print "11" for example, instead of "1 1" or "1 & 1".
I really appreciate ya'll!
def foo(x,y):
if x == y:
return x*2
def main():
x=input("Enter value 1")
y=input("Enter value 2")
print(int(max(x,y)))
main()
Even though the code that you've provided isn't matching your actual question (in the title), I'll try to answer what I think is your question.
You can try returning a string with a space in between the elements, like so:
def foo(x,y):
if x == y:
string = str(x)+" "+str(y) #there's a space between the quotation marks
return string
#this works even if x and y are not integers due to `str(x)` & `str(y)`
Another approach is:
def foo(x,y):
if x==y:
n = 2 #this is the number of times you want x to appear in the output
x_new = x+" " #x concatenated with a space
return (x_new*n).rstrip()
#here, rstrip() is a string method that removes\
#whitespaces from the *right* end of the string
The advantage of concatenation of strings is that you can concatenate any character (or string!) to str(x). For example, you can return str(x)+"&"+str(y) and you'll get 1&1 for x=1!
In the image below, I have defined foo(x,y) thrice and then printed the value returned by the function. NOTE: This is in the interactive Python IDLE Shell.
quick question since I was not able to find a sufficient answer online.
Following code snippet:
def Credentials (x, y):
list = [("test", 1234), ("test2", 4567)]
for list in list:
if list[0] == userinput1 and list[1] == userinput2:
print("success")
return True
else:
print("error")
return False
userinput1 = str(input("provide username: "))
userinput2 = int(input("provide PW: "))
Credentials(userinput1, userinput2)
I do not fully understand why the boolean values True and False will return the print statements. I know that we use return statements to work with functions in our main program and that we could also define variables and return those. But why exactly does returning the booleans will give us the print outputs?
Many thanks in advance.
Short answer: It does not
In your function/in my function shown below,
def returnBools():
(print) print('Printed')
(return) return True
print(returnBools())
The print function and the return statement are actually two different things. The print has nothing to do with the return, and the return statement does not in anyway trigger the print function.
Additionally, the way we call the function can effect the output
For example, printing the function print(returnBools()) will display the returned value along with any print functions in our function
output
Printed
True
But say we did not print the function and only called it. returnBools(). The returned value will not be showed in this case and only the printed values will.
output
Printed
def testfunction():
for i in range(10):
return('a')
print(testfunction())
I want 'a' outputed 10 times in one line. If I use print instead of return, it gives me 10 'a's but each on a new line. Can you help?
return terminates the current function, while print is a call to another function(atleast in python 3)
Any code after a return statement will not be run.
Python's way of printing 10 a's would be:
print('a' * 10)
In your case it would look like the following:
def testfunction ():
return 'a' * 10
print(testfunction ())
The reason its only printing once is because the return statment finishes the function (the return function stops the loop).
In order to print 'a' 10 times you want to do the following:
def testfunction():
for i in range(10):
print('a')
testfunction()
If you want "a" printed 10 times in one single line then you can simply go for:
def TestCode():
print("a"*10)
There's no need to use the for loop. For loop will just "a" for 10 times but every time it'll be a new line.
You can also take in a function argument and get "a" printed as many times as desired.
Such as:
def TestCode(times):
t = "a"*times
print(t)
Test:
TestCode(5)
>>> aaaaa
TestCode(7)
>>> aaaaaaa
print and return get mixed up when starting Python.
A function can return anything but it doesn't mean that the value will be printed for you to see. A function can even return another function (it's called functional programming).
The function below is adapted from your question and it returns a string object. When you call the function, it returns the string object into the variable called x. That contains all of the info you wanted and you can print that to the console.
You could have also used yield or print in your for loop but that may be outside of the scope.
def test_function(item:str="a", n:int=10):
line = item*n # this will be a string object
return line
ten_a_letters = test_function()
print(ten_a_letters)
"aaaaaaaaaa"
two_b_letters = test_function("b",2)
print(two_b_letters)
"bb"
I want 'a' outputed 10 times in one line. If I use print instead of
return, it gives me 10 'a's but each on a new line.
If you want to use print, the you need to pass a 2nd parameter as follows:
def testfunction():
for i in range(10):
print('a', end='')
However, I think the pythonic way would be to do the following:
def testfunction():
print('a' * 10)
When you use return you end the execution of the function immediately and only one value is returned.
Other answers here provide an easier way to solve your problem (which is great), but I would like to suggest a different approach using yield (instead of return) and create a generator (which might be an overkill but a valid alternative nonetheless):
def testfunction():
for i in range(10):
yield('a')
print(''.join(x for x in testfunction()))
1. What does "yield" keyword do?
def test ():
print('a' * 10)
test()
Output will be 'aaaaaaaaaa'.
I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?
string = "Hello"
reverse = string[::-1]
print(reverse)
I tried putting it in a function but I cannot make it print Hello.
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
also tried this
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
Nothing seems to work. I'm having same problem with this as well.
total = 0
def length(words):
for i in words:
total += 1
return total
Functions without a return value
Functions that just take action or do something without returning a value (for example, print).
Functions that don't return a value can be defined like that:
def sayHello():
print "Hello!"
And can be used (called) like that:
sayHello()
And the output will be:
Hello!
Function parameters
A function can also receive parameters (type of variables) from the caller. It's better to demonstrate it with an example.
A function that receives a name and greets this name:
def sayHelloTo(name):
print "Hello", name
It can be called like that:
sayHelloTo("Yotam")
And the output will be:
Hello Yotam
The parameters are the function's input.
Functions with a return value
Other functions, unlike sayHello() or sayHelloTo(name) (that just do something) can return a value. For example, let's make a function that rolls a dice (returns a random number between 1 and 6).
from random import randint
def rollDice():
result = randint(1, 6)
return result
The return keyword just sets the output value of the function and exits the function. An example use of the rollDice function will be:
dice = rollDice()
print "The dice says", dice
When the function hits a return keyword, it finishes and the return value (in our case, the variable result) will be placed instead of the function call. Let's assume randint(1, 6) has produced the number 3.
Result becomes 3.
Result is returned.
Now, instead of the line:
dice = rollDice()
We can treat the line as:
dice = 3
(rollDice() was replaced with 3)
Functions with parameters and a return value
Some functions (for example, math functions) can take inputs AND produce outputs. For example, let's make a function that receives 2 numbers and outputs the greater one.
def max(a,b):
if a > b:
return a
else:
return b
What it does is pretty clear, isn't it? If a is greater, it returns the value of it. Otherwise, returns the value of b.
It can be used like that:
print max(4, 6)
And the output will be:
6
Now, your case
What you want to do is a function that reverses a string. It should take 1 parameter (input) - the string you want to reverse, and output 1 value - the reversed string. This can be accomplished like that:
def reverse_a_string(my_text):
return my_text[::-1]
now you can do something like that:
s = raw_input("Please enter a string to be reversed\n") #input in Python3
r = reverse_a_string(s)
print r
r will contain the reversed value of s, and will be printed.
About your second function - well, I assume that based on this answer you can make it yourself, but comment me if you need assistance with the second one.
Local variables
About your 3rd example:
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
This is something that is really worth delaying and understanding.
the variable reverse is first used inside the function. This makes it a local variable.
This means that the variable is stored in the memory when the function is called, and when it finishes, it is removed. You can say it's lifetime is from when the function is called to when the function is done.
This means that even if you called reverse_a_string(string), you wouln't be able to use the reverse variable outside of the function, because it would be local.
If you do want to pass a value like that, you have to "declare" your variable outside of the function and to use the global keyword, like that:
reverse = "" #This makes reverse a global variable
def reverse_a_string(string):
global reverse #Stating that we are going to use the global variable reverse
reverse = string[::-1]
# Then you can call it like that:
reverse_a_string("Hello")
print reverse
The output will be
olleH
Although it's strongly not recommended to do it in Python, or in any other language.
Once you create a function you must call it. You have created the function reverse_a_string but then you never actually call it. Think about a function as a button that does something everytime it is pushed (or in our case called). If you never push the button then although it has the potential to do something, it never will. In order for the set of instructions to happen we need to push the button (or in our case call the function). So in order for your code to work you first need to define the function then actually call it:
def reverse_a_string():
string="Hello"
reverse = string[::-1]
print reverse
reverse_a_string()
Result: 'olleH'
If you want to pass your own string in to the function so it doesn't just return 'olleH' all the time your code needs to look like such:
def reverse_a_string(stringThatWillBeReversed):
reverse = stringThatWillBeReversed[::-1]
print reverse
reverse_a_string('whateverStringYouWant')
Result: The reverse of the string you entered.
Hope that helps!
I don't know whether you are asking how to define functions in python or something else
If you want to learn python functions, go to http://www.tutorialspoint.com/python/python_functions.htm or just write python tutorial in google, you will get billions of good sites
def reverse_a_string(string):
#function definition
reverse = string[::-1]
print(reverse)
#function call
reverse_a_string("your string")
But you to define function for this, you could simply do
print( string[::-1] )
# defines the 'Reverse a String' function and its arguments
def reverse_a_string():
print(string)
reverse = string[::-1]
print(reverse)
print("Type a string") # asks the user for a string input
string = input() # assigns whatever the user input to the string variable
reverse_a_string() # simply calls the function
for functions, you have to define the function, then simply call it with the function name i.e. funtion()
In my example, I ask for a string, assign that to the variable, and use it within the function. If you just want to print hello (I'm a little unclear from your question) then simply including the print("hello") or w/ variable print(string) will work inside the function as well.
So if I make an input that is function=input() and I want the user to put in a function like y=2x+3. How would I change the x so that it equals one (without the user having to type it in manually) so if I print it, it would be y=21+3
I tried using global x then setting x=1 but that didn't work. (I'm pretty new to python so sorry if I'm missing something obvious.)
You can replace x in input string:
function=input()
# function gets 'y=2x+3' here
function = function.replace('x', '1')
# function now 'y=21+3'
Maybe so
>>> x = 1
>>> formula = raw_input()
>>> formula.replace('x', str(x))