What is wrong with this tiny python program? - python-3.x

I'm completely new to python and have been trying to experiment with things that I've been learning as I learn them. One of these things is using if statements. As you can see, when you run the program and input the correct answer which is 11 you will get a "yes!" message. Or else you will get a message that tells you the number you input plus 33 is not 44. However, when I input the correct answer (11) it still tells me that 11 + 33 is not 44. Curious why this is & if I am missing something?
num_in = input("what + 33 is 44?: ")
set_num = str(22 + 11)
if(num_in + set_num == str(44)):
print(" Yes!")
else:
print(num_in + " + " + set_num + " is not 44.")

+ operator has different meanings for different types. For str it is concatenation, for int add operation in math:
>>> 11 + 22
33
>>> "11" + "22"
'1122'
In your particular case try to use int everywhere where integer type variable is needed, and format output if necessary:
num_in = int(input("what + 33 is 44?: "))
set_num = 22 + 11
if num_in + set_num == 44:
print("Yes!")
else:
print("{} + {} is not 44.".format(num_in, set_num))

Here, num_in and set_num are strings, and string concatenation doesn't follow math. Here, let num_in is "11" and set_num is "33" then set_num+num_in is "3311" which is not str(44), just take int values
Edited code:
num_in = int(input("what + 33 is 44?: "))
set_num = 33
if(num_in + set_num == 44):
print(" Yes!")
else:
print(f"{num_in} + {set_num} is not 44.")

Related

Can't print a number despite using str/int

