python3.7 - NameError: name 'paul' is not defined using - python-3.x

tekst = input("Enter your word: ")
for i in len(tekst):
if tekst(i) == tekst(-i):
print(tekst + " is a palindrome word")
else:
print( tekst + " is not a palindrome word")
Having some trouble with the input, I am using python 3.7.

you are using () instead of [] to access the string characters.
tekst(i) would mean that you are calling a function named tekst and passing i to it, where as tekst[i] is used to address specific element in array.
so this
if tekst(i) == tekst(-i):
should be
if tekst[i] == tekst[-i]:
another way to check for palindrome is
if (tekst == tekst[::-1]):

You just messed up the syntax. The subscript operator is [], which is used to access any element in a list or a string.
tekst is a string, the ith member of the string can be accessed using tekst[i]. Instead, you have used tekst(i) which means you are trying to call a function named tekst, which does not exist. Hence the NameError.

So far you can check the below code to correct the syntax. Remember that indentation for Python play very important role which has not been correctly used by your code. You have to use here [].
tekst = input("Enter your word: ")
for i in range(len(tekst)):
if tekst[-i] == tekst[-i]:
print(tekst + " is a palindrome word")
else:
print( tekst + " is not a palindrome word")
You can check the live demo here- Demo
To know how to write program for checking if a string is palindrome or not use the link here

Related

How would I print a string obtained from a user in reverse?

I'm stuck on an exercise where I must obtain a string from a user and then print it in reverse with each letter on its own line. I've done this successfully with a for loop but I was wondering how to do so without it.
user_string = input("Please enter a string: ")
for letter in (user_string)[::-1]:
print(letter)
You can reverse and use str.join to rebuild the string.
print("\n".join(reversed(input("Please enter a string: "))))
If you know how many characters there are in the string or array (calculate using the length method len()) then you could do:
while i < arr_length:
with i incrementing at the end of every round.
The rest of the code would be the same but using i as an index.
One method would be to cast the string to a list and use the list.pop() method until there are no characters left in the list.
user_input = list(input())
while len(user_input) > 0:
print(user_input.pop())
list.pop() will remove the last item in the list and return it.
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Using index property we can easily reverse a given string
a = input()
print(a[::-1])

How to change a lower case to upper case using function?

I'm trying to convert a input parameter to capital case.
text = input("write anything you wish you change to capital case: ")
def case_change():
text.upper()
print(case_change(text))
You are not asking for an argument in the function case_change, but passing in text as an argument to it while calling case_change
Try:
text = input("write anything you wish you change to capital case: ")
def case_change(text):
return text.upper()
upper_case = case_change(text)
print("capital case is: "+upper_case)

Python3 reversing an inputed sentence

I am trying to create a function that reverses a sentence that a user inputs but when I run the program I am not getting the sentence in reverse. Bellow is my code
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=sentence.split()
newsentence=words.reverse()
return (newsentence)
print(sentence_reverse(sentence))
def sentence_reverse(s):
return ' '.join(s.split()[::-1])
print(sentence_reverse(sentence))
you can do this
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
or :
def reverse2(s):
return s[::-1]
reverse() is an in-place operation, meaning it reverses words itself and doesnt return anything. So instead of returning newsentence, you want to return words like so:
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=sentence.split()
words.reverse()
return words
print(sentence_reverse(sentence))
>>>Enter a sentence: hello world
>>>['world', 'hello']
Here is a simplest way to solve your problem:
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words= sentence.split() # breaks the sentence into words
rev_sentence= ''
for word in words:
rev_sentence = ' ' + word + rev_sentence
return rev_sentence
print(sentence_reverse(sentence))
Input: Hi please reverse me
Ouput: me reverse please Hi
Hope this helps you. Kindly let me know if anything else is needed.
Welcome to StackOverflow!
The reason is because you are using split() but it does not convert your input string into the list of its character. It just make a list with one element, which is your input string. Instead, convert the string to list using list() function, and then convert it back to string using join() function. In addition to that, reverse() returns nothing. So, you have to returns the words variable instead.
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=list(sentence)
words.reverse()
return ''.join(words)
print(sentence_reverse(sentence))

How to get my Python program to pass an online grading system?

Question:
The hand is displayed.
The user may input a word or a single period (the string ".")
to indicate they're done playing
Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
When a valid word is entered, it uses up letters from the hand.
After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
The sum of the word scores is displayed when the hand finishes.
The hand finishes when there are no more unused letters or the user inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
I am trying to write a code for my Python programming online course. However, I am getting an error :
ERROR: Failed to display hand correctly - be sure 'Current Hand' and the display of the hand are on the same line!
Here is my code :
def playHand(hand, wordList, n):
total = 0
while True:
print("\nCurrent Hand:",)
displayHand(hand)
entered = input('Enter word, or a "." to indicate that you are finished: ')
if entered == '.':
print ("Goodbye! Total score: " + str(total) +" points.")
break
if isValidWord(entered, hand, wordList) == False:
print ("Invalid word, please try again.")
else:
total += getWordScore(entered, n)
print (str(entered), "earned", getWordScore(entered,n), "points. Total:", str(total))
hand = updateHand(hand, entered)
if calculateHandlen(hand) == 0:
print ("\nRun out of letters. Total score: " + str(total) +" points.")
break
The answer is in your code already:
def displayHand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
Use end=" " in your print statement!!

