TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
requestedTickets = ticketsWanted(userName)
def calculateCost():
ticketQuantity = requestedTickets
totalCost = ticketQuantity * TICKETPRICE
return totalCost
costOfTickets = calculateCost()
def confirm():
global requestedTickets
global costOfTickets
tickets = requestedTickets
totalCost = calculateCost()
print("Okay so that will be " + str(tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/N) : ")
while confirmationResponse == "n":
requestedTickets = ticketsWanted(userName)
costOfTickets = calculateCost()
print("Okay so that will be " + str(requestedTickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/N) : ")
confirm()
def finalStage():
print("Your order is being processed.")
finalStage()
This is a simple program that:
Asks a user how many tickets they want
Calculates the cost of the tickets
Then asks if it's okay to go ahead with the purchase
How could I change the way I'm doing things to not have to overwrite the requestedTickets and costOfTickets global variables?
(they're being overwritten in the confirm function, if a user replies with an "n" declining the confirmation of purchase.)
I'm trying to learn best practices.
TICKETPRICE = 10
ticketsRemaining = 100
userName = input("What is your first name?: ")
print("There are " + str(ticketsRemaining) + " tickets remaining.")
def ticketsWanted(userName):
numOfTicketsWanted = input(
"Hey {} how many tickets would you like? : ".format(userName))
return int(numOfTicketsWanted)
def calculateCost(n_tickets):
totalCost = n_tickets * TICKETPRICE
return totalCost
def confirm(userName):
n_tickets = ticketsWanted(userName)
totalCost = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(totalCost))
confirmationResponse = input("Is this okay? (Y/n) : ")
while confirmationResponse == "n":
n_tickets = ticketsWanted(userName)
costOfTickets = calculateCost(n_tickets)
print("Okay so that will be " + str(n_tickets) +
" tickets making your total " + str(costOfTickets))
confirmationResponse = input("Is this okay? (Y/n) : ")
def finalStage():
print("Your order is being processed.")
confirm(userName)
finalStage()
Related
I'm new to python and am trying to fix this and By defualt its running the else statment I don't understand and need help. I'm new so please dumb your answers down to my -5 iq
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
if "" > menu:
order = input("What Would you like? \n ")
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
else:
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
I changed the if "" to on_menu and list the options but it didn't work, and I asked people on discord.
menu = ["Baguette" , "Crossiant" , "Coffee" , "Tea" , "Cappuccino "]
count = 0
for item in menu:
print(str(count) +" -> "+str(item))
count += 1
order = int(input("\n What Would you like? \n "))
if order > len(menu) or order < 0 or order == "" or not menu[order]:
print("Sorry Thats not on the menu")
quit()
orderCount = int(input("How many " + menu[order] + " would you like?"))
print("Your " + str(orderCount) + " " + menu[order] + " will be ready soon!\n\n\n")
amount = int(4) * int(orderCount)
print("Thank you, your total is: $" + str(amount))
print("Your " + str(amount) + " of " + str(menu[order]) + " is ready!")
print("Please enjoy you " + str(menu[order]) + "!")
print("Please come again!")
Currently you are not checking the user input, you are just checking for a False statement based on what you defined. You need to check if the user input is on the menu, else quit the program.
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
name = input("What your name? \n ")
order = input("What Would you like? \n ")
if not order.lower() in menu.lower(): # checking if user input is in the menu
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#input name
name = input("What is your name?\n")
#create menu
menu = "Baguette, Crossiant, Coffee, Tea and Cappuccino"
#display menu
print(menu)
#input order
order = input("What would you like?\n")
#if the order item is in the menu
if order in menu:
#input quantity
amount = input("How many " + order + "s would you like? ")
#display message
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
#setting price of all items to 4
price = 4
#calculating total
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#if the item is not in menu
else:
#display message
print("Sorry Thats not on the menu")
Hope this helps! I have added the explanation as comments.
I was wondering about a specific problem I was having while writing a program. The program is very simple. Ask for some info about the person with some input functions, and then compile the information into one paragraph, summarizing some info about the person.
Here's some code (I'll explain after):
def main():
userName = input("What's your name?")
userAge = input("How old are you?")
userNumber = input("What's your favorite number?")
userAnimal = input("What's your favorite animal?")
print("Hi, my name is" + userName + "and I'm" + userAge + ".")
print("My favorite number is" + userNumber + "and my favorite animal is" + userAnimal + ".")
main()
Python keeps asking me to indent the line "userName = input("What's your name?")", so I did that. But when I do that, the line just flat out disappears from when I run it.
You meant to write :
def main():
userName = input("What's your name?")
userAge = input("How old are you?")
userNumber = input("What's your favorite number?")
userAnimal = input("What's your favorite animal?")
print("Hi, my name is : " + userName + " and I'm " + userAge + ".")
print("My favorite number is : " + userNumber + " and my favorite animal is " + userAnimal + ".")
main()
You have to indent the content of the main function.
def main():
userName = input("What's your name?")
userAge = input("How old are you?")
userNumber = input("What's your favorite number?")
userAnimal = input("What's your favorite animal?")
print("Hi, my name is" + userName + "and I'm" + userAge + ".")
print("My favorite number is" + userNumber + "and my favorite animal is" + userAnimal + ".")
main()
If the students.txt file was like this:
michael jackson:
Civil id: 102931023
Gender: male
In the show_student() function I knew only how to check if the student is in the file or not, but I couldn't access the student information.
How can I access to it?
Code
import csv
import sys
import pathlib
file_path = pathlib.Path("students.txt")
if file_path.exists():
pass
else:
file = open("students.txt", "a+")
def login():
username = input("Username: ")
password = input("Password: ")
if username == "a" and password == "b":
menu()
else:
print("Please try again.")
login()
def menu():
print("*" * 20 + " Main Menu " + "*" * 20)
print(" " * 20 + "A: Register student" + " " * 20)
print(" " * 20 + "B: Show students" + " " * 20)
print(" " * 20 + "C: Show specific student" + " " * 20)
print(" " * 20 + "D: Quit" + " " * 20)
print("*" * 20 + " Main Menu " + "*" * 20)
operation = input("Enter operation: ")
if operation.strip().lower() == "a":
register_student()
elif operation.strip().lower() == "b":
show_students()
elif operation.strip().lower() == "c":
show_student()
elif operation.strip().lower() == "d":
sys.exit()
else:
print("Invalid operation.")
menu()
def register_student():
student_civil_id = input("Student id: ")
student_first = input("Student first name: ")
student_last = input("Student last name: ")
student_gender = input("Student gender: ")
student_full = student_first + " " + student_last
with open("students.txt", "a+") as studentInfo:
info = [student_full + ": " + "\n Civil id: " + student_civil_id + "\n Gender: " + student_gender]
studentInfo.write("\n" + student_full + ": " + "\n Civil id: "
+ student_civil_id + "\n Gender: " + student_gender)
print("Student has been registered.")
def show_students():
with open("students.txt") as studentInfo:
print(studentInfo.read())
def show_student():
student_name = input("Student name: ")
with open("students.txt") as studentInfo:
if student_name.strip().lower() in studentInfo.read():
print("Student exists.")
else:
print("Student not exists.")
login()
I guess, you have many students in students.txt file as:
michael jackson:
Civil id: 102931023
Gender: male
james smith:
Civil id: 165468798
Gender: male
With this file, you can find the index of the specific student, split the text starting from that index, and take the first 3 items from the returned list. At the end, you can use join() function while printing.
def show_student():
student_name = input("Student name: ")
with open("students.txt") as f:
text = f.read()
student_position = text.find(student_name.strip().lower())
if student_position != -1:
info = "\n".join(text[student_position:].split("\n")[:3])
print("Student information:")
print(info)
else:
print("Student does not exists.")
use a regular expression to match the block of information
import re
form = r'{}:\nCivil id: \d+\nGender: [a-z]+'
def show_student():
student_name = input("Student name: ")
with open("students.txt") as studentInfo:
name = student_name.strip().lower()
pat = re.compile(form.format(name), re.MULTILINE)
try:
print(pat.findall(studentInfo.read())[0])
except:
print("Student does not exist.")
You could change your def to something like:
def show_student():
student_name = input("Student name: ")
with open("students.txt") as studentInfo:
studentData = studentInfo.readLines()
if len(studentData) > 0 and student_name.strip().lower() in studentData[0]:
print(*studentData[1:])
else:
print("Student not exists.")
To make your life easier, you might want to look into creating structured data using json, xml, csv or something similar. How do you know that michael jackson: is a name?
This is my entire code block but I am just having trouble making the scores show after the game is played. The score is being added to the file correctly, but when I go to print the scores, the new score is not appearing, even though I have appended it. How can I fix my code to make it show up? I am new to coding so anything helps. I think this is an easily solvable error, but I don't know how to fix it. Thank you!
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
#Define functions for future use
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
#Determine if user needs to create a new account:
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see leaderboard:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK!")
#If they type the wrong username or password:
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
#Check to see if username already exists
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print(print_in_green + "Ok, please continue!" + print_default)
#Check to see if two passwords match
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again: ")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print(print_in_red + "Your passwords do not match. Please try again." + print_default)
login_user()
#Playing the game (rolling dice):
import random
min = 1
max = 6
sum = 0
#Ask user if they want to play
game_response = input("Would you like to play the game by rolling your dice (y/n)? ")
if game_response == "y":
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dices...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(print_in_pink)
print(int(dice1))
print(int(dice2))
print(print_default)
score = (int(dice1) + int(dice2))
sum = sum + score
roll_again = input("Your score for this round is " + str(score) + ". Roll the dices again (y/n)? ")
else:
print("Ok!")
print("Your final score is " + print_in_pink + str(sum) + print_default + "!")
add_file_contents(scoreslist_path, '\n' + str(sum))
scoreslist.append(str(sum))
leaderboard_again = input("Would you like to view the leaderboard again (y/n)? ")
if leaderboard_again == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for logging in!")
You never update scoreslist to have sum in it (either by appending it or by reading scoreslist out of the file again). Add a line that adds sum to scoreslist:
add_file_contents(scoreslist_path, '\n' + str(sum))
scoresline.append(sum)
I have to write a program for my Computer Logic class, and I can't figure out why this won't run. The error I keep getting is IndentationError: expected an indented block (<string>, line 3) Can someone please point me in the right direction? If there are any mistakes you find, please let me know. This code has to be able to run properly. Thanks.
while True:
cname = 'My Company'
drate = .17
maxhrs = 40
pdate = "9/1/2015"
orate = 1.5
lc = 'Y'
while(lc == 'Y'):
ename = raw_input("Enter employee's name.")
dcode = raw_input("Enter department code.(1 - Shipping 2 - Mngmt.)")
hworked = float(raw_input("Enter total hours worked."))
prate = float(raw_input("Enter your pay rate."))
inscost = float(raw_input("Enter the cost of insurance."))
city = float(raw_input("Enter your city code.(1 - Sumiton 2 - Hamilton)"))
st = raw_input("Enter your state")
sex = raw_input("Enter your sex.(M - Male F - Female)")
yrsemp = raw_input("Enter total years employed.")
print("Welcome to our company: ", cname)
print("Pay period date: ", pdate)
if(sex == 'M'):
sexword = 'Male'
else:
sexword = 'Female'
print("Employee name: ", ename, "Sex: ", sexword)
if(city == '1'):
cityn = 'Sumiton'
else:
cityn = 'Hamilton'
print("City: ", cityn, "State: ", state)
if(dcode == '1'):
dname = 'Shipping'
else:
dname = 'Management'
print("Department name: ", dname)
rpay = maxhrs * prate
print("Regular pay: ", rpay)
opay = [(maxhrs - hworked) * orate] * prate
print("Overtime pay: ", opay)
gross = rpay + opay
print("Gross before deduction: ", gross)
damt = drate * gross
print("Deduction amount: ", damt "Insurance cost: ", inscost)
npay = gross - (damt + icost)
print("Net pay: ", npay)
new = raw_input("Would you like to start over with a new person? yes/no")
if(new = 'yes')
restart = int(input("Press 1 to try again, 0 to exit. "))
if(restart == '1'):
continue
elif(restart == '0'):
break
else:
print("Invalid input. Please enter 1 to restart or 0 to exit.")
`
Your code is missing indentation after the first while. You need to indent the statements that will run within this loop, also do the same with the second while you have on line 9.
In Python, after a colon must indent(recommend 4 space). So the indent should be like this:
while True:
cname = 'My Company'
drate = .17
maxhrs = 40
pdate = "9/1/2015"
orate = 1.5
lc = 'Y'
while(lc == 'Y'):
ename = raw_input("Enter employee's name.")
dcode = raw_input("Enter department code.(1 - Shipping 2 - Mngmt.)")
hworked = float(raw_input("Enter total hours worked."))
prate = float(raw_input("Enter your pay rate."))
inscost = float(raw_input("Enter the cost of insurance."))
city = float(raw_input("Enter your city code.(1 - Sumiton 2 - Hamilton)"))
st = raw_input("Enter your state")
sex = raw_input("Enter your sex.(M - Male F - Female)")
yrsemp = raw_input("Enter total years employed.")
print("Welcome to our company: ", cname)
print("Pay period date: ", pdate)
if(sex == 'M'):
sexword = 'Male'
else:
sexword = 'Female'
print("Employee name: ", ename, "Sex: ", sexword)
if(city == '1'):
cityn = 'Sumiton'
else:
cityn = 'Hamilton'
print("City: ", cityn, "State: ", state)
if(dcode == '1'):
dname = 'Shipping'
else:
dname = 'Management'
print("Department name: ", dname)
rpay = maxhrs * prate
print("Regular pay: ", rpay)
opay = [(maxhrs - hworked) * orate] * prate
print("Overtime pay: ", opay)
gross = rpay + opay
print("Gross before deduction: ", gross)
damt = drate * gross
print("Deduction amount: ", damt "Insurance cost: ", inscost)
npay = gross - (damt + icost)
print("Net pay: ", npay)
new = raw_input("Would you like to start over with a new person? yes/no")
if(new = 'yes')
restart = int(input("Press 1 to try again, 0 to exit. "))
if(restart == '1'):
continue
elif(restart == '0'):
break
else:
print("Invalid input. Please enter 1 to restart or 0 to exit.")
(by the way, your code has a lot of problems...I can't even understand this is Python 3 or Python 2...)