Change result by function - python3 - python

I need to generate random number with 4 various literature,
so i wrote this program:
import random
def rand():
i=0
n=""
while i<4:
a = str(random.randint(0,9))
if a not in n:
n +=a
i+=1
return n
print (rand)
The content of the function is correct, but the function cause to strange result :
<function rand at 0x000001E057349D08>
what am I missing?

You are printing the reference to the function itself instead of invoking it. To invoke it, you need to follow it with parenthesis (()):
print (rand())
# Here ----^

Related

Return outside the function error:(Python)

Here, for this code I'm getting an error on return outside the function.
Can I anyone explain why is this so?
import numpy as np
name = input().split(" ")
arr = [int(num) for num in name]
sum=[]
for i in arr:
sum=+i
return sum
return statement only makes sense inside functions. To show or display infos use print(sum)
You are using the return keyword outside of a function. If you want to display the sum on screen use: print(sum).
You can't use the return statement outside a function. It is used to end the execution of a function and return the results of that particular function. You can simply modify your script to a function like this.
import numpy as np
name = input().split(" ")
arr = [int(num) for num in name]
def function_name(array):
sum=[]
for i in array:
sum=+i
return sum
variable_name = function_name(arr)

Calculating a factorial using loops in Python3

I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.
I almost have it but I've run into two issues that I just can't seem to resolve.
1) The function is returning an extra line of "None" after the calculation and
2) The answer is displaying over multiple lines when I want it to display on a single line.
My current code (which does return the correct answer) is as follows:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
When I test, using 3 for example, the REPL returns the following:
>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None
So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly.
Any help would be much appreciated.
your function calcFactorial(3) prints already, so you shouldn't call it with
print(calcFactorial(3))
just call it with
calcFactorial(3)
without the print function.
you might think about calling the function calc_and_print_factorial() in order to make it clear, that this function does already the printing
Regarding your second question:
Blockquote
2) The answer is displaying over multiple lines when I want it to display on a single line.
You can fix it by using a single print statement:
def calcFactorial(number):
factorial = 1
string = str(number) + "! = " + str(number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*(number-count)
string = string + " x " + str(number-count)
factorial = factorial * number
print(string + " = " + str(factorial))
This will give you:
IN: calcFactorial(3)
OUT: 3! = 3 x 2 x 1 = 6
On a side note: you might want to think of how to implement this recursively. Maybe that comes later in your class but this would be one of the first go-to examples for it.
Adding to the blhsing's answer, you should choose between these built-in ways to print the "returned" value.
First way:
def calcFactorial(number):
... # <- Your function content
return factorial
Then, call your function with a print() to get the explicitly returned value, as you can see in the return factorial line. See this reference for more details:
print(calcFactorial(3))
Second way:
Having the same function definition with its return statement, just call the function with its instance statement:
calcFactorial(8)
By default, python will print the returned value without a print()
Third way:
Just call the function (without the explicit return statement, this will return a "None" (null-like) value by default), using the print() method. Do NOT use print() inside another print().
Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.
You should make the calcFactorial function return factorial as a result at the end:
def calcFactorial(number):
factorial = 1
print(str(number)+"! =", number)
for count in range (1, number):
if number-count > 0:
factorial = factorial*number-count
print("x", str(number-count))
factorial = factorial*number
print("=", factorial)
return factorial
So I have the correct answer but with an extra line of "None" which I would like to remove
You are printing the return value from your function. In this case, you haven't specified a return value with a return statement so the function automatically returns None.
To fix the problem, you should return a value from your function. Note that you don't need to call print() for final answer because the REPL already does this for you.
Note that the REPL will automatically print the return value for you, so you can just type calcFactorial(3) instead of print(calcFactorial(3)).
Additionally, you are not getting the correct answer. You should get 6 instead of 12. It looks like you are trying to count down from number and multiplying each number together. You can get the same result by counting up from 1. This will lead to much simpler code and avoid the error.
If you want to understand why your code isn't doing the correct thing, look closely at factorial = factorial*number-count and think about the order of operations that are used to calculate the result here.

Python: Why does return not actually return anything that I can see

I have the following code:
def is_prime(n):
limit = (n**0.5) + 1
q = 2
p = 1
while p != 0 and q < limit:
p = n % q
q = q + 1
if p == 0 and n != 2:
return 'false'
else:
return 'true'
But when I send in an integer, there is nothing returned. The console simply moves on to a new command line. What's wrong here?
EDIT 1:
The following are screenshots of different scenarios. I would like to make it such that I call the function with a particular number and the function will return 'true' or 'false' depending on the primality of the number sent into the function. I guess I don't really understand the return function very well.
Also, note that when I send in to test 9, it returns true, despite 9 being quite definitely a composite number...should the if/else bits be outside the while loop?
Key to below image:
1: this is the code as it is above and how I call it in the Spyder console
2: adding a print statement outside the function
3: this is a simple factorial function offered by the professor
image here
EDIT 2:
I made a quick change to the structure of the code. I don't really understand why this made it work, but putting the if/else statements outside the while loop made things result in expected true/false outputs
def is_prime(n):
limit = (n**0.5)+1
q=2
p=1
while p!=0 and q<limit:
p = n%q
q = q+1
if p==0 and n!=2:
return 'false'
else:
return 'true'
Also, I call the function in the console using is_prime(int_of_choice)
Thanks for the helpful suggestions
If you want to print something to the console you have to use a print statement. The return keyword means that you can use this value in a piece of code that calls this function. So to print something:
print (x)
For more information about the print statement see: https://en.wikibooks.org/wiki/Python_Programming/Variables_and_Strings
Nothing is wrong, but you have to print out the return of your function.
Like this:
def Test():
if True:
return "Hi"
print(Test())
In this case python will show "Hi" in your console.

How to use python to print strings as processing like this

I want to write a function to print out string like this:
Found xxxx...
for x is result calculating by another function. It only print one line, sequential, but not one time. Example: I want to print my_name but it'll be m.... and my.... and my_...., at only line.
Can i do this with python?
Sorry I can't explain clearly by english.
UPDATE
Example code;
import requests
url = 'http://example.com/?get='
list = ['black', 'white', 'pink']
def get_num(id):
num = requests.get(url+id).text
return num
def print_out():
for i in list:
num = get_num(i)
if __name__ == '__main__':
#Now at main I want to print out 2... (for example, first get_num value is 2) and after calculating 2nd loop print_out, such as 5, it will update 25...
#But not like this:
#2...
#25...
#25x...
#I want to it update on one line :)
If you are looking to print your output all in the same line, and you are using Python 2.7, you can do a couple of things.
First Method Py2.7
Simply doing this:
# Note the comma at the end
print('stuff'),
Will keep the print on the same line but there will be a space in between
Second Method Py2.7
import sys
sys.stdout.write("stuff")
This will print everything on the same line without a space. Be careful, however, as it only takes type str. If you pass an int you will get an exception.
So, in a code example, to illustrate the usage of both you can do something like this:
import sys
def foo():
data = ["stuff"]
print("Found: "),
for i in data:
sys.stdout.write(i)
#if you want a new line...just print
print("")
foo()
Output:
Found: stuff
Python 3 Info
Just to add extra info about using this in Python 3, you can simply do this instead:
print("stuff", end="")
Output example taken from docs here
>>> for i in range(4):
... print(i, end=" ")
...
0 1 2 3 >>>
>>> for i in range(4):
... print(i, end=" :-) ")
...
0 :-) 1 :-) 2 :-) 3 :-) >>>
s = "my_name"
for letter in range(len(s)):
print("Found",s[0:letter+1])
Instead of 's' you can just call function with your desired return value.

