Using User Input to control parameters in a Random number Generator - python

I am attempting to write a program that generates random numbers, asks how big you want it, between 1-4 for example, then I want it to ask how many numbers you want and finally ask you if you want to run it again. I am attempting to grasp the concepts of recursion and type casting, just trying to learn the concepts of Object Orientated Design with Python. I tried to glean from what I have read so far on the Learn Python Hard Way site.
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)
# Here I am attempting to define the variables I need to convert keyboard input to int
size = raw_input()
intsize = # unsure of how to define this variable
intsize = int(size)
print "How many Digits?",
size = raw_input()
print "How many Times?".
times = raw_input()
# I want to construct a method here that sends my size input to random_with_N_digits(n)
# I need a method that runs the random_with_N_digits according to the input.
# while True:
reply = input('Enter text:')
if reply == 'stop':
break
if reply = times # not sure what to put here
print( def random_with_N_digits)
else:
# I want to tell the my method to run as many as much as 'times' is equal to
print "Again?"
answerMe = raw_input()
# here I want to have a if answerMe = Enter run the method again
print random_with_N_digits()

try this code
from random import randint
def random_with_N_digits(n):
s = int(raw_input("starting from.. "))
e = int(raw_input("upto... "))
l = ""
for i in range(0,n):
l= l +str( randint(s,e))
print int(l)
again = raw_input("print again?")
if again == "yes":
how_many =int(raw_input("how many digits?"))
random_with_N_digits(how_many)
how_many =int(raw_input("how many digits?"))
random_with_N_digits(how_many)

Related

Calling function to new function in Python

I have tried this several different ways, I am still fairly new to Python so go easy on me. I am trying to execute a script where the user can choose to import a list from a plaintext file, or input a list manually, and the script will return the median and mode of the data.
The problem I am having is that my median and mode functions are not recognizing the reference to the raw data, and the main function isn't recognizing the median and mode from their respective functions.
I guess it's safe to say I am not calling these functions correctly, but frankly I just dont know how. Any help here would be much appreciated.
def choice():
##Choose user input type
start = input("Please select your input method by typing 'file' or 'manual' in all lower-case letters: ")
# Import File Type
userData = []
if start == "file":
fileName = input("Please enter the file name with the file's extension, e.g. ' numbers.txt': ")
userData = open(fileName).read().splitlines()
return userData
userData.close()
# Manual Entry Type
elif start == "manual":
while True:
data = float(input("Please enter your manual data one item at a time, press enter twice to continue: "))
if data == "":
break
userData = data
return userData
# Error
else:
print("You have entered incorrectly, please restart program")
def median(medianData):
numbers = []
for line in (choice(userData)):
listData = line.split()
for word in listData:
numbers.append(float(word))
# Sort the list and print the number at its midpoint
numbers.sort()
midpoint = len(numbers) // 2
print("The median is", end=" ")
if len(numbers) % 2 == 1:
medianData = (numbers[midpoint])
return medianData
else:
medianData = ((numbers[midpoint] + numbers[midpoint - 1]) / 2)
return medianData
def mode(modeData):
words = []
for line in (choice(userData)):
wordsInLine = line.split()
for word in wordsInLine:
words.append(word.upper())
theDictionary = {}
for word in words:
number = theDictionary.get(word, None)
if number == None:
theDictionary[word] = 1
else:
theDictionary[word] = number + 1
theMaximum = max(theDictionary.values())
for key in theDictionary:
if theDictionary[key] == theMaximum:
theMaximum = modeData
break
return modeData
def main():
print("The median is", (median(medianData)))
print("The mode is", (mode(modeData)))
Welcome! I think you need to read up a bit more on how functions work. The argument when you define a function is a "dummy" local variable whose name matters only in the definition of a function. You need to supply it a variable or constant whose name makes sense where you use it. It is a very good analogy to functions in mathematics which you may have learned about in school. (Note that these points are not specific to python, although the detailed syntax is.)
So when you have def median(medianData) you need to use medianData in the definition of the function, not userData, and when you call median(somevar) you have to make sure that somevar has a value at that point in your program.
As a simpler example:
def doubleMyVariable(x):
return 2*x
How would you use this? You could just put this somewhere in your code:
print(doubleMyVariable(3))
which should print out 6.
Or this:
z = 12
y = doubleMyVariable(z)
print(y)
which will print 12.
You could even do
z = 36
x = doubleMyVariable(z)
which will assign 72 to the variable x. But do you see how I used x there? It has nothing to do with the x in the definition of the function.

How to use options like 1, 2, 3 etc. in Python for implementing different code?

