I am very new to Python (literally just started learning last week). My group got an assignment to code a program to compute system that calculate total price with several conditions. But we are stuck because the user input returns as string but we need it to link with the variable. And also we aren't allowed to use IF, ELSE method and everyone is new to this so we are at dead end. Please help :')
This is what we have coded in the last hour.
min_price=30
oak_type=15
pine_type=0
black=0
white=0
gold_leaf=15
print("Welcome to Mark Daniels Carpenting Service!")
import random
order_num=random.randint(1000,1999)
print("\nYour order number is", (order_num))
cust_name=input("Enter name:")
print("Type of wood available:")
print("1 oak_type \n2 pine_type")
wood_type=input("Enter choice of wood:")
And when we tried to total up the price it comes up as error because the wood_type returns as string while the other data returns as integer.
How to make input from wood_type link to oak_type or pine_type value?
wood_type=input("Enter choice of wood:")
You can use wood_type=int(input("Enter choice of wood:"))
Use integer_x = int(input("Enter... ")) for integer and float_x = float(input("Enter... ")) for float.
You can add the type of your input at the beginning of your input syntax.
So for your case, it will be :
wood_type = int(input("Enter choice of wood:"))
Related
I know I’m missing something with this code. Can someone please help me? I’m new to coding and I’ve struggling with this all day. I don’t want to keep emailing my instructor so maybe I can get help from here. I’m trying to get it to run through the if statements with user input and then calculate the amount but I don’t know what I’m missing.enter image description here
You should post code you're asking about as text in your question.
Going over your code with some comments:
print("Welcome") # no issue here, although Python default is single quotes, so 'Welcome'
print = input("Please enter company name:")
After that last line, print is a variable that has been assigned whatever text was entered by the user. (even if that text consists of digits, it's still going to be a text)
A command like print("You total cost is:") will no longer work at this point, because print is no longer the name of a function, since you redefined it.
num = input("Please enter number of fiber cables requested:")
This is OK, but again, num has a text value. '123' is not the same as 123. You need to convert text into numbers to work with numbers, using something like int(num) or float(num).
print("You total cost is:")
The line is fine, but won't work, since you redefined print.
if num > 500:
cost = .5
This won't work until you turn num into a number, for example:
if int(num) > 500:
...
Or:
num = int(num)
if num > 500:
...
Also, note that the default indentation depth for Python is 4 spaces. You would do well to start using that yourself. Your code will work if you don't, but others you have to work with (including future you) will thank you for using standards.
Finally:
print = ("Total cost:, num")
Not sure what you're trying to do here. But assiging to print doesn't print anything. And the value you're assigning is just the string 'Total cost:, num'. If you want to include the value of a variable in a string, you could use an f-string:
print(f"Total cost: {num}")
Or print them like this:
print("Total cost:", num) # there will be a space between printed values
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))
I'm trying to create a game that is kind of along the lines of the game mastermind.
I have a section where the user has to either guess the number or type "exit" to stop the game. How do i make it so that the code allows both an integer and string input?
The code is:
PlayerNum = int(input("Type your number in here:"))
if PlayerNum == "exit":
print "The number was:",RandNum1,RandNum2,RandNum3,RandNum4
print "Thanks for playing!
exit()
If anyone could help that would be great.
Thanks. :D
you can use isdigit() function to check whether input is int or string.
Let user has input "32" then "32".isdigit() will return True but if user has input "exit" then "exit".isdigit() will return False.
player_input = input("enter the number")
if player_input.isdigit():
# Do stuff for integer
else:
# Do stuff for string
PlayerNum = input("Type your number in here:")
Well You can remove the int so that it takes both integet and string as input
Integer and String classifications are specific to Python (they are functions). When the user types in their response, that would be interpreted by the system as stdin (standard input).
Once the stdin is entered by the user and allocated under the PlayerNum variable, you are free to convert it to an int/str/bytes as you please.
I am relatively new to python, and I just started learning how to use classes. This is the first program I've made where I've tried to integrate them, but I'm coming up with a small issue I can't seem to fix, and I think it has to do with lists. The code is as follows:
(The topic is getting the user to choose what type of seat to purchase).
class SeatBooking:
def __init__(self, seat):
self.seat = seat
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
while True:
if self.seat not in possible_types:
print("Sorry, but this is not a valid answer. Please try again!")
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("You have chosen to book a {} ticket.".format(self.seat))
confirmation = str(input("Please confirm with 'Yes' or 'No': ")).lower()
if confirmation == "yes":
print("Excellent decision! Ready to continue")
print("=" * 170)
break
elif confirmation == "no":
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("That doesn't seem to be a valid answer.")
Here is the main file (to execute the different classes I'll make):
import type_seat
# Choose the seat to book
print("=" * 170)
print("Welcome to Etihad! This program can help you organize your flight, payments and usage of miles!")
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
seat_type = str(input("What type of ticket would you like? The possible types are: {}. "
.format(possible_types)))
type_seat.SeatBooking(seat_type)
The problem I have is that I seem to be able to enter certain letters and it doesn't count them as an error even though they're not one of the available seats. For example, when I enter the letters "h" or "s", my error checking part of the code doesn't respond to it, but when I enter the letter "b" or random words like "try" it does. It doesn't seem to be completely random though, and it seems to only happen with letters or parts of the first 3 'items' in the possible_types[] list. However, I haven't tested this fully. This is why I thought it had something to do with lists, so if anyone knows what's causing this, I'd really appreciate it if they could help me resolve this and perhaps help me from repeating this mistake in the future!
Note, for the lists I am using .join, but I also tried str().
You don't have a list, you are testing characters against one long string:
possible_types = " ".join(possible_types)
The letters h and s are in that string (in the words High_Economy and Business, respectively), but the sequence try doesn't appear anywhere in the string.
If you only wanted to allow whole words to match, you'd need to leave possbile_types a list, or ideally convert it to a set (as sets allow for fast membership testing). You can define the list, no need for list.extend() here:
possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"]
or make it a set by using {...}:
possible_types = {"Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"}
Do not join this into a string, just test directly against the object:
if self.seat not in possible_types:
If you still need to show the values to a user in an error message, join the values then, or store the str.join() result in a different variable for that purpose.
Note that you shouldn't deal with user input validation in the class __init__ method. Leave user interaction to a separate piece of code, and create instances of your class after you validated. That way you can easily swap out user interfaces without having to adjust all your data objects too.
possible_types = " ".join(possible_types)
Above statement will create one string as "Low_Economy Standard_Economy High_Economy Business First Residence".
Now you are doing
if self.seat not in possible_types:
This will check for a particular character in the string present or not. In your case you are finding 'h' which is present and 'try' which isn't.
Your program will work if you remove this statement
possible_types = " ".join(possible_types)
Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.
If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.
Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))
In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response