My functions are not running

Working with random functions and doing 3 things with 3 different functions, the first gives me values from 1,10 randomly displayed in a list of 10 integers. The second gives me a list values 1,10 and squares them. Then last but not least the third singles out numbers that can be divided by three. The problem is my program is not running while on eclipse the program has no errors, yet my program terminates without printing anything. Please help me...
import random
def main():
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
if __name__ == '__main__':
main()
You are just calling main() not any of the functions nested inside main(),
Using if __name__ == '__main__': does not magically call all your functions.
If your main function was like:
def main():
squareint_()
div3()
rand10()
then you would be calling the other functions as it is, main does nothing or returns nothing.
As far as your methods go, squares.append(random.randint(0,10))**2 is not valid, you cannot use ** on a list method.
It needs to be inside the paren squares.append(random.randint(0,10)**2)
Also num is a list so you cannot use if num % 3 == 0:
You could use something like:
def div3():
divlist = []
num = range(1,10)
for n in num: # loop over the list elements
if n % 3 == 0:
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
There are two current problems with the code:
You're defining your functions inside main(), which is allowed but it's not very good coding practice. If you do this, then you can only ever use these functions from inside main().
You're not actually calling any of your functions, you're just defining them. They need to be called with rand10(), squareint_() or div3().
Try this bit of code instead, which fixes both issues:
import random
def rand10():
my_list = []
for _ in xrange(10):
my_list.append(random.randint(0,10))
print my_list
def squareint_():
squares = []
for _ in xrange(0,10):
squares.append(random.randint(0,10))**2
print squares
def div3():
divlist = []
num = range(1,10)
if (num % 3 == 0):
for _ in xrange(20):
divlist.append(random.randint(0,10))
print divlist
def main():
rand10()
squareint_()
div3()
if __name__ == '__main__':
main()
Of course, if your functions are invalid, then they will need to be fixed on their own. This just solves the issue of nothing happening when you execute your code. Now when you run the project in Eclipse, you'll see some errors and be able to fix them properly.

Categories

Resources