import random
def main():
uinput()
def uinput():
times = int(input('How many numbers do you want generated?'))
number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
rnumber = random.randint(number1, number2)
print (rnumber)
main()
I am messing around in Python, and I want my program to generate random numbers. As you can see I have already accomplished this. The next thing I want to do is have it generate multiple random numbers, depending on how many numbers the "user" wants generated. How would I go about doing this? I am assuming a loop would be required.
This will produce a list of random integers in range number1 to number2
rnumber = [random.randint(number1, number2) for x in range(times)]
For more information, look at List Comprehension.
I would recommend using a loop that simply adds to an existing string:
import random
from random import randint
list=""
number1=input("Put in the first number: ")
number2=input("Put in the second number: ")
total=input("Put in how many numbers generated: ")
times_run=0
while times_run<=total:
gen1=random.randint(number1, number2)
list=str(list)+str(gen1)+" "
times_run+=1
print list
Use a "for" loop. For example:
for i in xrange(times):
# generate random number and print it
Use generators and iterators:
import random
from itertools import islice
def genRandom(a, b):
while True:
yield random.randint(a, b)
number1 = int(input('Put in the first number:' ))
number2 = int(input('Put in the second number:'))
total = int(input('Put in how many numbers generated:'))
rnumberIterator = islice(genRandom(number1, number2), total)
You can define a function to take user input to generate numbers in a given range. You can return the function or print the function.
import random
def ran_nums():
low_range = int(input('Enter the low end of the range: '))
high_range = int(input('Enter the high end of the range: '))
times = int(input('How many numbers do you want to generate? '))
for num in range(times):
print(random.randint(low_range,high_range))
This code chooses a random number:
import random
x = (random.randint(1, 50))
print ("The number is ", x)
Repeat the code 6 times to choose 6 random numbers.
Related
how_many_number = int(input("How many number do you want to print? "))
for take_number in how_many_number:
take_number = int(input("Enter number: "))
sum = 0
sum = sum + take_number
print(sum)
Here you go. To take user input we can use a for loop and for each iteration we can add it to our sum using += operator. You can read through the following code to understand it well enough.
number_of_inputs = int(input("How many number to sum: ")
sum = 0 # Initialize the sum variable
for x in range(number_of_inputs): # Repeat the number of inputs times
sum += int(input("Enter Value: ")) # Take a input and add it to the sum
print("Sum is", sum) # print out the sum after completing
You can also compress it into a List Comprehension, like this...
how_many_number = int(input("How many number do you want to print? "))
print(sum([int(input("Enter number: ")) for i in range(how_many_number)]))
i would use the following, note: error handle is not yet incorporated.
num_list = []
### create a function that adds all the numbers entered by a user
### and returns the total sum, max 3 numbers
### return functions returns the entered variables
def add_nums():
while len(num_list) < 3:
user_num = int(input('please enter a number to add:'))
num_list.append(user_num)
print('You have entered the following numbers: ',num_list)
total_num_sum = 0
for x in num_list:
total_num_sum += x
print('total sum of numbers = ',total_num_sum)
add_nums()
Also, please follow the StackOverFlow post guidelines; have your post title as a problem question, it has to be interesting for other devs, and add more emphasis on why you want to add numbers entered by user vs running calc on a existing or new data-frame, need more meat.
How can I have a program that will ask a minimum and maximum number from a user?, Generate a list of 5 random numbers between the minimum and maximum numbers given, and Display another list where the values are square of the generated 5 numbers?
This is my code. I just want it to display each number with its corresponding squared number.
from numpy import random
import numpy as np
#ask minimun and maximum numbers
a=int(input("Minimum Number: "))
b=int(input("Maximum Number: "))
#random elements and elements size
x=random.randint(a,b , size=(5))
#list of 5 random elements
print("Generated Numbers:", x)
#squared of the 5 random elements
print ("Squared Numbers:", np.square(x))
Try this:
import random
value1 = int(input("Enter minimum value: "))
value2 = int(input("Enter maximum value: "))
randomValues = []
for i in range(5):
randomvalue = random.randint(value1,value2)
randomValues.append(randomvalue)
print("Got Random Values")
print(randomValues)
for value in randomValues:
squareValue = value*value
print("Sqare of value: "+str(value)+" is: "+str(squareValue))
Bro/Sis I typed this answer a bit fastly, If u got any syntax error or something else try resolve it
EDIT: *you can skip converting it to int, I thought it is in float type
x = input("How many numbers, between two and six? ")
print("You have selected, " + x + " numbers!")
import random # I would like to only print out the amount of numbers entered in the first line!!!
numbers = list(range(1,48)) # So if a user types six they get six random numbers and so on.
random.shuffle(numbers)
print(numbers)
After shuffling the list you can just pick x numbers from it;
for i in range(0,x):
print(i)
This does of course assume the input is a number, and you've set the input as an integer with x = int(input("text")).
import random
x = input("How many numbers, between two and six? ")
print("You have selected, " + x + " numbers!")
numbers = list(range(1,48))
print([random.choice(numbers) for x in range(int(x))])
random.choice(numbers) is a function that takes a argument that must be list and give you any random number as return value, the for loop is used to run random.choice() function for range defined by x. suppose user enter the value 2 so we have x=2 then our for loop will run 2 times and we have 2 random value as output from our numbers list.
try this:
for x in range(int(x)):
print(random.randint(1, 48))
it will work you can also append into the list if you want.
have you tried this
import random
x = input("How many numbers, between two and six? ")
print("You have selected, " + x + " numbers!")
li = [random.random() for x in range(int(x))]
print(li)
I'm trying to make a random number generator and return the random generated number, but this code returns all the numbers before the random number. How can I return only the last string printed?
import random
from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))
for num in range(random.randrange(from_num,to_num+1)):
if True:
print(f'Random number: {num}')
else:
print('You did not entered valid min/max numbers')
Output for from_num = 0 and to_num = 20 by exemple, instead of '11' can return any number between these two given.
Random number: 0
Random number: 1
Random number: 2
Random number: 3
Random number: 4
Random number: 5
Random number: 6
Random number: 7
Random number: 8
Random number: 9
Random number: 10
Random number: 11
Following to the comments above, just print the random value, without iterating on anything:
import random
from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))
if from_num > to_num:
print('You did not entered valid min/max numbers')
return
random_num = random.randrange(from_num,to_num+1):
print(f'Random number: {random_num}')
Replace this :
for num in range(random.randrange(from_num,to_num+1)):
if True:
print(f'Random number: {num}')
else:
print('You did not entered valid min/max numbers')
with :
ran_num = random.randint(from_num,to_num)
print("Random number is " + str(ran_num))
Why do you have a loop?
import random
from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))
if to_num > from_num:
ran_number = random.randrange(from_num,to_num+1)
print(f'Random number: {ran_number}')
else:
print('You did not entered valid min/max numbers')
If you're trying to make it so the user can pick the range then i don't know but if you want it random on a button click then heres the code first do this
int Rnumber;
then
TextView RandomNumber;
The "RandomNumber" You must make a textview that has the id RandomNumber
Oh! And before i forget you need a button with the id GenRan.
Then put in this code
Button GenRan;
Insert this code
Random Number;
Then this code
Number = new Random();
Rnumber = Number.nextInt(1000);
RandomNumber.setText(Integer.toString(Rnumber));
and you're good to go and btw the "(1000)" is the max number it can generate so its from 1-1000 you can change that if you want
Im having trouble with sorting Variables/lists and then being able to transfer them across functions. Im still quite new to python and am probably missing something very basic. but ive been going over this for hours.
I need to create a program which generates 20 random integers and indicates whether each number is odd or even. I need to sort the two original integers into ascending order and transfer them to random.randint function but am having trouble, any help would be appreciated.
This is what i have so far.
import random
def userinput():
global number1
global number2
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
userinput()
def numbersorting():
global both
both = [(number1),(number2)]
sorted(both)
numbersorting()
def random_gen():
global num
i = 0
for i in range(20):
num = random.randint(number1,number2)
def get_num():
return values.pop
def odd_even():
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
odd_even()
random_gen()
Well it doesn't seems so clear on the question what actually you want to do but the use of global is a really bad practice in general.
However you can use the methods that returns the values you need for instace:
If you need a user input that returns 2 numbers it is better to use this approach:
def get_numeric_input(label):
try:
return int(input(label))
except NameError:
print "Please enter a number"
return get_numeric_input(label)
With this function you can get a numeric value from a user.
Using it you can the 2 next values like
def get_user_input():
n = get_numeric_input("Enter First Integer: ")
m = get_numeric_input("Enter First Integer: ")
return [n, m]
Now you have a function that returns the 2 values from the user and using the sort method for list you have those values sorted
def get_sorted_values(l):
return l.sort()
Check this information about sorting in python https://wiki.python.org/moin/HowTo/Sorting
Using the random numbers as you have described is ok, but also try to use the is_odd and is_even function outside of any other function and you will be able to reuse them more times.
Are you looking for something like this?
I edited your code to work with what I understand your problem to be...
You want the user to input 2 numbers to set the upper and lower bound of each random number. Then you want to generate 20 random numbers within that range and find out whether each number of even or odd?
import random
def random_gen(number1, number2):
for i in range(20):
num = random.randint(number1,number2)
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
random_gen(number1, number2)
You have a few problems with your current code:
Indentation (fixed in the edit)
Unnecessary use of global variables. If you need that type of functionality you should consider passing the variables into each function as you need it instead
A number of functions are unnecessary too. For example, you dont need the get_num() and odd_even() functions as you can just perform those actions within the loop that you have. Even in the case I just posted you dont even really need the random_gen() function - you can just move all of that code to after user input. I just left it there to show what I mean with point #2 above
from random import randint
def user_input():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
if number1 > number2:
number1, number2 = number2, number1
return number1, number2
def odd_even(num):
if num % 2 == 0:
print("Random Number " + str(num) + " is even")
else:
print("Random Number " + str(num) + " is odd")
def random_gen():
number1, number2 = user_input()
for i in range(20):
num = randint(number1, number2)
odd_even(num)
random_gen()
You generally want to try to avoid using global variables when possible. It's just good programming practice, as they can get rather messy and cause problems if you don't keep careful track of them. As far as sorting your two integers, I think that that one if statement is a much more pythonic way of doing things. Well, I think it's easier at least. Also, in Python, you don't need to declare your for loop variables, so the line i=0 is unnecessary. Also, I'm sure this is an assignment, but in real life you're going to want to run an exception clause, in which you would say something like
while True:
try:
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
break
except ValueError:
print("Oops! Try entering an integer!")
Hope that helps!
Avoid globals by passing the variables to functions and returning the new values from functions.
import random
def userinput():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
return number1, number2
def numbersorting(nums):
return sorted(nums)
def random_gen(hi, lo):
return random.sample(range(hi, lo), 20)
def odd_even(num):
if num % 2 == 0:
print("Random Number %d is even" % num)
else:
print("Random Number %d is odd" % num)
nums = userinput()
sortnum = numbersorting(nums)
randoms = random_gen(*sortnum)
[odd_even(n) for n in randoms]
In keeping with your original function names.
You should be aware of the difference between list.sort and sorted. If you have a list li then li.sort() sorts in place, that is it alters the original list and returns None. So return li.sort() is always wrong. on the other hand return sorted(li) is ok, but just sorted(li) is a wasted sort since the result is thrown away.
Try both.sort()
sorted returns a new list.
sort() is done in place.