Using Astericks to Display a Bargraph of User Inputted Numbers in Python - python

I am currently attempting to solve a homework problem. The problem states to collect user inputted numbers and then arrange them using asterisks to display a graph, with the largest number having forty asterisks and the rest becoming smaller as the numbers decrease.
_NumberList= []
print("Please type 'quit' to stop entering numbers.")
print("Please type 'print' to view the list that has been entered so far.")
a= True
while a:
_number= input("Please enter a number or make a selection. ")
if _number.isdigit():
_number=int(_number)
_NumberList.append(_number)
elif _number.isalpha():
_number= _number.lower()
if _number== 'quit':
a= False
if _number== 'print':
print(_NumberList)
else:
print("Please use digits to enter a number.")
print("For exmaple: 'ten' should be typed at '10'")
else:
print("Invalid entry.")
_NumberList.remove(max(_NumberList))
for i in range(len(_NumberList)):
_NumberList.remove(max(_NumberList))
However, I am unsure as to how to find the given proportions utilizing the numerical data. Thus far, I have considered utilizing the .pop function, but it simply isn't making a ton of sense so far. I considered making them go up by one step, but again, that doesn't seem logical, and the program can run for more than forty numbers. I know I will need to utilize a loop, hence the for loop at the end, but I'm not sure as to how to continue from there.

Your variable name _NumberList makes my eyes hurt, so I'll call it number_list
largest_number = max(number_list)
scale_factor = 40 / largest_number
scaled_number_list = [int(x * scale_factor) for x in number_list]
for scaled_number in scaled_number_list:
print('*' * scaled_number)

Related

How to divide variable from input by two