I'm new to stack overflow and Python too. I'm currently coding in Python 3.8.2 on https://www.repl.it.
I am making a math solver which solves things using certain formulas, I have print functions, input functions and variables which are also integers.
What I want to do is that the user will be greeted, then the user will be prompted to choose a certain option (ex. 1, 2, 3, etc.) and each option would be a formula/method.
I have written code for just one formula as of now, but this concept which I'm solving has multiple different formulas.
Have a look at my code below:
print("Hello, welcome to the \nA.P. SOLVER!")
import click
if click.confirm("Do you want to start?", default=True):
print("Ok! Let's start!")
a = input('Type the value of "a" [the first term of the A.P.] ')
d = input('Type the value of "d" [the common difference of the A.P.] ')
n = input('Type the value of "n" [the nth term of the A.P.] ')
print(f"Finding the {n}'th/nd' term...")
a = int(a)
d = int(d)
n = int(n)
x = a + (n-1)*d
print(x)
Please help me out, would be appreciated :)
what I've understood from your question is that you want to make a menu driven program that asks what you want to do. What you can do is take the value (here action) which will decide in the switch() what will happen with it.
import click
def switch(action):
if action==1:
a = int(input('Type the value of "a" [the first term of the A.P.]'))
d = int(input('Type the value of "d" [the common difference of the A.P.]'))
n = int(input('Type the value of "n" [the nth term of the A.P.] '))
print(f"Finding the {n}'th/nd' term...")
x = a + (n-1)*d
print(x)
else:
a=int(input("Number 1 :"))
b=int(input("Number 2 :"))
print("Subtraction :",a-b)
if click.confirm("Do you want to start?", default=True):
print("Ok! Let's start!")
print("1) AP")
print("2) Sub")
action=int(input(":"))
if action not in [1,2]:
print("Invalid")
else:
switch(action)
If you want it to go on until the user wants to quit you can write before the 1) AP part a while loop which will go on until the user enters lets say 3) Exit which will break that while loop.

Try and Except with a list and multiple inputs

I am making a D&D style character generator and I am rolling the stats for them and allowing them to allocate them to the ability score they want. I would like to have the ability to start at the same stat they were at vs the entire section over again.
Here is what I have
from random import randint
def char_stats():
# roll 4 D6s drop the lowest number and add the highest 3
s1,s2,s3,s4,s5,s6 = ([],[],[],[],[],[])
for x in range(4):
s1.append(randint(1,6))
s2.append(randint(1,6))
s3.append(randint(1,6))
s4.append(randint(1,6))
s5.append(randint(1,6))
s6.append(randint(1,6))
stat1 = sorted(s1)
stat2 = sorted(s2)
stat3 = sorted(s3)
stat4 = sorted(s4)
stat5 = sorted(s5)
stat6 = sorted(s6)
return sum(stat1[1:]),sum(stat2[1:]),sum(stat3[1:]),sum(stat4[1:]),sum(stat5[1:]),sum(stat6[1:])
a = list(char_stats())
print "Please choose one of the following for your stat: {}".format(a)
while len(a) > 0:
try:
Strength = int(raw_input('Please input one of these stats for your Strength:\n'))
if Strength in a:
a.remove(Strength)
print a
Wisdom = int(raw_input('Please input one of these stats for your Wisdom:\n'))
if Wisdom in a:
a.remove(Wisdom)
print a
Intelligence = int(raw_input('Please input one of these stats for your Intelligence:\n'))
if Intelligence in a:
a.remove(Intelligence)
print a
Constitution = int(raw_input('Please input one of these stats for your Constitution:\n'))
if Strength in a:
a.remove(Constitution)
print a
Dexterity = int(raw_input('Please input one of these stats for your Dexterity:\n'))
if Dexterity in a:
a.remove(Dexterity)
print a
Charisma = int(raw_input('Please input one of these stats for your Charisma:\n'))
if Charisma in a:
a.remove(Charisma)
except ValueError:
print "Incorrect Input"
continue
I have tried nesting each of the if statements (which I believe is very bad form) and have similar results. I have also tried grouping all the inputs into the try and not the calculations and have gotten the same results. Any advice?
You need to use the "loop until valid" logic for both the format (int) of the input, and the value (is it in the list of rolled stats?). The basic logic is this:
while True:
# get input
# check input
# if input is valid,
# break
In your case, this looks something like
while True:
user = input("Please enter a stat to use")
if user.isnumeric():
stat_choice = int(user)
if stat_choice in a:
break
Now, to make effective use of this, you need to parametrize your six stats and put those into a loop:
stat_name = ["Strength", "Wisdom", ...]
player_stat = [0, 0, 0, 0, 0, 0]
for stat_num in range(len(player_stat)):
while True:
user = input("Please input one of these stats for your" + \
stat_name[stat_num] + ": ")
# Validate input as above
player_stat[stat_num] = stat_choice
Note that you can similarly shorten your char_stats routine to a few lines.
Does that get you moving?
You have at least one function in your code (char_stats) so I feel like you know how to do functions.
This is a great place to use a function.
My suggestion, for this code, would be to write a function that incorporates the try/except, the asking of the question, and the checking against the stats list.
Something like this:
def pick_a_stat(stats, prompt):
"""Prompt the user to pick one of the values in the `stats` list,
and return the chosen value. Keep prompting until a valid entry
is made.
"""
pass # Your code goes here.

