Can you define a variable inside an if statement? [closed] - python

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 8 years ago.
Improve this question
I am trying to create a variable inside an if statement but it won't allow it. Is there any other way to do what I'm trying?
print ('Type numbers 1 or 2')
c = int(input())
if c == 1:
answer = (90) #so the variable "answer" will be set to '90' if the user types "1"
if c == 2:
answer = (50)
print (answer)

The code will run in the expected way if either 1 or 2 are entered as input. But if user inputs another number, you will get an Exception:
NameError: name 'answer' is not defined
To avoid this, you could declare the variable answer before the if statements:
answer = 0 # or a reasonable number
if c == 1:
answer = 90
# ...
Note: The () in answer = (90) are not necessary since it's a single number.

You need to allow the possibility that your input() might be out of your preconceived options:
c = int(input("Type no. 1 or 2: "))
if c==1:
answer=90
print(answer)
elif c==2:
answer =50
print(answer)
else:
print("you input neither 1 nor 2")
Here's a more compact solution using assert:
c = int(input("Type no. 1 or 2: "))
assert c in [1,2], "You input neither 1 nor 2."
answer = 90 if c == 1 else 50
print(answer)

Related

Program calculating sum, min, max values of user input [closed]

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
As the title says, I have created a program that does the following until the user presses the 'X' key. Which then stops and prints out all values in order. I also would like to mention that I can only use a specific compiler through my university, which registers the program as an error/wrong even though it should be correct.
Edit: Added the Status of the compiler.
My question is, what other alternatives can I use to code a similar program, or any recommendations in general.
The requested input:
1
2
X
The requested output:
result:[1, 2]
average:1.50
min:1.00
max:2.00
list1 = []
asknumber = str(0)
while asknumber != 'X':
asknumber = input("Enter number: ")
if asknumber == 'X':
break
list1.append(int(asknumber))
big_value = max(list1)
min_value = min(list1)
average = sum(list1) / len(list1)
print("result:", sorted(list1))
print("average:", f'{average:.2f}')
print("min:", f'{min_value:.2f}')
print("max:", f'{big_value:.2f}')
Since a computer is grading your work, the error is likely because you have spaces after your colons.
Someone suggested to use the following to resolve that issue:
print("result:", sorted(list1), sep='')
However, since you are already using f strings in your print statement, you might as well use them for all of it.
You also do not need to calculate the min, max, and average until the loop ends—and since you break the loop manually, you can just use while True:.
list1 = []
asknumber = str(0)
while True:
asknumber = input("Enter number: ")
if asknumber == 'X':
break
list1.append(int(asknumber))
big_value = max(list1)
min_value = min(list1)
average = sum(list1) / len(list1)
print(f'result:{sorted(list1)}')
print(f'average:{average:.2f}')
print(f'min:{min_value:.2f}')
print(f'max:{big_value:.2f}')

How to replace items in a list? [closed]

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 1 year ago.
Improve this question
Please help me.
I am a noob and the code does not run. The input should be a number which indicates the index where the 0 turns to an 1.
board2 =[0,0,0,0,0,0,0,0,0]
inp = input('Input Number 0-8:')
if inp == int():
a = inp
for i in board2:
board2.replace(i[a],1)
return board2
You can check if the value input is both an int and if it is in range that you described.
Then you can use the index to replace the value in board2 to 1.
Also, the input() function defaults to string.
board2 =[0,0,0,0,0,0,0,0,0]
inp = input('Input Number 0-8:')
if 0 <= int(inp) < len(board2):
board2[int(inp)] = 1
print(board2)
Almost there! you don't really need to use "replace" here; you can just modify the element which resides at the index provided directly. The only criteria you would need to consider is that the number is greater than zero AND within the range of the "board2" list provided.
board2 =[0,0,0,0,0,0,0,0,0]
inp = input('Input Number 0-8:')
if (0 < int(inp) < len(board2)):
board2[int(inp)] = 1
print(*board2)
This code snippet should solve your question:
board2 = [0,0,0,0,0,0,0,0,0]
index = int(input('Input Number 0-8:'))
if index in range(len(board2)):
board2[index] = 1
print(board2)

I wanted to print something when given two numbers gives remainder 0 in python. The following code is to demonstrate what I want but it didn't worked [closed]

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
A = '4'
B = '2'
while True:
if A % B == 0:
print("True")
It'll not gonna work as A and B are of string data-type. You can't just evaluate the % operator on string values you need to convert the values in suitable data types 1st.
A = '4'
B = '2'
while True:
if int(A) % int(B) == 0:
print("True")
The variables A and B should be integers.
By declaring them in this way A = '4' declares them as strings.
But without the single inverted-commas, the variable is declared as an integer, like A = 4.
Use double equals sign for checking, single equals will assign the RHS value to LSH:
So, the code would be:
A= 4
B = 2
if A % B == 0:
print("True")

Can't get my program to continue properly until true [closed]

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 6 years ago.
Improve this question
Since you are not liking my explanation of my program I have changed it purely to only a question now:
how do I allow the program to continue to check what the input was and apply a rule according until the output is mu
x = input("Enter your string: ")
while not set(x).issubset({'m', 'u', 'i'}):
print("false")
x = input("Enter your string")
print("Your String is " + x)
if x == ("mu"):
print("game complete")
quit()
#I understand that right now I am only checking if x is mu and then
#displaying the question input
#not sure how to bring the rules into the loop too
else:
while x !=("mu"):
Question = int(input("Which rule would you like to apply? enter numbers 1-4: ")
if Question is 1:
x = (x + "l")
print(x)
elif Question is 2:
print("2")
elif Question is 3:
print("3")
elif Question is 4:
print("4")
elif Question is not 1 or 2 or 3 or 4:
print("invalid rule try again")
You bring the rules into the while-loop by indenting them accordingly:
while x != "mu":
Question = int(input("Which rule would you like to apply? enter numbers 1-4: ")
if Question == 1:
x = (x + "l")
print(x)
elif Question == 2:
print("2")
elif Question == 3:
print("3")
elif Question == 4:
print("4")
else:
print("invalid rule try again")
By the way: don't us is to compare numbers. Your last elif-condition is wrong, should be Question not in (1, 2, 3, 4) or even better a simple else.

python program will not continue [closed]

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 9 years ago.
Improve this question
i am writing a program about coin flips i want the user to enter number and for the program to flip a coin that many times.
once the user gives number the program stops
this is what i have
import random
flips = 0
heads=0
tails=0
numFlips = raw_input("Flips ")
while flips < numFlips:
flips += 1
coin = random.randint(1, 2)
if coin == 1:
print('Heads')
heads+=1
if coin == 2:
print ('Tails')
tails+=1
total = flips
print(total)
print tails
print heads
numFlips is a str. You have to convert it to an int first.
numFlips = int(raw_input("Flips "))
Otherwise, your check flips < numFlips will not work, since all ints are 'less than' any string.
(Also, you want to add some error-handling for the case the user enters something other than an integer)
On line
numFlips = raw_input("Flips ")
raw_input() reads a string : http://docs.python.org/2/library/functions.html#raw_input
Convert it to integer by doing int(raw_input("Flips "))
You can also use input() evaluates the string to a python expression, which in this case would evaluate to an int.
EDIT: As pointed out by #bruno desthuilliers, it is unsafe to use input() and should rather just convert the raw_input() to int.

Categories

Resources