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.
Related
total = 0
for i in range(5):
question = int(input("Enter a number : "))
included = input("Do you want that number included , (y/n) : ")
if included == "Y" or included == "y" :
total = total + question
print(total)
This is my code and I was trying to get each number from the question variable and add them to the total if the user writes y in the second variable which is included , but when i print total , it should add the numbers together, but the output shows the last number that the user wrote
if could someone tells me the answer to my question, how I can get each number from the input in the loop, to add them together
Well that's very simple. I've tested you program, and you just messed up the tabs.
total = 0
for i in range(5):
question = int(input("Enter a number : "))
included = input("Do you want that number included , (y/n) : ")
if included == "Y" or included == "y" : # over here
total = total + question
print(total)
You see when you type anything, while loop, for loop, if statement or anything which end's with column ":", you should add tabs before each line of code which is related to loop or statement.
Example:
if name == 'John': <----------------------------------------------------,
print('Your name is John') <------------, |
^.________ over here we have 4 spaces so this is related to statement here
this way "print" function will work only when statement is true (if name is john).
I hope I explained it easy enough, if you still have some trouble with it, look at this tutorials here
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
Hi I have a python code which does the following things sequentially
Displays a list of urls
asks the user if they want to remove
any links.
If the user inputs yes then takes an input which link
to remove and removes the link
code exits.
My issue is I want the code to ask the user again after removing the link if they want to remove more links?
Can someone help me figure it out. Sorry I am new to python so if this question seems very trivial.
My code:
import sys
def remove_links():
# initializing list
list = links
# initializing string
str_to_remove = input("Enter the link you want to remove: ")
# Remove List elements containing String character
# Using list comprehension
links.remove(str_to_remove)
# printing result
print("The list after removal : " + str(links))
print(len(links))
# printing original list
print("The list of links are : " + str(links))
print(len(links))
# Sets to simplify if/else in determining correct answers.
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
# Convert their input to lowercase.
choice = input("Do you want to remove some/any links? (y/N) ").lower()
if choice in yesChoice:
remove_links()
elif choice in noChoice:
# exit the code
sys.exit("User doesn't want to make any modifications.")
else:
# print("Invalid input.\nExiting.")
sys.exit("Invalid input.\nExiting.")
You can put it in while loop, like this and reaplace sys.exit() to break:
while True:
choice = input("Do you want to remove some/any links? (y/N)").lower()
if choice in yesChoice:
remove_links()
elif choice in noChoice:
print("User doesn't want to make any modifications.")
break
else:
print("Invalid input.\nExiting.")
break
This is only one way to do this
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
This question already has answers here:
How to read keyboard input?
(5 answers)
Closed 6 years ago.
I am working on a python project and I have got the following questions.
How to catch a character in python ? What modules I need to use ? What functions I need to use?
If you need to take a line of input just use:
x = input('Your name: ')
y = input()
Or (For Python 2)
x = raw_input('Your name: ')
y = raw_input()
For taking just one character from the keyboard you can use msvcrt.getch():
import msvcrt
key = msvcrt.getch()
if key == 'a':
print("You pressed a")
This question already has answers here:
TypeError: 'dict_keys' object does not support indexing
(5 answers)
Closed 7 years ago.
So,
I am using Python 3.4.2 and I have this code:
import csv
import random
filename = input("Please enter the name of your file: ")
# Open file and read rows 0 and 1 into dictionary.
capital_of = dict(csv.reader(open(filename)))
# Randomly select a country from the dictionary
choice = random.choice(capital_of.keys())
# The correct capital corresponds to the dictionary entry for the country
answer = capital_of[choice]
# Take a guess from the user
guess = input("What is the capital of %s? " % choice)
# If it's right, let the user know
if guess == answer:
print("Right-o!")
# Otherwise, do what you want to do.
This code was given to me as a solution on a previous question but upon entering the name of my CSV file, I get this error:
TypeError: 'dict_keys' object does not support indexing
Does anybody know a fix for this?
Thanks
Try this:
choice = random.choice(list(capital_of.keys()))