How do I improve my code for Think Python, Exercise 7.4 eval and loop

The task:
Write a function called eval_loop that iteratively prompts the user, takes the resulting input and evaluates it using eval(), and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it evaluated.
My code:
import math
def eval_loop(m,n,i):
n = raw_input('I am the calculator and please type: ')
m = raw_input('enter done if you would like to quit! ')
i = 0
while (m!='done' and i>=0):
print eval(n)
eval_loop(m,n,i)
i += 1
break;
eval_loop('','1+2',0)
My code cannot return the value of the last expression it evaluated!
Three comments:
Using recursion for this means that you will eventually hit the system recursion limit, iteration is probably a better approach (and the one you were asked to take!);
If you want to return the result of eval, you will need to assign it; and
I have no idea what i is for in your code, but it doesn't seem to be helping anything.
With those in mind, a brief outline:
def eval_loop():
result = None
while True:
ui = raw_input("Enter a command (or 'done' to quit): ")
if ui.lower() == "done":
break
result = eval(ui)
print result
return result
For a more robust function, consider wrapping eval in a try and dealing with any errors stemming from it sensibly.
import math
def eval_loop():
while True:
x=input('Enter the expression to evaluate: ')
if x=='done':
break
else:
y=eval(x)
print(y)
print(y)
eval_loop()
This is the code I came up with. As a start wrote it using the If,else conditionals to understand the flow of code. Then wrote it using the while loop
import math
#using the eval function
"""eval("") takes a string as a variable and evaluates it
Using (If,else) Conditionals"""
def eval_(n):
m=int(n)
print("\nInput n = ",m)
x=eval('\nmath.pow(m,2)')
print("\nEvaluated value is = ", x)
def run():
n= input("\nEnter the value of n = ")
if n=='done' or n=='Done':
print("\nexiting program")
return
else:
eval_(n)
run() # recalling the function to create a loop
run()
Now Performing the same using a While Loop
"using eval("") function using while loop"
def eval_1():
while True:
n=input("\nenter the value of n = ") #takes a str as input
if n=="done" or n=="Done": #using string to break the loop
break
m=int(n) # Since we're using eval to peform a math function.
print("\n\nInput n = ",m)
x=eval('\nmath.pow(m,2)') #Using m to perform the math
print("\nEvaluated value is " ,x)
eval_1()
This method will run the eval on what a user input first, then adds that input to a new variable called b.
When the word "done" is input by the user, then it will print the newly created variable b - exactly as requested by the exercise.
def eval_loop():
while True:
a = input("enter a:\n")
if a == "done":
print(eval(b)) # if "done" is entered, this line will print variable "b" (see comment below)
break
print(eval(a))
b = a # this adds the last evaluated to a new variable "b"
eval_loop()
import math
b = []
def eval_loop():
a = input('Enter something to eval:')
if a != 'done':
print(eval(a))
b.append(eval(a))
eval_loop()
elif a == 'done':
print(*b)
eval_loop()

how do i randomly pick characters out of a list the amount of times the user asks for using input in python?

For my assignment i have to create a password generator using python. it has to ask the user how many characters long they want the password, then it has to create it by using random.randint and prints it out as a string. how do i get the user input to multiply the random.randint bit the number of times they've asked for??
this is what i have so far...........
# imports modules
import random, time
# defines welcome function
def welcome():
print('Welcome to the password generator!')
time.sleep(2)
print('This program will generate random passwords.')
# create a list
character_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']
# defines enter number function which asks the user to enter a number
def password_gen():
i = 'Nothing yet'
while i.isdigit() == False:
i = input()
if i.isdigit() == False:
print('Please enter a number\n')
return int(i)
for x in range(0,5):
rc = character_list[random.randint(0,62)]
print (rc)
# calls functions and runs the program
welcome()
print('Please press enter...')
password_gen()
This is very nearly there...
for x in range(0,5):
rc = character_list[random.randint(0,62)]
print (rc)
Change to a list-comp to build a single list of n items, eg:
rc = [character_list[random.randint(0,62)] for _ in xrange(5)]
However, it's easier to use choice then generate an index into the list - then do as you're doing now but repeated...
from random import choice
from string import ascii_letters, digits
chars = ascii_letters + digits
# replace 10 with how many....
passwd = ''.join(choice(chars) for _ in xrange(10))
# create a list
character_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']
import random
pas = list() # random password
number = input() # 8
number = int(number) if number.isdigit() else 0
while(number):
pas.append(random.choice(character_list))
number -= nu
result = "".join(pas)
print(result)
# 'jjyMQPuK'

Categories