Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hello :) I am new to python. I have been challenged to build a script that simply converts us measurements to metric ones and vise versa. Should be simple but when I run the script I am getting an error
"/home/oily/public_html/script.py
Enter us or international for conversion:us
Traceback (most recent call last):
File "/home/oily/public_html/script.py", line 4, in <module>
begin = input("Enter us or international for conversion:")
File "<string>", line 1, in <module>
NameError: name 'us' is not defined"
Why is python not reconizing the us varible that I have assigned? Is it because of the order? I googled this and I am not finding anything I really understand. Thank you beforehand for any assistance.
SCRIPT------------------
#!/usr/bin/env python
begin = input("Enter us or international for conversion:")
import begin
us = input("Please enter the value in international:")
international = input ("Please enter the value in us:")
def start(begin):
if begin == us:
return us
else:
return international
def conversion():
if us:
return us * 0.0348
elif int:
return int * 3.28084
print(conversion)
Only one function needed, need to change the variable us and international to a float:
begin = input("Enter 'us' or 'international' for conversion:")
def start():
if begin == "us":
us = float(input("Please enter the value in international:"))
print(us * 0.0348)
else:
international = float(input ("Please enter the value in us: "))
print(international * 3.28084)
start()
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
library = ['Harry Potter','Lord of the rings','Lupin']
user_input=input('Choose option: ')
# When adding a book , it is not saved in library, it only prints out what was by default.
How to save books in Library?
if user_input == 'add_book':
x = input('add_book: ')
library.append(x)
elif user_input =='show_books':
for e in library:
print((e),end=' ')
# How to specify which book to remove?
elif user_input =='remove':
library.pop()
Where to place details for each book? Details should appear when book is selected.
This code resolves the problems you stated in your comments, the following points explain the changes.
library = ['Harry Potter','Lord of the rings','Lupin']
while True:
user_input = input('\n Choose option: ')
if user_input == 'add_book':
to_add = input('add_book: ')
library.append(to_add)
elif user_input =='show_books':
for e in library:
print((e),end=' ')
elif user_input =='remove_book':
to_remove = input("remove_book: ")
library.remove(to_remove)
elif user_input == 'quit':
break
else:
print("Available options: add_book, show_books, remove_book, quit")
While True lets your entire algorithm start again until user_input == 'quit', when the break command tells the program to exit the While True loop, ending the program. This was necessary to solve the problem you described of the program not saving changes: the reason was your program ended after your first input, and when you start the program again, it only runs its source code, so it couldn't show any "changes" to variables you made using it previously. Now until you type quit it "saves" every change you make.
I used library.remove() because it accepts the library key value as an argument. library.pop() required the index instead. (Now you just need to enter the item (book) name.
( I couldn't implement the last function you described)
Where to place details for each book? Details should appear when book is selected.
You didn't describe the concept of "selecting" a book and what are the "details" of one.
Hope I've been of some help.
I've figured out how to implement logic for displaying details about selected book.
elif user_input == 'book_details':
which_book = input('Which book: ')
if which_book == 'Harry Potter':
print('\n''Author: J. K. Rowling')
print('ISBN: 9780747532743')
print('Year of release: 1997')
if which_book == 'Lupin':
print('\n''Author: Maurice Leblanc')
print('ISBN: 9780141929828')
print('Year of release: 1907')
if which_book == 'Lord of the rings':
print('\n''Author: J. R. R. Tolkien')
print('ISBN: 9788845292613')
print('Year of release: 1954')
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to use an dictionary with b and c like in the code such that when I give input o, then I receive 1 as an result with o.
science_dictionary = {"O": 1, "H": 2}
print("Hey welcome to the chemical reactor")
import time
time.sleep(2)
print("\n")
print("In this chemical reactor you can receive the product of any two "
"elements")
b = input("Please enter your first element element in short forms : ").upper().strip()
c = input("Please enter your second element element: ").upper().strip()
time.sleep(1)
print("Calculating")
time.sleep(2)
print(f"{b}{c}")
You can access dictionary items by using the dictionary name with the specific key you want. I.e. science_dictionary['O'] will return 1. You can also pass in variable names as keys, for example science_dictionary[b] would be matched with the input (if the input is either O or H).
I'm not sure what's your purpose; but i think that if you want to try a make a product using the keys in the dictionary with the inputs [key name] , that would be like this:
import time
science_dictionary = {"O": 1, "H": 2}
print("Hey welcome to the chemical reactor")
time.sleep(2)
print("\n")
print("In this chemical reactor you can receive the product of any two elements")
b = input("Please enter your first element element in short forms : ").upper()
c = input("Please enter your second element element: ").upper()
time.sleep(1)
print("Calculating")
time.sleep(2)
print("{}".format(science_dictionary[b] * science_dictionary[c]))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For my class we have been instructed to execute the following:
"Create a program called ph.py that determines the acidity or basicity of a solution. It should ask the user to enter a numeric pH value. It should then call a function that accepts the value as a parameter and returns a string indicating that the solution is acidic (pH less than 7), basic (pH greater than 7), or neutral (pH is 7); it should return "invalid" if the value is greater than 14 or less than zero*. Finally, your script should then output the returned string for the user to see."
This is what I was able to come up with:
def water_ph() -> object:
ph: int = int(input("Enter the numeric value for your water: "))
if ph >= 14 or ph <= 0:
return f"{ph} invalid"
elif ph < 7:
return f"{ph} is acidic"
elif ph > 7:
return f"{ph} is basic"
elif ph == 7:
return f"{ph} is neutral"
ph = water_ph()
print(ph)
Does this look correct? it works I'm just worried I'm not answering the above question correctly.
call a function that accepts the value as a parameter
def water_ph()
I do not see any arguments in your function declaration.
returns a string
def water_ph() -> object:
Then why are you declaring the function to return an object ?
ask the user to enter a numeric pH value. It should then call a function
You are first calling the function and then asking the user for input iside this function.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
im trying to have an input in every line of the displayed data.
here are the codes
def attendance():
print ("\n\nList of Students\n")
print ("StudNo StudName Age Course Attendance")
for idx in range(len(studNo)):
print (" {0:15} {1:10s} {2:10s} {3:10s}".format(studNo[idx],
studName[idx], Age[idx], Course[idx]))
and this is the output
List of Students
StudNo StudName Age Course Attendance
a1001 Daryl 21 CS
a1002 Akex 21 CS
a1003 John 24 CS
a1004 Jose 22 CS
im creating a simple attendance monitoring system. so im trying to have an input for each line so i can write A for absent or P for present.
You can use the input function. input("Write your prompt here") will print the prompt and ask the user to write an entry of text. This can get messy with your desired output, so I suggest collecting all attendance information and then printing
students = ['Kathy','Will','Nayeon']
attendanceRecord = []
for student in students:
attendance = input("What is "+student+"\'s attendance? ")
attendanceRecord.append(attendance)
print("\n") # add a space before printing student list
print("Name"+" Attendace")
for i in range(len(students)):
print(students[i] + " "+ attendanceRecord[i])
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm a newcomer to programming so i apologize for my lack of technical ability.
I'm trying to create a qrcode generator in python, however, when i try to increment the number on the filename save, i get this error.
Traceback (most recent call last):
File "/home/sam/Desktop/QR Code Gen/run.py", line 52, in <module>
purchase_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 32, in purchase_code_fn
qr_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 41, in qr_code_fn
im.save("filename"+ count + ".png")
AttributeError: 'function' object has no attribute 'save'
>>>
Is there anyway to rectify this?
(see below for my full code - it's still a WIP)
from qrcode import *
import csv
import time
active_csv = csv.writer(open("active_codes.csv", "wb"))
void_csv = csv.writer(open("void_codes.csv", "wb"))
active_csv.writerow([
('product_id'),
('code_id'),
('customer_name'),
('customer_email'),
('date_purchased'),
('date_expiry')])
void_csv.writerow([
('code_id'),
('customer_email'),
('date_expiry')])
count = 0
def purchase_code_fn():
global count
count =+ 1
customer_email = raw_input("Please enter your email: ")
product_id = raw_input("Which product would you like (1 - 5): ")
qr_code_fn()
def qr_code_fn():
qr = QRCode(version=5, error_correction=ERROR_CORRECT_M)
qr.add_data("asaasasa")
qr.make() # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image
im.save("filename"+ count + ".png")
def restart_fn():
restart_prompt = raw_input("Would you like to purchase another code? : ").lower()
if restart_prompt == "yes" or restart_prompt == "y":
purchase_code_fn()
elif restart_prompt =="n" or restart_prompt == "no":
print("exit")
purchase_code_fn()
The error is here : im = qr.make_image. You are storing into im the function make_image of object qr. As you can store functions in variables in Python, this is a valid syntax.
So, you are not calling the function make_image, just storing it. It should be im = qr.make_image().
After you'll implement T. Claverie answer - it is likely that you'll fail in .save() as you are concating string and integer.
Can you try to change the following line:
im.save("filename"+ count + ".png")
to be:
im.save("filename"+ str(count) + ".png")