On line 7 and 14 I cant figure out how to divide the variable.
import keyboard
import random
def main(Number, Start):
Number = random.randrange(1,100)
Start = False
QA = input('Press "K" key to begin')
if keyboard.is_pressed('K'):
Start = True
input('I"m thinking of a random number and I want that number divisible by two')
print(Number)
input('Please divide this by two. *IF IT IS NOT POSSIBLE RESTART GAME*\n')
if QA == int(Number) / 2:
print('.')
else:
print('.')
main(Number=' ' ,Start=' ')
What you probably want:
Pick a random number
Make user divide this number by two (?)
Do something based on whether the guess is correct
What is wrong with your code:
You are not picking a number divisible by two. The easiest way to ensure that your number is, indeed, divisible by two, is by picking a random number and then multiplying it by two: my_number = 2 * random.randrange(1, 50). Note the change in the range. Also note that the upper limit is not inclusive, which may be not what your meant here. A typical check for divisibility by N is using a modulo operator: my_number % N == 0. If you want users to actually handle odd numbers differently, you would need to write a separate branch for that.
input returns a string. In your case, QA = input('Press "K" key to begin') returns "K" IF user has actually done that or random gibberish otherwise. Then you are checking a completely unrelated state by calling keyboard.is_pressed: what you are meant to do here is to check whether the user has entered K (if QA == "K") or, if you just want to continue as soon as K is pressed, use keyboard.wait('k'). I would recommend sticking to input for now though. Note that lowercase/uppercase letters are not interchangeable in all cases and you probably do not want users to be forced into pressing Shift+k (as far as I can tell, not the case with the keyboard package).
input('I"m thinking of does not return anything. You probably want print there, possibly with f-strings to print that prompt along with your random number.
input('Please divide this by two. does not return anything, either. And you definitely want to store that somewhere or at least immediately evaluate against your expected result.
There is no logic to handle the results any differently.
Your function does not really need any arguments as it is written. Start is not doing anything, either.
Variable naming goes against most of the conventions I've seen. It is not a big problem now, but it will become one should you need help with longer and more complex code.
Amended version:
import random
import keyboard
def my_guessing_game():
my_number = random.randrange(1, 50) * 2
# game_started = False
print('Press "K" to begin')
keyboard.wait('k')
# game_started = True
print(f"I'm thinking of a number and I want you to divide that number by two. My number is {my_number}")
user_guess = input('Please divide it by two: ')
if int(user_guess) == my_number / 2:
# handle a correct guess here
print('Correct!')
pass
else:
# handle an incorrect guess here
pass
Alternatively, you can use the modulo operator % to test whether Number is divisible by 2:
if Number % 2 == 0:
print('.')
else:
print('.')
This will check whether the remainder of Number divided by 2 is equal to 0, which indicates that Number is divisible by 2.

Passing variables defined inside of one function into another

Context:
I'm sure this has been asked elsewhere, but the topics I'm finding thus far are more advanced than what I'm doing and only confusing me further. I am a student in an intro to Python course, and am working on a "Lottery Number" assignment. Basically, randomly generate a 7-digit lottery number and print it back out.
That much I get, but I am trying to approach this from a less literal perspective and a more practical one. As in, I want the user to define how many numbers they need and which numbers to choose from. From there, I want the program to generate random numbers that fit the criteria they set.
My instructor wants everything done inside of functions, so I am trying to attempt the following:
What I'm doing:
main() Function - everything inside of here.
get_info() to collect the data from the user, number of digits (MaxDigits), range minimum (MinChoice), range maximum (MaxChoice).
lottery_pick() take the variables and do the lottery thing with them.
I have it "working", but I can only do so if I have lottery_pick() function run inside of the get_info() function. I imagine there has to be a way to define these variables independently, and just pass the variables from get_info() to lottery_pick().
import random
# Define the main function
def main():
get_info()
exit_prompt()
def get_info():
# Set Variables to 0
MaxDigits = 0
# Let the user know what we are doing
print("Let's choose your lottery numbers!")
print("First, How many numbers do you need for this lottery?")
# Request the user input the number of lottery numbers we need
while True:
try:
MaxDigits = int(input('Please enter how many numbers you need to choose: '))
if MaxDigits > 0:
break;
else:
print('Please enter an integer for how many numbers are being drawn. ')
except:
continue
print('Next, we need to know the smallest and largest numbers allowed to choose from')
# Request user input smallest number in range of numbers to pick from.
while True:
try:
MinChoice = int(input('Please enter the lowest number you are allowed to choose from: '))
if MinChoice >= 0:
break;
else: print ('Please enter an integer, 0 or greater for the smallest number to pick from.')
except:
continue
# Request user input largest number in range of numbers to pick from.
while True:
try:
MaxChoice = int(input('Please enter the largest number you are allowed to choose from: '))
if MaxChoice >= 0:
break;
else: print ('Please enter an integer, 0 or greater for the greatest number to pick from.')
except:
continue
# Define the function to actually assemble the lottery number
def lottery_pick(lot_digits, lot_min, lot_max):
numbers = [0] * lot_digits
for index in range(lot_digits):
numbers[index] = random.randint (lot_min, lot_max)
print('Here are your lottery numbers!:')
print(numbers)
# Execute the function - I've not yet figured out how to pass the variables from the get_info
# function to the lottery_pick function without lottery_pick being inside of get_info.
lottery_pick(MaxDigits, MinChoice, MaxChoice)
def exit_prompt():
while True:
try:
# use lower method to convert all strings input to lower-case. This method
# allows user to input their answer in any case or combination of cases.
ExitPrompt = str.lower(input('Would you like to generate another lottery number? Please enter "yes" or "no" '))
if ExitPrompt == 'yes':
main()
elif ExitPrompt =='no':
print('Goodbye!')
exit()
# If an answer other than yes or no is input, prompt the user again to choose to re-run or to exit
# until an acceptable answer is provided.
else:
print('Please enter "yes" to generate another lottery number, or "no" to exit. ')
except:
continue
main()

Creating a loop and calculating the average at the end

I have an assignment as follows
Write a program that repeatedly asks the user to enter a number, either float or integer until a value -88 is entered. The program should then output the average of the numbers entered with two decimal places. Please note that -88 should not be counted as it is the value entered to terminate the loop
I have gotten the program to ask a number repeatedly and terminate the loop with -99 but I'm struggling to get it to accept integer numbers (1.1 etc) and calculate the average of the numbers entered.
the question is actually quite straightforward, i'm posting my solution. However, please show us your work as well so that we could help you better. Generally, fro beginners, you could use the Python built-in data types and functions to perform the task. And you should probably google more about list in python.
def ave_all_num():
conti = True
total = []
while conti:
n = input('Input value\n')
try:
n = float(n)
except:
raise ValueError('Enter values {} is not integer or float'.format(n))
if n == -88:
break
total.append(n)
return round(sum(total)/len(total),2)
rslt = ave_all_num()
Try the following python code. =)
flag = True
lst=[]
while(flag):
num = float(raw_input("Enter a number. "))
lst+=[num]
if(num==-88.0): flag = False
print "Average of numbers: ", round( (sum(lst[:-1])/len(lst[:-1])) , 2)
enter code hereThank you for the prompt replies. Apologies. This is the code i was working on:
`#Assignment2, Question 3
numbers=[]
while True:
num=int(input("Enter any number:"))
if num==float:
continue
if num==-88:
break
return print(" the average of the numbers entered are:",sum(numbers)/len(numbers)`

Collatz Function: Strange try/except Bugs

So I'm getting into coding and I was doing an exercise from the Automate the Boring Stuff book. I figured out how to write the original function, but then I wanted to try to add a little more to it and see if I could fit it all in one function.
So in Python 3.6.2, this code works fine if I enter strings, positive integers, nothing, or entering "quit". However, if I enter 1 at any point between the others then try "quitting", it doesn't quit until I enter "quit" as many times as I previously entered 1. (like I have to cancel them out).
If I enter 0 or any int < 0, I get a different problem where if I then try to "quit" it prints 0, then "Enter a POSITIVE integer!".
Can't post pics since I just joined, but heres a link: https://imgur.com/a/n4nI7
I couldn't find anything about this specific issue on similar posts and I'm not too worried about this working the way it is, but I'm really curious about what exactly the computer is doing.
Can someone explain this to me?
def collatz():
number = input('Enter a positive integer: ')
try:
while number != 1:
number = int(number) #If value is not int in next lines, execpt.
if number <= 0:
print('I said to enter a POSITIVE integer!')
collatz()
if number == 1:
print('How about another number?')
collatz()
elif number % 2 == 0: #Checks if even number
number = number // 2
print(number)
else: #For odd numbers
number = number * 3 + 1
print(number)
print('Cool, huh? Try another, or type "quit" to exit.')
collatz()
except:
if str(number) == 'quit':
quit
else:
print('Enter an INTEGER!')
collatz()
collatz()

Construct a game so that two random numbers appear and the user has to choose which one is bigger

AIM: Construct a game so that two random numbers appear and the user has to choose which one is bigger
This is what I have but I don't know how to make it so the code can realise if the user has guessed the bigger number or not.
#Ask the user to input his/her name in which will be used in the
#opening comments about the game and how to play it
user_name=str(input("Please type in your name: "))
#print instructions
print('''Hello {}! Welcome!
This game is going to develop your number skills!
So here is how to play:
Firstly, {}, we are going to give you two numbers.
Then you must choose which of these numbers you think is the biggest.
Type this number in and we will tell you if you are right.
Get enough right and you can progress TO THE NEXT LEVEL!!!''' .format(user_name, user_name))
#RUN MODULE TO CHECK IF THE TEXT IS BEING PRINTED AND THE USERS NAME IS BEING SHOWN IN SPACE OF THE {}
#level 1
#import a random number
import random
a1 = random.randint(1, 10)
a2 = random.randint(1, 10)
#Making sure the integers are not the same
while a1 == a2:
a2 = random.randint(1, 10)
print('''
The two random values are {} and {}.
Which one do you think is bigger? ''' .format(a1, a2))
#RUN MODULE TO CHECK IF THE IF TWO NUMBERS ARE BEING PRODUCED AND ARE DIFFERENT, MAKING SURE THESE PRINT THROUGH THE THE PRINT STATEMENT.
The simplest thing you can do is ask for the value of the biggest number, and compare it to the biggest number:
biggest = max(a1, a2)
user_num = int(input("What is the biggest number?"))
if user_num == biggest:
print('Correct!')
else:
print('Wrong! The biggest number is {}'.format(biggest))
Note the use of int() for converting the input to integer before testing for equality.
The question you are asking your user is to choose one of two possible outcomes (bigger of smaller). You could say enter 1 if the first number is bigger than the second return if not.
k=raw_input("Enter 1 if first number bigger, else return: ")
the question is a choice between two outcomes.
You can alter your question slightly to generate a 1 or a zero using the random function then ask; Is a mystery number I have chosen a 1 or a zero enter 1 or 0
# do this code
a = raw_input()
# gets user input
if a1 > a2:
if a == a1:
print ('you got it right')
break
# all the ifs check if it is right or wrong
if a != a1:
print ('you got it wrong try again')
a = raw_input()
# then right this same code again but change if a1 > a2: do if a2 > a1: sorry if it does not work

Categories

Resources