Python Blackjack Run module IDLE error? - python

I try to run the following module written for a blackjack 21 game in Python but get an error saying:
Unindent does not match any outer indentation level.
Questions
Please help resolve the error.
Also is there a stable option to run modules and get them checked with a python checker which I know there is but an easy to use one without adding code in python , just running it to check where the code got broken?
example
if the screenshot is unclear:
koloda = [6,7,8,9,10,2,3,4,11] * 4
import random
random.shuffle(koloda)
print(' Lets play blackjack, shall we? ')
count = 0
while True:
choice = input(' Will you pick another card? y/n\n ')
if choice == ' y ':
current = koloda.pop()
print(' You got a higher card %d ' %current)
count += current
if count > 21:
print(' Sorry, you lost ')
break
elif count == 21:
print(' Congrats, you got 21! ')
break
else:
print(' You have %d points. ' %count)
elif choice -- 'n':
print(' You have %d points and you ended this game. ' %count)
break
print('See you again!')
Thanks in advance

Your indentations are inconsistent. In python, you can choose how you indent blocks (e.g. tabs, 4 spaces, 3 spaces...), but you should always stick to your initial choice. Otherwise you'll get indentation errors.
Regarding your other question, there are many IDEs that will report syntax errors (such as the ones in your code) while writing. I like Pycharm, but you can choose anything you like. PyCharm also has an option to convert indentation between spaces and tabs, which can help you fix your code.

Related

User inputs reserved keyword in Python. There happens an error

