Print 20 random numbers in range, check if odd or even - python

I've been killing myself with this assignment for the past week and I'm still baffled. I have to create a program that gets the user to input 2 numbers, arranges them in order of size, prints 20 random numbers within the range and also determines whether or not they are odd or even. Here's what I've got so far:
#Main function
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
def sortnums(first, second):
if first > second:
return second, first
else:
return first, second
MIN, MAX = sortnums(first, second)
for x in range(20):
random = random.randrange(MIN, MAX)
if random%2 == 0:
print ("The random number", random ,"is even.")
elif random%2 != 0:
print ("The random number", random ,"is odd.")
return random
main()
I'm not just lazily asking for a solution, I've genuinely exhausted my efforts on this one and even contacted my lab tutor for additional advice but I'm still clueless as to why it's not working.
Thanks.

On this line:
random = random.randrange(MIN, MAX)
You've shadowed the random module with a number. You should pick a different variable name, like random_number so subsequent calls to random.randrange don't error:
for x in range(20):
random_number= random.randrange(MIN, MAX)
if random_number % 2 == 0:
print ("The random number", random_number, "is even.")
elif random_number % 2 != 0:
print ("The random number", random_number, "is odd.")
return random_number

A few problems with your code. But you are pretty close. I think you may just have issues with understanding how your program is executed. The "main()" function call at the bottom is the first code execution point. The user prompts are collecting the user data just fine, but then you just define two functions and never actually call them. Additionally, you use the word "random" as a variable name but this is also being used as the namespace for the random library. Below is a fixed up version...
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
MIN, MAX = sortnums(first, second)
for x in range(20):
randNum = random.randrange(MIN, MAX)
if randNum%2 == 0:
print ("The random number", randNum ,"is even.")
elif randNum%2 != 0:
print ("The random number", randNum ,"is odd.")
def sortnums(first, second):
if first > second:
return second, first
else:
return first, second
main()

Your biggest oversight is probably shadowing the random you imported with the first random number you select. After this, you program would fail the second time through the loop when it tries to look up the randrange attribute on an int.
There's already a nice builtin way to sort numbers
def sortnums(first, second):
return sorted([first, second])
More simply, using tuple unpacking
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
for x in range(20):
num = random.randrange(*sorted([first, second]))
if num%2 == 0:
print ("The random number", num ,"is even.")
else:
print ("The random number", num ,"is odd.")
return
main()
You can remove repetition from the print functions like this
import random
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
for x in range(20):
num = random.randrange(*sorted([first, second]))
print("The random number", num ,"is", "odd." if num%2 else "even.")
return
main()

I would take the def sortnums outside of the main function:
import random
def sortnums(first, second):
if first > second:
return second, first
else:
return first, second
Then the MIN, MAX assignment seems to have wrong indentation...
and you re-assign random (the module) with a value. Change it to something
like r or number.
def main():
first = int(input("Enter first integer: "))
second = int(input("Enter second integer: "))
MIN, MAX = sortnums(first, second)
for x in range(20):
r = random.randrange(MIN, MAX)
if r%2 == 0:
print ("The random number", r ,"is even.")
elif r%2 != 0:
print ("The random number", r ,"is odd.")
return r
main()

Try:
import random
min_input = int(input("Enter first integer: "))
max_input = int(input("Enter second integer: "))
if max_input<min_input:
min_input, max_input=max_input, min_input
for i in range(20):
rnd=random.randrange(min_input, max_input)
print 'The random number {} is {}.'.format(rnd, ('even', 'odd')[rnd%2])

Related

How to make a deductive logic game of guessing a three degit number?

The question is: In Bagels, a deductive logic game, you must guess a secret three-digit number based on clues. The game offers one of the following hints in response to your guess: “Pico” when your guess has a correct digit in the wrong place, “Fermi” when your guess has a correct digit in the correct place, and “Bagels” if your guess has no correct digits. You have 10 tries to guess the secret number.
I am new in Python. Any suggestions are appreciated:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
for i in range(10):
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
input_dictionary = dict(zip(range(len(input_list)), input_list))
if random_number == input_num:
print("Your answer is correct!!")
break
elif [i for (i, j) in zip(rand_list, input_list) if i == j]:
print("Fermi")
if set(rand_list) & set(input_list):
print("Pico")
elif set(rand_list) & set(input_list):
print("Pico")
else:
print("Bagels")
else:
print("This is not a valid three digit number. Please try again.")
print("The test is finished.")
I don't know if i got what you wanted but try this:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
i = 0
while i < 10:
try:
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
print(input_list)
input_dictionary = dict(zip(range(len(input_list)), input_list))
if input_num == random_number:
print("Your answer is correct!!")
break
elif set(rand_list) & set(input_list):
correct_place = 0
for j in range(0, len(input_list)):
if rand_list[j] == input_list[j]:
correct_place += 1
correct_digits = len(set(rand_list) & set(input_list))
print("Fermi "*correct_place + "Pico "*(correct_digits - correct_place))
else:
print("Bagels")
i += 1
else:
print("This is not a valid three digit number. Please try again.")
except:
print("Not a valid input")
print("The test is finished.")

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

how to connect user input and lists

