Python Input and Output? [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I am working on learning python and I for some reason the output I get is always incorrect. Not sure what I'm doing wrong or how to fix it and any help is greatly appreciated:
##a. 3 variables —
## The name of a movie
## The number of tickets to purchase
## The total cost of tickets purchased
##
##b. 1 Constant —
## The cost of a single ticket
##2. Create four print statements that will display the values of the variables and the constant along with labels that describe them
##
#Initialize
movieNm = str("")
numTickets = int(0)
totalTicketPrice = float(0.0)
SINGLE_TICKET = int(10)
#input
name = input("Enter the name of the movie you would like to see:")
numTickets = input("Enter the number of tickets you wish to purchase:")
#process
totalTicketPrice = SINGLE_TICKET * numTickets
#output
print("Feature Film", name)
print("Cost of single ticket", SINGLE_TICKET)
print("Number of Tickets purchased", numTickets)
print("Your Total", SINGLE_TICKET * numTickets)
When you test the code the output is always just so wrong and I'm not sure how to fix it. thanks!

in this line numTickets = input("Enter the number of tickets you wish to purchase:") when you got user input you got string you should convert this input to int like below:
numTickets = int(input("Enter the number of tickets you wish to purchase:"))
see this example maybe help you (this example happen in your code):
print('2'*10)
# 2222222222

Related

I'm trying to multiply inputs using functions and arguments [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I'm new to functions and arguments (actually new to python in general) and I'm having a bit of a problem making this program multiply the unit given by the user and output it. It just keeps coming up as whatever the variable is up top, and if I don't include that it says it isn't defined. May someone help, please?
# Variables
inches = 0
item_length = 0
unit_value = 0
# Your unit (smooots for general purposes) function
def inches_to_smoots(inches):
## inches = item x unit value
inches = item_length * unit_value
## return the number of inches
return inches
## main function
def main():
unit = input("What is the name of your unit? ")
unit_value = input (str("What is the length of your unit in inches? "))
item = input("What is the name of the object you'd like to convert to your unit? ")
item_length = input ("What is the length of your item in inches? ") # Is there a way to print a variable inside an input statement?
answer = inches_to_smoots(item_length)
## print the answer
print(item_length,'inches is', inches, unit, 's!')
## call main
main()
Instead of declaring the variables up at the top, your function should take the necessary inputs as arguments. Since you're doing unit conversion, it's very helpful to give each variable a name that indicates what units it's in! For example, your inches_to_smoots function is presumably (according to its name) supposed to take an inch measurement and return a smoot measurement, but you're returning a value called inches. It would make more sense for one of its arguments to be inches and for it to return something that's in smoots. When your code itself makes sense, you'll find that it's not necessary to comment each individual line to explain it.
Make sure to keep the Python types straight as well -- input() gives you a str, but for any kind of mathematical operation you want values to be int or float.
def inches_to_smoots(inches: float, smoots_per_inch: float) -> float:
smoots = inches * smoots_per_inch
return smoots
def main():
smoot = input("What is the name of your unit? ")
inches_per_smoot = float(input(
f"What is the length of one {smoot} in inches? "
))
item_name = input(
f"What is the name of the object you'd like to convert to {smoot}s? "
)
item_inches = float(input(f"What is the length of your {item_name} in inches? "))
item_smoots = inches_to_smoots(item_inches, 1 / inches_per_smoot)
print(f"{item_inches} inches is {item_smoots} {smoot}s!")
if __name__ == '__main__':
main()
Note that your function inches_to_smoots expects to be told how many smoots are in an inch, but you asked the user for the number of inches in a smoot -- hence you want to take the reciprocal! smoots_per_inch == 1 / inches_per_smoot.
Example output:
What is the name of your unit? finger
What is the length of one finger in inches? 4.5
What is the name of the object you'd like to convert to fingers? hand
What is the length of your hand in inches? 7
7.0 inches is 1.5555555555555554 fingers!
To make math with elements inputed by the user, you need to convert it to int or float using the int() or float() methods.
unit = input("What is the name of your unit? ")
unit_value = int(input (str("What is the length of your unit in inches? ")))
item = int(input("What is the name of the object you'd like to convert to your unit? "))
item_length = int(input ("What is the length of your item in inches? ") # Is there a way to print a variable inside an input statement?)
That is because it is seeing inputs as strings and python does not know how to properly multiply those together.

Add more values in a list at once in Python

I'm a beginner in Python and I'm trying to solve this problem.
I'm trying to write a code where you can put your name and the amount that you want to donate.
The thing is, deppending on the amount of the donation you can have more chances to be the winner.
Eg. If you donate $10 (1 chance), $20(2 chances), $30(3 chances).
My biggest problem is because I can't figure out how to solve this problem when the person insert $30 its name goes to the list 3 times and so on. I tried to use "for..inrange():" but without any sucess. Can someone explain me how to do this?
from random import shuffle
from random import choice
list = []
while True:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
list.append(name)
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 1:
continue
else:
shuffle(list)
winner = choice(list)
break
print('The winner was: {}' .format(winner))
First do not use the name of a built-in type as a (meaningless) variable name. Change list to entry_list.
For the particular problem
compute the quantity of chances;
make a list of the person's name that many times;
extend the entry list with that list of repeated name.
Code:
entry_list = []
while ...
...
chances = int(donation) // 10
entry_list.extend( [name] * chances )
An alternative to adding another loop with additional control flow, you can use list.extend() with a list expression:
num_chances = donation // 10
chances = [name] * num_chances
all_chances.extend(chances)
Note that list is a built-in python identifier, and it's not a good idea to overwrite it. I've used all_chances instead.
Rather than adding extra names to the list to represent the higher chance, you could use the donations as weights in the random.choices function:
from random import choices
names, donations = [], []
while True:
names.append(input('Write your name: '))
donations.append(float(input('Enter the amount you want to donate.: $')))
print(f'You donated ${donations[-1]}. Thank you {names[-1]} for your donation!')
print('=-'*25)
print('[1] YES')
print('[2] NO')
if input('Would you like to make another donation? ') != '1':
break
winner = choices(names, donations)[0]
print(f'The winner was: {winner}')
This allows for non-integer donations to be counted fairly -- e.g. if Bob donates $0.25 and Fred donates $0.50, the drawing will still work in a reasonable way. It also allows very large donations to be handled without tanking the performance of the program -- if you have one list entry per dollar donated, what happens if Elon donates $20B and Jeff donates $30B? (The answer is that your fan spins really fast for a while and then the program crashes because you can't create a list with 50 billion elements -- but this is not a problem if you simply have a list of two elements with large int values.)
Note that shuffle is not necessary if you're using random.choices (or random.choice for that matter) because those functions will already make a random selection from the list.
You can use a for loop to append the name to the list more than one time :
for i in range(donation//10):
list.append(name)
This code should do the job. Please follow good naming conventions as pointed out by others. I have changed the list variable to donations as it is forbidden to use keywords as variables.
I have included the name in donations int(name) // 10 times using the extend function as pointed out by others. You may change the number of times as you wish.
from random import shuffle
from random import choice
donations = []
makeDonation = True
winner = "Unknown"
while makeDonation:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
donations.extend([name for i in range ( int(donation) // 10)])
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 2:
makeDonation = False
shuffle(donations)
winner = choice(donations)
print('The winner was: {}' .format(winner))

Dealing with an error without defining what the correct answer is [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'd like to deal with an input error without defining what the success criteria is i.e. only loop back round the user input turns out to be incorrect. All of the examples I can find require a definition of success.
Rather than list all the possible units as "success" criteria, I'd rather set up the else function to send the user back to the beginning and enter valid units.
I have the following code which uses pint (a scientific unit handling module) which throws and error if a user enters hl_units which is not recognised. This simply kicks the user out of the program on error with a message about what went wrong. I'd like the user to be sent back to re-input if possible.
try:
half_life = float(input("Enter the halflife of the nuclide: "))
hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
full_HL = C_(half_life, hl_units)
except:
print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")
else:
Thanks in advance.
I would use a while loop for that:
input = False
while not input:
try:
half_life = float(input("Enter the halflife of the nuclide: "))
hl_units = input("Half-life units i.e. s, h, d, m, y etc: ")
full_HL = C_(half_life, hl_units)
input = True
except:
print("The half-life input is not recognised, maybe you entered incorrect units, please try again.")
input = False
I hope this works for you :)

How to ask user for number of items and then assign each item a number?

I couldn't find anything online, so I was wondering if someone could help. I have the following code:
x = str(input("Enter number of unique customers then press enter: "))
I want it to then ask the user for a specific number for however many customers the user inputs. For example say the user inputs "2". I want to ask: Number for customer 1? Number for customer 2?
I can't find a way to look at the variable x and use the answer to that to know how many to ask. Thanks!
I think you need loops:
num = int(input('How many customers there are?')
list_customer = []
for i in range(num):
a = input('number for customer x')
list_customer.append(a)
print(list_customer[0]) # Number for customer 1
print(list_customer[1]) # Number for customer 2
I think this is what your trying to do. It takes the number of customers entered. Makes a list, then iterates through that list to get the input for that customer number. and will dump that into a results dataframe
import pandas as pd
results = pd.DataFrame()
x = str(input("Enter number of unique customers then press enter: "))
list_of_cust = list(range(0, int(x)))
for i in list_of_cust:
x2 = str(input("Enter number for customer %d: " %(i+1)))
temp_df = pd.DataFrame([[str(i+1), x2]], columns=['cust_no','value'])
results = results.append(temp_df).reset_index(drop = True)

Python - Can users call variables with only part of its name? [duplicate]

This question already has answers here:
Dynamic variable in Python [duplicate]
(2 answers)
Closed 8 years ago.
What im trying to do is have the user type a number, which would then register into the system as a specific variable.
Example:
n1 = "X"
n2 = "Y"
n3 = "Z"
num = input("enter a number (1-3): ")
print(n(num))
So, if the user entered the number 2 into their program, the program would display the value stored in n2, or be able to use n2 in an equasion.
Is this possible? I'm still new to Python and this is not a school assignment, just my own curiosity :)
Thanks
EDIT:
Here is what im trying to do:
temp = int(input("\nPlayer One, please pick a square (1-9): "))
while {1:n1, 2:n2, 3:n3, 4:n4, 5:n5, 6:n6, 7:n7, 8:n8, 9:n9}[temp] == "X" or {1:n1, 2:n2, 3:n3, 4:n4, 5:n5, 6:n6, 7:n7, 8:n8, 9:n9}[temp] == "O":
temp = str(input("\nPlayer One, please pick a valid square (1-9): "));
{1:n1, 2:n2, 3:n3, 4:n4, 5:n5, 6:n6, 7:n7, 8:n8, 9:n9}[temp] = "X"
You could use a dictionary for this. Like:
num = input("...")
print {1:n1, 2:n2, 3:n3}[num]
Hope that helps.

Categories