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
Related
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
Question: Create a program that allows the user to enter 10 different integers. If the user tries to enter
an integer that has already been entered, the program will alert the user immediately and
prompt the user to enter another integer. When 10 different integers have been entered,
the average of these 10 integers is displayed.
This is my code:
mylist = []
number = int(input("Enter value: "))
mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
if number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
else:
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
This kind of works but I need to create a loop that will keep on asking the user for another number if the number is in the array. Can you help?
What about:
mylist = []
number = int(input("Enter value: ")) mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
while number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
I have trouble finishing a Python assignment. I'm using Python 3.0
So the program asks the user to input a set of 20 numbers, store them into a list, and perform calculation on it to output the largest number, the smallest, the sum, and the average.
Right now, everything is working, except one thing! In the event of a non numeric input from the user, I would like the program to ask for the input again.
I have trouble doing that, I thought of a Boolean variable, I'm not sure.
Thanks a lot for your help.
Here's my code :
import time
#Defining the main function
def main():
numbers = get_values()
get_analysis(numbers)
#Defining the function that will store the values
def get_values():
print('Welcome to the Number Analysis Program!')
print('Please Enter A Series Of 20 Random Numbers')
values =[]
for i in range(20):
value =(int(input("Enter A Random Number " + str(i + 1) + ": ")))
values.append(value)
#Here we store the data into a list called "values"
return values
#Defining the function which will output the numbers.
def get_analysis (numbers):
print(".................................")
print("The Lowest Number Is:", min(numbers))
time.sleep(1)
print("The Highest Number Is:", max(numbers))
time.sleep(1)
print("The Sum The Numbers Is:", sum(numbers))
time.sleep(1)
print("The Average The Numbers Is:", sum(numbers)/len(numbers))
print(".................................")
main()
Vince
A couple of changes:
added a get_int() function which prompts repeatedly until an integer is entered
used this to simplify your get_values() function
added a how_many parameter. Follows the "don't repeat yourself" principle - if you want to change the number of items, you can do it in one place
moved the "welcome to the program" message out of get_values to main where it belongs
Don't Capitalize Every Word Or Chuck Norris Will Get You
I renamed get_analysis() to show_analysis() because it prints the result rather than returning it; accurate function names are important!
I reduced the analysis to a data-driven loop; this is more a matter of taste than anything else, but I think it is cleaner and easier to understand, especially as the number of tests increases, and also contributes to Don't Repeat Yourself
and the final result:
import time
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
# couldn't parse as int
pass
def get_values(how_many):
return [get_int("Enter #{}: ".format(i)) for i in range(1, how_many+1)]
def average(lst):
return sum(lst) / len(lst)
def show_analysis(numbers):
tests = [
("The lowest value is", min),
("The highest value is", max),
("The sum is", sum),
("The average is", average)
]
print(".................................")
for label,fn in tests:
print("{} {}".format(label, fn(numbers)))
time.sleep(.5)
print(".................................")
def main():
how_many = 20
print("Welcome to the Number Analysis program!")
print("Please enter {} integers".format(how_many))
numbers = get_values(how_many)
show_analysis(numbers)
main()
I ran it on my Python 3 and got this
$ python3 so.py
Welcome to the Number Analysis Program!
Please Enter A Series Of 20 Random Numbers
Enter A Random Number 1: 3
Enter A Random Number 2: 4
Enter A Random Number 3: 2
Enter A Random Number 4: 6
Enter A Random Number 5: 4
Enter A Random Number 6: 3
Enter A Random Number 7: 5
Enter A Random Number 8: 6
Enter A Random Number 9: 8
Enter A Random Number 10: 9
Enter A Random Number 11: 7
Enter A Random Number 12: 6
Enter A Random Number 13: 5
Enter A Random Number 14: 4
Enter A Random Number 15: 3
Enter A Random Number 16: 2
Enter A Random Number 17: 4
Enter A Random Number 18: 6
Enter A Random Number 19: 7
Enter A Random Number 20: 1
.................................
The Lowest Number Is: 1
The Highest Number Is: 9
The Sum The Numbers Is: 95
The Average The Numbers Is: 4.75
.................................
This works fine. Now make a function like this one
import re
def isInteger(x):
seeker = re.compile("-?[0-9]+")
return bool(seeker.search(x))
You can use a loop with header
while not isInnteger(x):
##get number
to repeat until a number is actually entered.
# generate a random number between 1 and 99 sgenrand.randint(1,99) # your code goes here
print("Enter coins that add up to 81 cents, one per line.")
#promp the user to start entering coin values that add up to 81
coin = (sgenrand.randint(1,99))
number1 = ("Enter first coin: ")
sum = 0
number1 = eval(input("Enter first coin: "))
while number1 != coin:
if number1 != coin:
number1 = eval(input("Enter next coin: "))
im stuck in this while loop. I want to have it that the user can hit enter without an answer and breaks out of the loop. after he breaks out, the sum of numbers he previously added is calculated, and if the sum isn't 81. tells the user he didn't reach target value, tells him what value he reached and asks if he wants to start over!
I like doing homework, I really do:
import random as sgenrand
def oneRound():
target = sgenrand.randint(1, 99)
print('Enter coins that add up to {} cents, one per line.'.format(target))
total = int(input('Enter first coin: '))
while True:
s = input('Enter next coin: ')
if not s: break
total += int(s)
if total == target:
print('Well done.')
return True
print('You reached {}.'.format(total))
return input('Do you want to start over? [y/*] ') != 'y'
while not oneRound(): pass
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.