I'm a noob trying to learn python 3 and I'm trying to include the half_age as a string without using directly writing the number 9 as a string but I couldn't figure it out.
I've tried:
print = str(18//2)
print = int(18//2)
print = float(18/2)
my_age = 18
half_age = (18//2)
name = "Kenny!"
greeting = "Kia Ora, "
print(greeting + name)
print("Your age is " + my_age + "and half your age is " + str(half_age ))
print("Your age is " + my_age + "and half your age is " + str(half_age ))
TypeError: can only concatenate str (not "int") to str
Try formatting all of your numbers with str ie.
my_age = 18
half_age = (18//2)
name = "Kenny!"
greeting = "Kia Ora, "
print(greeting + name)
print("Your age is " + str(my_age) + " and half your age is " + str(half_age))
Just use modern f-strings:
my_age = 18
half_age = (18//2)
name = "Kenny"
greeting = "Kia Ora"
print(f'{greeting}, {name}!')
print(f"Your age is {my_age} and half your age is {half_age}")
or
print(f"Your age is {my_age} and half your age is {my_age/2}")

python pyparsing scanString - wrong start/end location

I'm trying to find the start and end location of a typical token in a text with the scanString function.
text = """
P: INT;
timer2.et == 3423
Q : INT ;
TIME1: TIME;
TIME2: TIME;
TIMER_Q3 : BOOL;
WECHSEL : BOOL;
m : BOOL;
timer.q = 4
"""
From this text I want to find the location of the XXX.et and the XXX.q tokens:
import pyparsing as pp
TK_TIMER_Q_ET = pp.Word(pp.alphanums + "_") + (pp.Literal(".q") | pp.Literal(".et"))
t_end = []
t_match = []
t_start = []
for match, start, end in TK_TIMER_Q_ET.scanString(text):
t_match.append(match)
t_start.append(start)
t_end.append(end)
i = len(t_match) - 1
k = 0
while k <= i:
print("t_end=", t_end[k])
print("t_start=", t_start[k])
print("t_match=", t_match[k])
print("match=", text[t_start[k]:t_end[k]])
k += 1
As an output I expect "timer2.et" and "timer.q" when I print "match=...", but I get:
t_end= 35
t_start= 26
t_match= ['timer2', '.et']
match= 423
Q
t_end= 189
t_start= 182
t_match= ['timer', '.q']
match=
Would be awesome if somebody could help me with that issue!
What you are missing is the grouping of the characters to make one identifier. Try changing the code the following way:
K_TIMER_Q_ET = pp.Group(pp.Word(pp.alphanums + "_") + (pp.Literal(".q") | pp.Literal(".et")))
Works for me:
('t_end=', 27)
('t_start=', 18)
('t_match=', ([(['timer2', '.et'], {})], {}))
('match=', 'timer2.et')
('t_end=', 153)
('t_start=', 146)
('t_match=', ([(['timer', '.q'], {})], {}))
('match=', 'timer.q')

character counter in Python 3 without built in functions

So I have to create a program that reads a paragraph from Romeo & Juliet and returns the number of characters, number of spaces, number of words, and the top 3 most common characters without the use of built in functions such as counter. I made this program to use parallel lists to count unique characters and add a tally into the second list. My problem lies in being able to pick out the top three and print the two lists (i.e. "A 3").
This is the txt file the program reads:
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
This is the program I have so far:
charCount = []
uniqueChar = []
char_count = 0
word_Count = 0
space_count = 0
Open_File = open("romeo.txt")
for romeo in Open_File:
for char in romeo:
if (char == ' ' or char == '.'):
word_Count += 1
if (char == ' '):
space_count += 1
if (char != ' ' and char != '\n'):
char_count += 1
if (char not in uniqueChar):
uniqueChar.append(char)
charCount.append(1)
else:
for j in range(len(uniqueChar)):
if (uniqueChar[j] == char):
charCount[j] += 1
print("Spaces: ", space_count)
print("Char: ", char_count)
print("Words: ", word_Count)

Python while/if statements not working

I am currently learning Python and I am trying to get this game to work. Basically I assigned a word to be guessed and then sliced the word and assigned it to several other variables. Basically, each variable assigned as "letterx" is a letter which makes up part of the string variable word. The problem is getting the while statement with nested if statements to work. For some reason I can't get the guess input to equal letterx. All I get when I run the code is "No." and then the amount of turns left. However, I can't get the elif statement to work. Pretty much everything else works. I'm used to programming in Java and I am fairly new to Python so any tips or help would be greatly appreciated. Thank you for your time and help! Here's the code:
#Guess The Word
word = "action"
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
print("Welcome to Guess the Word!\n")
count = 6
while(count != 0):
guess = input("Take a guess: \n")
if(guess != letter1 or guess != letter2 or guess != letter3 or guess !=
letter4 or guess != letter5 or guess != letter6):
count -= 1
print("No.\n")
print("Turns left: \n", count)
elif(guess == letter1 or guess == letter2 or guess == letter3
or guess == letter4 or guess == letter5 or guess == letter6):
count -= 1
print("Yes.\n")
if(count == 0):
print("Your turns are up, what do you think the word is?")
guess = input("The word is...: \n")
if(guess == word):
print("You win! That's the word")
elif(guess != word):
print("Sorry, you lose.")
Here's the program running in the Python shell:
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Welcome to Guess the Word!
Take a guess:
a
No.
Turns left:
5
Take a guess:
c
No.
Turns left:
4
Take a guess:
t
No.
Turns left:
3
Take a guess:
i
No.
Turns left:
2
Take a guess:
o
No.
Turns left:
1
Take a guess:
n
No.
Turns left:
0
Your turns are up, what do you think the word is?
The word is...:
action
You win! That's the word
Let's say guess equals letter1. Then even though
guess == letter1, the first condition is still True since guess != letter2. And similarly, no matter what guess is, there is some letter (amongst letter1, letter2, etc.) which it is not equal.
So the first if condition is always True.
Instead, you could use
while(count != 0):
guess = input("Take a guess: \n")
if not guess in word:
count -= 1
print("No.\nTurns left: \n", count)
else:
count -= 1
print("Yes.\n")
By the way, it should be entirely possible to code the game without defining letter1, letter2, etc. All this code should be deleted:
letter1 = ""
letter2 = ""
letter3 = ""
letter4 = ""
letter5 = ""
letter6 = ""
position1 = 0
position2 = 1
position3 = 2
position4 = 3
position5 = 4
position6 = 5
letter1 += word[position1]
letter2 += word[position2]
letter3 += word[position3]
letter4 += word[position4]
letter5 += word[position5]
letter6 += word[position6]
Just use word[0] in place of letter1, and word[1] in place of letter2, etc.
And note you may not even need word[0], word[1]. For example,
with Python you can use
guess in word
instead of
guess in (word[0], word[1], word[2], word[3], word[4], word[5])
It's not only a lot less typing, it is more general, since guess in word does the right thing with words of any length.

Why am I getting incorrect values for string length?

My professor is teaching us Scala using Horstmann's book "Scala for the impatient", and one of our homework exercises are straight from the book; Chapter 4, exercise 2.
We are expected to read in the eBook in text format, the professor has specified that the input file should be "Moby Dick", available for free from the Guttenberg project here: http://www.gutenberg.org/ebooks/2701.txt.utf-8
My code works, as far as counting instances of words. However, he has added the requirement that we must we must format the output in two two columns, with words left justified, and counts right justified. To do so, I am determining the longest word in the book so I can figure the width of the "word" column. However, the values I am getting for the length of the strings is just wrong. In fact, it tells me that all the strings are the same length. "a" is being reported as length 26, just as is "Whale", "Ishmael", etc...
Here's the code:
object Chapter4Exercise2 extends App {
//for sorting
import util.Sorting._
//grab the file
val inputFile = new java.util.Scanner(new java.io.File("moby.txt"))
//create a mutable map where key/values == word/count
val wordMap = collection.mutable.Map[String, Int]() withDefault (_ => 0)
//for formatting output (later), the longest word length is relevant
var longestWord = 0
var theWord: String = ""
//start reading each word in the input file
while (inputFile hasNext) {
//grab the next word for processing, convert it to lower case, trim spaces and punctuation
var nextWord = inputFile.next().toLowerCase().trim().filter(Character.isLetter(_))
//if it's the longest word, update both theWord and longestWord
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
//update the map value for the key with same value as nextWord
wordMap(nextWord) += 1
}
println("Longest word is " + theWord + " at " + longestWord + " Characters")
}
The output of these lines:
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
and
println("Longest word is " + theWord + " at " + longestWord + " Characters")
is way off. It's telling me that EVERY word in the input file is 26 characters long!
Here's a small sample of what's being output:
husks 26
on 26
a 26
surfbeaten 26
beach 26
and 26
then 26
diving 26
down 26
into 26
What am I missing/doing wrong?
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
You shouldn't write multiple statements on a single line like that. Let's write this out in multiple lines and properly indent it:
if (nextWord.size > longestWord)
longestWord = nextWord.size
theWord = nextWord
println(theWord + " " + longestWord)
Do you see the problem now?
Try putting { and } around your if statement alternatives.
You can avoid this kind of pitfall by formatting your code in a structured manner - always using braces around code blocks.
if (nextWord.size > longestWord)
{
longestWord = nextWord.size;
theWord = nextWord;
println(theWord + " " + longestWord);
}
Your current code is equivalent to
if (nextWord.size > longestWord)
{
longestWord = nextWord.size;
}
theWord = nextWord;
println(theWord + " " + longestWord);

Resources