using .find for multiple letters in a string

I'm working on a hobby project. I'm attempting to make a hangman game in Python. So far everything works nice. There's just one problem. If I type a letter that appears in the word two times, I can't get the second letter to appear. I've been toying around with string.find and string.count methods but to no avail. Does anyone have an idea how I would go about doing this? I'm stumped.
#!bin/bash/python
import os
import time
word = 'megalopolis'
l = len(word)
list = []
n=0
while n!=l:
list.append('-')
n+=1
os.system('cls' if os.name=='nt' else 'clear')
print list
i=3
while i!=0:
x = raw_input('Enter a letter: ')
if x in word and x!='':
print 'Good choice!'
count=word.count(x)
loc=word.find(x)
print count
print loc
list[loc]=x
os.system('cls' if os.name=='nt' else 'clear')
if '-' not in list:
break
print list
else:
print 'Sorry...'
i-=1
if i==2:
print 'You have '+`i`+' more chances.'
if i==1:
print 'You have '+`i`+' more chance!'
time.sleep(1)
os.system('cls' if os.name=='nt' else 'clear')
print list
if '-' not in list:
print 'YOU WIN!!'
else:
print 'GAME OVER!!'
x = raw_input('press enter')
If you just need the index of every character occurence:
indexes = [idx for idx, ch in enumerate(word) if ch == x]
Perhaps you should use Unidecode to keep the accents in words, it might be useful depending on the language (if not English). Also, you can use str.lower() or str.upper() methods to ensure every word and trial is in the same case.
The string module has useful constants for you (e.g. ascii_uppercase).
However, in this game you don't need to worry about any index. I've made another version for you:
#!/usr/bin/env python
from string import ascii_uppercase
word = "megalopolis".upper() # Top-secret!
trial = 3 # Total trials available (number of mistakes to lose the game)
typed = set() # Typed characters
word_letters = set(word)
while trial:
print
print "".join(ch if ch in typed else "-" for ch in word)
# Winning condition
if typed.issuperset(word_letters):
break
# Data input
x = raw_input("Enter a letter: ").upper()
# Error cases
if len(x) != 1:
print "Invalid input."
continue
if x in typed:
print "Already typed."
continue
if x not in ascii_uppercase:
print "What you typed isn't a letter."
continue
# Valid data cases
typed.add(x)
if x in word:
print "Good choice!"
else:
print "{} not found!".format(x),
trial -= 1
if trial == 1:
print "You have one more chance!"
elif trial > 1:
print "You have {} more chances.".format(trial)
else:
print 'Sorry...'
# Ending message
print
if trial:
print "YOU WIN!!"
else:
print "GAME OVER!!"
Hashbang: Your shebang should usually start with "#!/". You're probably using Windows, so the "bin" as a relative directory wasn't used by you.
"l" / l as a variable name should be avoided! It might be seen as one or lower "L" (PEP8), or even a pipe "|". PS: At the beginning of this item, I typed the same letter here twice.
There's no need to use "list" as a variable name here, and you shouldn't do, as that's a built-in name.
Multiplication like "txt" * 3 returns "txttxttxt" (it repeats the data) for both strings and lists
Neither "cls" nor "clear" worked here, showing
"TERM environment variable not set."
instead of clearing the console screen. I replaced these with an empty
"print", and removed the time sleep. Look for subprocess if you want to call something from console (although I'd also look for curses if there's a need to do some CLI visualization).
Suppose x is a string. When x == "", bool(x) is False, else bool(x) is True.
Suppose x is an integer. When x == 0, bool(x) is False, else bool(x) is True.
Avoid backticks (`). No one uses them today in Python, they doesn't exist in Python 3 and you can use the repr built-in instead. However, you probably wanted something like str(trial), "%d" % trial or "{}".format(trial).
The last "press enter" probably has to do with an operating system "auto-close-after-finish" behaviour, but you [at least] didn't need to store it in x.
I've used a generator expression. You should read here about list comprehensions if the "for" in the middle of one line is confusing for you. Python developers use generator expressions and list comprehensions all the time, you shouldn't avoid learning about them.
I replaced the original winning evaluation to a comparison between the set of characters the word originally has and the set of typed characters (both uppercase).
If there's something here you didn't understand, please ask a new question.
This SO question ought to cover it for you:
Finding multiple occurrences of a string within a string in Python
It should work just as well for individual characters as strings, considering how easy it is to form the second from the first.
So in the end, I wound up doing it this way:
if x in word and x!='':
count=word.count(x)
loc=0
while count==1 or count>1:
loc=word.find(x,loc)
list[loc]=x
loc+=1
count-=1
print 'Good choice!'
Thanks for your help everyone. I definitely learned something.

Resources