so I am using Spyder IDE for python. it stopped executing my codes, I have tried to run only a few lines and all together but still no response.
Anyone familiar with these sort of issues?
#Assinging Variables
ProductName = "iPhone"
ProductPrice = 450
Tax = 0.5 #Tax is a constant that cannot be changed
print(ProductTax)
#Dealing with Inputs
name = input("Your Name")
print(name)
print("Hello", name)
city = input("Where do you live?")
print(name, "lives in", city)
#CASTING - converting one data type to another as examples below.
##Note that all the answers required below will be in form of strings
ProductName = input("what is the product Name?")
ProductPrice = float(input("how much is it cost?")) #the string is converted to float
ProductQuantity = int(input("How many?")) #the string is converted to an integer
TotalPrice = ProductQuantity*ProductPrice
print("Total Price: ", TotalPrice)
##SELECTION
## selection is used to choose between 2 or more otions in programming
## if statements is a type of 'selection'
#weather = input("is it raining")
#if weather == "raining":
#print ("Grab an Umbrella")
#else:print("Wear a coat")
it works for me when create a new Console. Hope that works for you.
enter image description here
Related
Basically I'm using Python to pull information off a google spreadsheet.
enter image description here
I have no problem pulling the information I need but when I start to break it down into specific catergories like "goals scored" i get the information but can print it to the terminal with the column headings. Example below:
enter image description here
So basically I want to bring down the above information but also with the column headings:
'player, position, appearances..... etc'
This is what my code looks like to get the information posted above:
data = {
"man united": SHEET.worksheet("man_utd").get_all_values(),
"man city": SHEET.worksheet("man_city").get_all_values(),
"chelsea": SHEET.worksheet('chelsea').get_all_values(),
"liverpool": SHEET.worksheet('liverpool').get_all_values()
}
team_name = ""
position = ""
top_stats = ""
def user_commands():
"""
gives commands the user is able to input to receive different data sets
"""
options = 'Man United, Man City, Liverpool, Chelsea'
print(f"1: {options}")
team_name = input("Please Enter A Team Name:\n").casefold()
print(f"You Have Entered {team_name}\n")
while team_name not in data:
print("You Entered a Wrong Option, Please Enter A Correct Option")
print(f"1: {options}")
team_name = input()
print(tabulate(data[team_name]))
return team_name
def user_commands_2(team_name):
"""
function to see players of a set position
from data received from first input.
Players can be goalkeepers, defenders, midfielders or forwards
"""
options_1 = 'goalkeeper, defender, midfielder,\nforward, home'
print(f"1: {options_1}")
position = input("\nPlease Enter a Position:\n").casefold()
print(f"You Have Entered {position}\n")
while position.casefold() not in (options_1):
print("\nYou Entered a Wrong Option, Please Enter a Correct Option")
print(f"1: {options_1}")
position = input()
if position.casefold() == 'home':
print("Hi! Welcome to a Football Stats Generator")
print("The Available Options Are As Follows:")
main()
res = [i for i in data[team_name] if position.capitalize() in i]
print(tabulate(res))
print("Hi! Welcome To a Football Stats Generator\n")
print("The Available Options Are As Follows:\n")
Any help would be greatly appreciated.
Thanks
Use "get_all_records()" instead of "get_all_values()".
I'm new to python and need help because I have no clue how to space in a print()
lemme show you what I'm working on
#Receipt.py
#Create a program that will prompt the user for an item description, the price of the item, and the quantity purchased.
#The program will output the final cost including all taxes. Your output should look as follows...
#
#Sample Output
#Enter the description: Volleyball
#Enter the price: 39.99
#Enter the quantity: 4
#RECEIPT
#-------------------------------------------------
#Description QTY price Subtotal
#Volleyball 4 $39.99 $159.96
#HST: $20.79
#-------------------------------------------------
#Total: $180.75
#user inputs
def main():
print("Welcome!")
Description = input("What is the name of the item?")
Price = float(input("What is the price?"))
Quantity = float(input("What is the quantity of the item?"))
#variables
Tax = 1.13
#boring math
Total = Price * Quantity * Tax
#what the user has inputted
print( "You have inputted the following")
print("The item is", Description)
print("The price is", Price)
print("The Quantity is", Quantity)
#Asking the user if it is correct
Answer = int(input("Is this want you want? If \"no\" type 1 if \"yes\" type 2")
if Answer = "1":
main()
#ignore the top part lol thaz extra
else:
print("Receipt")
print("--------------------------------------------------------------------------")
print (Description Price Subtotal)
tldr
As you can see I'm trying to make it like this
Sample Output
Enter the description: Volleyball
Enter the price: 39.99
Enter the quantity: 4
RECEIPT
-------------------------------------------------
Description QTY price Subtotal
Volleyball 4 $39.99 $159.96
HST: $20.79
-------------------------------------------------
Total: $180.75
but every time I try it gives me a error
Please use simple things cause I'm just a beginner and don't be to harsh on me lol
If you have any tips list them down below!
Thanks :)
The error seems to be from this line, print (Description Price Subtotal),
you have to separate out arguments to the print function with a ,, so
print (Description, Price, Subtotal) should work. Also please try to include the interpreter outputs when posting errors as they are helpful for debugging. Welcome to StackOverflow!
Your have syntax issues on your print statements. Please check the syntax for printing variables. Also variables need to be separated using commas.
Check out string formatting for Python.
Description = "Volleyball"
Quantity = 4
Price = 39.99
Subtotal = 159.96
name = "bug_spray"
# For newer versions of Python (>=3.6)
# Use f-strings
print(f"{Description} {Quantity} {Price:.2f} {Subtotal:.2f}")
print(f"Hi {name}")
# For older versions of Python
# Use modulo operator
print("%s %d %.2f %.2f" % (Description, Quantity, Price, Subtotal))
print("Hi %s" % name)
# Or use .format() (for Python >= 2.6)
print("{0} {1} {2} {3}".format(Description, Quantity, Price, Subtotal))
print("Hi {0}".format(name))
Also careful of how you indent stuff with if-else statements.
EDIT: I also a syntax error where you wrote if Answer = "1". It should instead look like:
if (Answer == 1):
...
else:
...
I’m finding the Python syntax very confusing, mainly concerning variables. I’m trying to learn it using the Microsoft EDX course but I’m struggling when trying to check if a string from an input is in the variable.
Example 1: Check if a flavor is on the list
# menu variable with 3 flavors
def menu (flavor1, flavor2, flavor3):
flavors = 'cocoa, chocolate, vanilla'
return menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
#print the result
print ("It is", data in menu, "that the flavor is available")
Example 2: Print a message indicating name and price of a car
def car (name, price):
name = input(“Name of the car: “)
price = input (“Price of the car: “)
return (name, price)
print (name, “’s price is”, price)
Also, I would like to know what would be the disadvantage of doing something like this for the example 2:
name = input("name of the car: ")
price = input ("price of the car: ")
print (name,"is", price,"dollars")
Could someone please clarify this to me? Thank you very much!
i didnt understand what your trying to do in first example.
But i can partially understand what your trying to do in second example,
def car ():
name = input("Name of the car: ")
price = input ("Price of the car: ")
return name, price
name,price = car()
print ("{}\'s price is {}".format(name,price))
the above code is the one of the way to solve your problem,
python can return multiple variable
use format function in print statement for clean display.
You dont need function parameters for car. since your taking input from in car function and returning it to the main.
Hope it helps you understand.
Example 1
# menu variable with 3 flavors
def menu():
flavors = 'cocoa, chocolate, vanilla'
return flavors #return flavors instead of menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
# print the result
print ("It is", data in menu(), "that the flavor is available") #menu is a function so invoke with menu () instead of menu
Example 2:
def car(): #no input required since you are getting the input below
name = input('Name of the car: ')
price = input('Price of the car: ')
return (name, price)
name, price = car() #call the function to return the values for name and price
print (name, "’s price is", price)
The below approach works and is faster as compared to calling the function although adding small stuff to form functions allows the program to be modularized, making it easier to debug and reprogram later as well as better understanding for a new programmer working on the piece of code.
name = input("name of the car: ")
price = input("price of the car: ")
print (name, "is", price, "dollars")
Just found how to print the result in the way the exercise required. I had difficulty explaining, but here it is an example showing:
def car(name,price):
name_entry = input("Name car: ")
price_entry = input("Price car: ")
return (name_entry,price_entry)
This is the way to print the input previously obtained
print (car(name_entry,price_entry))
Thank you very much for all the explanations!
I am doing the following dictionary:
import random
from tkinter.messagebox import YES
name = input("Hello, what is your name? ")
print("nice to meet you {}!".format(name))
instruments = (["Bass","Guitar","Piano"])
instruments1 = ({"Name":"Bass","Price":"US$ 900,00"},
{"Name":"Piano","Price":"US$ 1000,00"},
{"Name":"Guitar","Price":"US$ 900,00"})
print("{} we have these instruments for you to buy:".format(name),", ".join(instruments))
#the line above give m all items without the brackets
answer = input("You're going to take some of them? Yes or no.")#waiting the user input
if answer == YES:#boolean command for confirming the yes/no answer.
print("{} which one will be?".format(name))
pos_awnser = input()
print(pos_awnser,"It's a very good choice.")
elif awnser != YES:
print("Sorry, we don't have what you need.")
print(pos_awnser,"costs",)
and I want to display the type of instrument that was chosen previously and display the name and price at the console
Instead of doing it like that, create a single dictionary instead, like this
instruments = ({"Bass":'US$ 900,00',"Guitar":"US$ 1000,00","Piano":"US$ 900,00" })
You can then print the instruments using,
print("{} we have these instruments for you to buy:".format(name),", ".join(instruments.keys())
and display the type of instrument through
print(pos_awnser, instruments[pos_answer], " is a very good choice.")
I've been writing a program as part of a school course and decided to make it a bit more extensive than I needed to. So for the better part of 3 months I've been slowly adding stuff in an attempt to make the system output a file to save that is human readable.
I could save this all under one file as previous programs I've written have but I can only get better if I try. So I have the program take the users family name and date of arrival and use that as the file name. I have the program concatenate these variables (both strings) with ".txt" at the end and save this as a variable I then use to name the file I want to write to. Issue is it spits out the error that "decoding strings is not supported". Just for reference the program is made to get a booking for a hotel-like thing and spit out the price, arrival date, name etc. and just print it but as I've said I'm overambitious. Also I apologise about the bad code, just started to learn this year and a bit. Any help appreciated. Having to run it through Python 3.3.0:
#Comment Format
#
#Code
#
#Comment about above Code
from random import*
c_single = 47
c_double = 90
c_family = 250
discount = 10
VAT = 20
max_stay = 14
min_stay = 1
room_list = []
min_rooms = 1
max_rooms = 4
cost = 0
#Sets all needed variables that would need to be changed if the physical business changes (e.g. Increase in number of rooms, Longer Max stay allowed, Change to Pricing)
print("Cost of room:")
print("Single - £", c_single)
print("Double - £", c_double)
print("Family - £", c_family)
#Prints prices based on above variables
name = input("What is the family name --> ")
arrival = input("Please enter date of arrival in the form dd/mm/yy --> ")
while len(arrival) != 8:
arrival = input("Please re-enter, in the case of the month or day not being 2 digits long insert a 0 before to insure the form dd/mm/yy is followed --> ")
#Gets the guests name and date of arrival for latter update into the business' preferred method of storage for bookings
nights = int(input("How many nights do you intend to stay in weeks --> "))
while nights > max_stay or nights < min_stay:
nights = int(input("That is too short or long, please reneter stay in weeks -->"))
if nights >= 3:
discount_aplic = 1
#Gets the guests ideal number of weeks stay, ensure that this would be possible then adds the discount if applicable
rooms = int(input("Please enter number of rooms required --> "))
while rooms < min_rooms or rooms > max_rooms:
rooms = int(input("That number of rooms is unachievable in one purchase, please re-enter the number of rooms you require --> "))
#Gets number of rooms desired and checks that it does not exceed the maximum allowed by the business or the minimum (currently 1, staying no nights doesn't work)
for room in range (rooms):
current_room = input("Please enter the room desired--> ")
current_room = current_room.upper()
if current_room == "SINGLE":
cost += c_single
elif current_room == "DOUBLE":
cost += c_double
elif current_room == "FAMILY":
cost += c_family
#Checks which room is desired
else:
while current_room != "SINGLE" and current_room != "DOUBLE" and current_room != "FAMILY":
current_room = input("Invalid room type, valid entries are : single, double or family --> ")
current_room = current_room.upper()
#Ensures that the desired room is valid, if first inserted not correctly, repeats until valid entry is entered
room_list.append (current_room)
#Adds the wanted room type to the array room_list
cost = cost * nights
#calculates cost
booking = randrange(1000,9999)
print("Name: ", name)
print("You have booked from ", arrival)
print("You have booked stay for ", nights, "weeks")
print("You have booked", rooms, " room/s of these categories;")
print(str(room_list))
print("This will cost £", cost)
print("Booking referral: ", booking)
#Prints booking information
dateStr = str(arrival)
storageFileName = str(dateStr, name,".txt")
storageFile = open(storageFileName, "w")
storageFile.write("Name: ", name)
storageFile.write("They have booked from ", arrival)
storageFile.write("They have booked stay for ", nights, "weeks")
storageFile.write("They have booked", rooms, " room/s of these categories;")
storageFile.write(str(room_list))
storageFile.write("This has cost them -- >£", cost)
storageFile.write("Booking referral: ", booking)
#saves the storage data to a server under the name and data.
storageFileName = str(dateStr, name,".txt")
Calling str with more than one argument will not convert each argument to a string and combine them. What you're actually doing here is calling str with the parameters str(bytes_or_buffer, encoding, errors). According to the documentation:
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
Since you're specifying encoding and errors, the first argument can't be a string, because a string isn't a data buffer. This explains the error decoding str is not supported.
If you are trying to concatenate strings together, you should use the + operator, or the format method:
storageFileName = dateStr + name + ".txt"
Or
storageFileName = "{}{}.txt".format(dateStr, name)