I am working on a simple program (just for a joke). A program wants that the user input yes or no (it can be in different languages). But when he enters a reserved word (i. e. keyword) there happens an error because this keyword does some bugs in the code.
My truncated code (maybe it seems unclear because it's truncated):
x = input('Enter yes or no (you can do this in different languages...) ')
x = x.lower()
answersYes = ['yes','si','oui','ioe','inde','tak','ja','da']
answersNo = ['no','ayi','che','leai','nie','ne','nein']
if ' ' in x:
print('Input just one word!')
else:
if x in answersYes:
print('You enteres YES!')
elif x in answersNo:
print('You enteres NO!')
else:
print('Sorry, but this isn\'t YES nor NO!')
I have done some googling around, but there was no luck yet.
Thank you a lot for any answer!
P.S.
Just one little note:
When I have run the upper script in Python in basic Python IDLE, there wasn't any error, but when I have run this in Spyder, there displayed this message (when I typed 'yes in no' ("in" is a reserved word)):
File "<ipython-input-49-d1e48c3ddecb>", line 1
yes in no
^
SyntaxError: invalid syntax
I don't get an error. Make sure your spyder is python3-configured or try running with python3 file.py
You can also try replacing input() with raw_input()

python identation error not expected

I am trying to solve this problem many times but I am not able to solve i tried everything but it shows error message everytime
a=int(input('enter the first number')) #we ask for input
b=int(input('enter the second number'))
while True:
choice=int(input('enter the number corresponding to the operation you want to \nperform \n1)addition \n2)subtraction \n3)multiplication \n4)division '))
#we ask for the user choice
if choice==1: #if the user opts for addition
addition=a+b
print(f'the addition of the 2 numbers is {addition} ') #ans
ans=input('want to try another operation? yes or no')
if ans=='yes': #if the user whishes to use another operation
continue
else: #if the user opts out
print('thank you for using')
break
elif choice==2:
subtraction=a-b #same for others but diffrent opperation
print(f'the subtraction of the 2 numbers is {subtraction} ')
ans=input('want to try another operation? yes or no')
if ans=='yes':
continue
else:
print('thank you for using')
break
elif choice==3:
multiplication=a*b
print(f'the multiplication of the 2 numbers is {multiplication} ')
ans=input('want to try another operation? yes or no')
if ans=='yes':
continue
else:
print('thank you for using')
break
else:
division=a//b
remainder=a%b
print(f'the division of the 2 numbers is {division} \nand the remainder is{remainder} ')
ans=input('want to try another operation? yes or no')
if ans=='yes':
continue
else:
print('thank you for using')
break
the error message is
File "calc_of_2_nos.py", line 15
break
^
IndentationError: unindent does not match any outer indentation level
I don't know how to solve this problem I think I have indentated it perfectly four spaces
This happens to me in Sublime Text sometimes if I mix up tabs and spaces. I am answering specifically for Sublime Text because that is what you say you are using in the comments.
In Sublime Text, when you highlight whitespace you can actually see if it is a tab or a space, like this:
Notice the two arrows on the left. Where you see dots, there are spaces, and where you see lines, there's a tab.
To make your spacing consistent, I recommend that you either go back through manually and delete and then manually and consistently re-indent your code, or use a linter to redo the indentation. Sublime Text provides some tools for this (view -> indentation -> *), and tools exist online.
Another trick in Sublime Text that can help is to search the file for tabs and replace them with (for spaces).
I could not find any error.You might want to add a newline after division in your menu choice, else its perfect!

Python 3 syntax error invalid syntax

With this code I am trying to generate simple multiplication tables. The program should ask for input and multiple that number in a range up to 15 and the generate the multiplication table for the number. After the if_name_ == 'main': line I end up with a syntax error after the colon. I normally program in python 2, so python 3 is a bit new to me but I'm not sure what the difference is. Below I have listed the short but full code. Any help would be much appreciated.
'''Multiplication Table'''
def multi_table(a):
for i in range(1,16):
print(' {0} x {1} = {2} '.format(a, i, a*i))
if_name_ == '_main_':
a = input('Enter a number: ')
multi_table(float(a))
if_name_ == '_main_':
a = input('Enter a number: ')
multi_table(float(a))
should be :
if __name__ == "__main__":
a = input('Enter a number: ')
multi_table(float(a))
Notice that both variable __name__ and __main__ has two underscores around them and that there must be a space between the if keyword and the start of the condition.
As #Maroun Maroun said right, it has to be if __name__ == "__main__" . But you wont need it. Just write it at the bottom :
'''Multiplication Table'''
def multi_table(a):
for i in range(1,16):
print(' {0} x {1} = {2} '.format(a, i, a*i))
a = input('Enter a number: ')
multi_table(float(a))
Should work, too.
EDIT: In the official docs :
https://docs.python.org/3/library/main.html
if __name__ == "__main__":
In the example provided, (i) there's a space missing after if, and (ii) the symbol's name should have two pairs of underscores: __name__. If these two corrections resolve your problem, great.
But in case you still have another more mysterious unresolved syntax error, then read on...
Recently I encountered a very similar error message, and it was hard to root-cause, since the error message seems to point in the wrong direction. The error seems to indicate that the syntax error lies at the end of the if statement. However, with Python 3.x I noticed that in case a parentheses mismatch error happens in a python source file, the error might be reported at the beginning of the next block rather than where the mismatch actually occurs.
It's worth checking for mismatched parentheses in the entire source code file, prior to the if statement. Check if all your (s are matched by a closing ).

How to verify numbers in input with python?

I'm trying to learn how to program and I'm running into a problem....
I'm trying to figure out how to make sure someone inputs a number instead of a string. Some related answers I found were confusing and some of the code didn't work for me. I think someone posted the try: function, but it didn't work, so maybe I need to import a library?
Here's what I'm trying right now:
Code:
print "Hi there! Please enter a number :)"
numb = raw_input("> ")
if numb != str()
not_a_string = int(next)
else:
print "i said a number, not a string!!!"
if not_a_string > 1000:
print "You typed in a large number!"
else:
print "You typed in a smaller number!"
Also I have another question while I'm asking. How can I make it so it will accept both uppercase and lower case spellings? In my code below, if I were to type in "Go to the mall" but with a lowercase G it would not run the if statement because it only accepts the capital G.
print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")
if answer == "Go to the mall":
print "Awesome! Let's go!"
elif answer == "Get lunch":
print "Great, let's eat!"
elif answer == "Go to sleep":
print "Time to nap!"
else:
print "Not what I had in mind...."
Thanks. ^^
Edit: I'm also using python 2.7 not 3.0
You can do something like this:
while True: #infinite loop
ipt = raw_input(' Enter a number: ')
try:
ipt = int(ipt)
break #got an integer -- break from this infinite loop.
except ValueError: #uh-oh, didn't get an integer, better try again.
print ("integers are numbers ... didn't you know? Try again ...")
To answer your second question, use the .lower() string method:
if answer.lower() == "this is a lower case string":
#do something
You can make your string comparisons really robust if you want to:
if answer.lower().split() == "this is a lower case string".split():
In this case, you'll even match strings like "ThIs IS A lower Case\tString". To get even more liberal in what you accept, you'd need to use a regular expression.
(and all this code will work just fine on python2.x or 3.x -- I usually enclose my print statements in parenthesis to make it work for either version).
EDIT
This code won't quite work on python3.x -- in python3, you need to change raw_input into input to make it work. (Sorry, forgot about that one).
First,you should ask only one question per post.
Q1: use built-in .isdigit()
if(numb.isdigit()):
#do the digit staff
Q2:you can use string.lower(s) to solve the capital issue.
you may try
numb = numb.strip()
if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
# process numb

Beginner: While loop not functioning properly, syntax errors, displays nothing

I am working through some Looping exercises, While statements in particular. Here are the instructions:
2.2) Modify the program so that it asks users whether they want to guess again each time. Use two variables, number for the number and answer for the answer to the question whether they want to continue guessing. The program stops if the user guesses the correct number or answers "no". (In other words, the program continues as long as a user has not answered "no" and has not guessed the correct number.)
Here is my code:
#!usr/bin/env python
#
#While statement
number = 24
while number != 24:
answer = raw_input("Guess my lucky number! Do you want to keep guessing?")
if number == 24:
print "You got it! That is great!"
elif answer == "no":
print "Thank you for playing."
else:
print "That is not the right answer! Try again."
When I run the module in IDLE, the end quote of That is great!" - becomes red and says invalid syntax. In terminal if I run $ python while.py nothing loads. I've tried writing this as Python 3 functions with print("") but it still does not run.
Thanks to anyone who can help with this.
The while-cycle is never entered because the condition number != 24 never holds.
This is why there is no output.
Your loop never executes because you state that number = 24, and then right after, your while loop will only start if number != 24.
In addition, raw_input will yield a string, not an int so either ask for "24" or cast the raw_input to an int.
It also seems that you don't actually give the user a chance to guess the number at all; you only ask the user if s/he wants to keep playing.
You might want to do something like this:
number = 24
answer = ""
while answer != str(number):
answer = raw_input("Guess my lucky number, or type 'no' to quit.")
if answer == "no":
print "Okay, see you later"
break
elif answer != str(number):
print "wrong number"
if answer == str(number):
print "you got it right"
Here's the syntax issues:
answer = ""
while answer != "24":
answer = raw_input("Guess my lucky number! Do you want to keep guessing?")
if answer == "24":
# You can fill in the rest ...
Well, I don't want to straight out solve it for you, but take a look at your conditional in the while loop. Think about what happens, line-by-line, when you run it, particularly in the "number" variable.
The other answers are touching on the problem but there are more...
Yes you really should be checking the answer variable in your loop instead of the number variable, but also keep in mind that raw_input is going to give you a string. So you will not get an int 24, you will get a string "24". The idea here is to take the answer variable from raw_input and check that variable against both your number and the value "no"
number = "24"

Categories