in my program, I am taking user input (integers 1-9) and having the user keep typing in numbers until they type 0 to exit. once they type 0 I want to print the sum of the integers and then exit. Im new to python so any help would be appreciated. Im getting an invalid syntax error when using the > and < symbol not sure why.
def createList():
myList=[]
return myList
def fillList(myList):
for number in myList:
if number >=1 and <= 9:
number=int(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()
You're only missing a word, try this:
if number >=1 and number <= 9:
So close!
_sum = 0
looping = True
while looping:
num = input("Enter a number (1-9) or 0 to exit.")
if num.isdigit() and 0 <= int(num) <= 9:
_sum += num
if num is 0:
looping = False
print("Sum is", _sum)
if number >=1 and number <= 9:
You need to place the variable on both sides of the and since they are two separate conditions.
Also, since you're initially creating an empty list, you will never get to the part where you get user input. To fix this you should use a while loop.
while number != 0:
The full program might look like this:
def createList():
myList=[]
return myList
def fillList(myList):
number = 5
while number != 0:
if number >=1 and number <= 9:
number=eval(input(" enter a number 1-9, and 0 to quit"))
myList.append(number)
return myList
def printList(myList):
for number in myList:
print ( " the sum is" ,sum(myList))
print(number)
if number ==0:
exit()
def main():
myList = createList()
fillList(myList)
printList(myList)
main()

My 'lowest common multiple' program hangs, and doesn't output an answer

I have been trying to get more into programming, so I've been trying to make a simple program that takes two numbers as input, and computes the lowest common multiple. I did this in Python because I don't know how to take input in Java. What happens now is the program just hangs after I input my numbers, and nothing happens. Any pointers here would be greatly appreciated. Thank you.
#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = 2 #this is the number that the program tried to divide each number by.
#it increases by 1 if it doesn't divide evenly with both numbers.
while True:
if one % counter == 0 and two % counter == 0:
print counter
break
else:
counter += 1
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)
Your logic is a bit off. This line:
if one % counter == 0 and two % counter == 0:
needs to be rewritten like this:
if counter % one == 0 and counter % two == 0:
Also, your function should return counter instead of print it. This has two advantages:
It will keep the script from printing None at the end (the function's default return value).
It allows you to condense these two lines:
print counter
break
into just one:
return counter
Finally, as #FMc noted in a comment, you can improve the efficiency of the function by doing two things:
Starting counter at the smaller of the function's two arguments.
Incrementing counter by this value.
Below is a version of your script that addresses all this:
#LCM Calculator
#Author: Ethan Houston
#Language: Python
#Date: 2013-12-27
#Function: Program takes 2 numbers as input, and finds the lowest number
# that goes into each of them
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = min_inp = min(one, two)
while True:
if counter % one == 0 and counter % two == 0:
return counter
else:
counter += min_inp
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)
Oh, and one more thing. input in Python 2.x evaluates its input as real Python code. Meaning, it is dangerous to use with uncontrolled input.
A better approach is to use raw_input and then explicitly convert the input into integers with int:
first_number = int(raw_input("Enter your first number: "))
second_number = int(raw_input("Enter your second number: "))
Try this:
#!/usr/local/cpython-2.7/bin/python
def lcmCalculator(one, two):
""" takes two numbers as input, computes a number that evenly
divides both numbers """
counter = 2 #this is the number that the program tried to divide each number by.
#it increases by 1 if it doesn't divide evenly with both numbers.
while True:
if counter % one == 0 and counter % two == 0:
break
else:
counter += 1
return counter
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = int(input("Enter your first number: "))
second_number = int(input("Enter your second number: "))
print lcmCalculator(first_number, second_number)
You need to let the loop end if it finds no factor, instead of while True:
def lcmCalculator(one, two):
counter = 2
while counter <= min(one, two):
if one % counter == 0 and two % counter == 0:
return counter
else:
counter += 1
return "No common factor found"
print "\nThis program takes two numbers and computes the LCM of them...\n"
first_number = input("Enter your first number: ")
second_number = input("Enter your second number: ")
print lcmCalculator(first_number, second_number)

Integrating a for loop into an if statement

This is kind of a double-barreled question, but it's got me puzzled. I currently have the following code:
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
Now, I'd like to have some kind of loop (I'm guessing it's a for loop, but I'm not entirely sure) so that after a function has been completed, it'll return to the top, so the user can enter a new function number and do a different equation. How would I do this? I've been trying to think of ways for the past half hour, but nothing's come up.
Try to ignore any messiness in the code... It needs some cleaning up.
It's better to use a while-loop to control the repetition, rather than a for-loop. This way the users aren't limited to a fixed number of repeats, they can continue as long as they want. In order to quit, users enter a value <= 0.
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
while function > 0:
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer = b/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
print 'Enter a value <= 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
You can tweak this (e.g., the termination condition) as needed. For instance you could specify that 0 be the only termination value etc.
An alternative is a loop that runs "forever", and break if a specific function number is provided (in this example 0). Here's a skeleton/sketch of this approach:
function = int(raw_input("Type function no.: "))
while True:
if function == 1:
...
elif function == 2:
...
elif function == 0:
break # terminate the loop.
print 'Enter 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
Note: A for-loop is most appropriate if you are iterating a known/fixed number of times, for instance over a sequence (like a list), or if you want to limit the repeats in some way. In order to give your users more flexibility a while-loop is a better approach here.
You simply need to wrap your entire script inside a loop, for example:
from __future__ import division
import math
for _ in range(10):
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
This will run your if statement 10 times in a row.
I'd try this:
while True:
function = ...
if function == 0:
break
elif ...

Categories

Resources