Python help. If statement not working? [closed] - python

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 8 years ago.
Improve this question
I am trying to store a high-score in a txt doc and then read it to show it on screen. But when the score that the player got is higherreturning, I would like to change the high-score in the txt file.
I know approximately how to do this but the If statement in my code has a little problem:
It keeps saying False...
Here is the code:
score = 10
highscoreFile = open('Highscore.txt', 'r+')
HS = highscoreFile.read() #the HS is, let's say, 3
highscoreFile.close()
print 'Your score is', score
print 'The High-Score is', HS
if score > HS:
print 'newHS'
newHS = True
highscoreFile = open('Highscore.txt', 'w+')
highscoreFile.write('%s' %(score))
highscoreFile.close()
NOTE: if I put '<' instead for the If statement, it returns True... please explain.

You are comparing int with string.
The line
if score > HS:
should be ,
if score > int(HS):

read reads the entire file, by default. And that will be treated as a string in Python. Quoting from the documentation,
If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object.
So, you have to explicitly convert the string to a number, like this
HS = int(highscoreFile.read())

Related

python: csv.writer - commas between numbers in the output [closed]

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 2 years ago.
Improve this question
i suspect that this is a simple answer, but i cannot figure out the answer. (I did give it due diligence)
i wrote a simple python program to identify prime numbers. the program is function, but i'm receiving strange results in the output. when i have it write a number with multiple digits, each number is comma separated; for example, 13 is added to the document as 1,3. I would like to have a comma after each full number (13,) and don't want commas within the number (1,3 or 1,301). eventually, i want to have each number on its own row (one of the issue that i ran into in my g1 program is that the row became too long around 50mill ;-)
Any thoughts?
#!/bin/python3
import time
import os
import csv
folderLocation = "c:/notNow/"
primeName = "primeNumbers.csv"
# notPrimeName = "noPrimeNumbers.csv"
primePath=folderLocation + primeName
# notPrimePath=folderLocation + notPrimeName
no=13
os.makedirs(folderLocation)
f = open(primePath, "w")
writer = csv.writer(f)
writer.writerow(str(no))
output: 1,3
writerow expects a sequence of items (e.g list). A string is just seen as a sequence of individual characters, try this instead:
writer.writerow([no])

inaccurately reading from file logic error Python [closed]

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 6 years ago.
Improve this question
Hi I have the following text file on which I am using a csv reader:
number,obstacle,location,message
1,gobacktostart,8,Sorry but you've landed on a dangerous number, back to the start for you!
2,movetosquare42,matrix[1][0],The meaning of life is 42 or so they say, and that's where you're headed
I wish to (at the end) retrieve the number 8 from the row that starts 1,gobacktostart,8....etc.
My code is:
def gobacktostart():
with open("obstacles.txt","r") as f:
idnumber="1"
fReader=csv.reader(f)
for row in fReader:
for field in row:
if field==idnumber:
print(row[3])
player1position==row[2]
print(player1position)
and the undesired output however, is:
>>>
Sorry but you've landed on a dangerous number
1
>>>
I do need to read the value into the variable player1position in order to pass it on to another function at a different part of the program.
Any thoughts on solving this logic error? Why is it printing "1", when row[2] refers to the 8. Also, Row[3] seems to execute properly in the previous line....
You are checking for equality not assignment in player position == row[2]

If statement checking if a variable is equal to a specific word is getting invalid syntax [closed]

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
So, I'm trying to make an easter egg in my calculator program, where if you type my friend johns name in, it prints nerd, but I keep getting invalid syntax on the line the if statement starts. here's what the code looks like:
x = input(' ')
if x = John:
print nerd
else:
print x
please keep in mind i'm using python 2.7, not 3. when I googled it, I only got answers that worked in 3.
x = raw_input('enter name ')
if x == 'John':
print 'nerd'
else:
print x
You are doing an assignment, but you need == to check for equality

Why is the While loop creating a syntax error on the next statement [closed]

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 7 years ago.
Improve this question
Hi I've been trying to write a program in python 2.7 that takes a word as its input and outputs the number of letters in a word. At first it was working but something happened and now it keeps returning an error by the first line that is not part of the while loop.
This is a part of the code:
def number_of_letters(input):
nol = input.find(input[-1])
while input[nol:] != input[-1]:
nol = input.find(input[-1], input.find(input[-1] + 1)
nol = nol + 1
print nol
The python interpreter keeps returning a syntax error by whatever I try to put after the while block (in this case 'nol = nol + 1 ')
I've tried playing around with it but nothing worked. PLease help.
By the way if there are any modules that may help with this program that would be great but I'd also like to know why this one isn't working
You are missing a closing paren:
nol = input.find(input[-1], input.find(input[-1] + 1)) #<- add here
If you want to count the number of actual letters you can use str.isalpha:
return sum(ch.isalpha() for ch in inp)
If you don't care what characters are there just use len(inp).
Avoid input as a variable name as it shadows the python function.
Change this
nol = input.find(input[-1], input.find(input[-1] + 1)
to this
nol = input.find(input[-1], input.find(input[-1] + 1))
Notice that parenthesis in the end.
There is a built in function for getting the length of a string in python.
word = "test"
length = len(word)

Why does this if statement not work in this case? [closed]

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 8 years ago.
Improve this question
In this code I ask the user which way they want the text file ordered however, when run the if statement will not work and when run without the if statement it does work. Why will it not work?
way = int(input('Which way would you like the data to be sorted, Alphabetical[1], Ascending[2] Descending[3] or Average[4]'))
classno = str(input('Which class would you like to sort? Please state the entire class name no spaces please with .txt on the end'))
if way=='1':# WORKS with classno but not with if statement
f = open(classno, "r")# omit empty lines and lines containing only whitespace
lines = [line for line in f if line.strip()]
f.close()
lines.sort()# now write the output file
f = open(classno, 'w')
f.writelines(lines) # Write a sequence of strings to a file
f.close()
The other codes which i have not displayed have the same problems and all work without the if statement They all use an if statement no elif ect. if that is any use.
way is an integer, and you're checking for a string, which leads 1 == '1', and that's false.
What you should do is write -
if way == 1:
or remove the int() cast that you're doing on the input, and then you have:
way = input("Message...")
if way == '1':
Change way == '1' to way == 1 so you are checking an int against an int.

Categories